lactea-render 0.3.1

wgpu backend reproducing the MilkDrop 2 frame pipeline; host-provided device, renders into any texture.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// SPDX-FileCopyrightText: 2026 Gianluca Boiano
// SPDX-FileCopyrightText: 2005-2013 Nullsoft, Inc.
// SPDX-License-Identifier: (MIT OR Apache-2.0) AND BSD-3-Clause

//! Built-in WGSL: fixed-function replacements, blur passes, final blit, and the vertex shader
//! shared with user warp / composite shaders.

/// A GLSL-style full-screen triangle for modules that draw one without vertex buffers: WGSL `fullscreen_tri(vi)`
/// gives the clip-space corner of vertex `vi` (0..3). Expands to a string literal so it can be `concat!`ed.
macro_rules! fullscreen_tri_fn {
    () => {
        r#"
fn fullscreen_tri(vi: u32) -> vec2<f32> {
    var p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
    return p[vi];
}
"#
    };
}
pub(crate) use fullscreen_tri_fn;

/// Vertex shader for every `MeshVertex` pass (warp, composite, textured fills). Output layout
/// matches `lactea_abi::WGSL_COMMON`'s `VsOut` (locations 0..2 + position).
pub fn mesh_vs() -> String {
    mesh_vs_src(String::new(), String::new())
}

/// The mesh vertex stage: `members` / `stmts` add the fold varyings (see [`fold_members`], [`fold_stmts`]).
fn mesh_vs_src(members: String, stmts: String) -> String {
    format!(
        r#"
struct VOut {{
    @builtin(position) position: vec4<f32>,
    @location(0) diffuse: vec4<f32>,
    @location(1) uv: vec4<f32>,
    @location(2) rad_ang: vec2<f32>,
{members}}};
@vertex
fn vs_main(@location(0) pos: vec2<f32>, @location(1) diffuse: vec4<f32>,
           @location(2) uv: vec4<f32>, @location(3) rad_ang: vec2<f32>) -> VOut {{
    var o: VOut;
    o.position = vec4<f32>(pos, 0.0, 1.0);
    o.diffuse = diffuse;
    o.uv = uv;
    o.rad_ang = rad_ang;
{stmts}    return o;
}}
"#
    )
}

/// projectM's warp vertex shader (`PresetWarpVertexShaderGlsl330.vert`), statement for statement, so the GPU's own
/// `pow` / `sin` / `cos` and its multiply-add fusion produce the same UVs as projectM's GL driver.
/// `group` is the bind group of [`WarpVsUniforms`]. Output layout = [`mesh_vs`] (`VsOut`).
pub fn warp_vs(group: u32) -> String {
    warp_vs_src(group, false, 0)
}

/// The same vertex stage, but every vertex is drawn as a point into texel `(i % (gx+1), i / (gx+1))` of a
/// `(gx+1) x (gy+1)` target (`wu.diffuse.xy` = `(gx+1, gy+1)`), with the fragment stage `fs_probe` writing
/// `uv.xy`: reads the GPU's own per-vertex UVs back (what projectM's `RG16F` UV map interpolates).
pub fn warp_uv_readback(group: u32) -> String {
    warp_vs_src(group, true, 0)
}

/// `lactea_abi::WGSL_COMMON` followed by every fold function: the declarations a fold vertex stage shares with the
/// user fragment shader (`mu` / `mx` / `pu`, `fold_k`).
fn fold_prelude(folds: &[String]) -> String {
    let mut s = String::from(lactea_abi::WGSL_COMMON);
    for f in folds {
        s.push('\n');
        s.push_str(f);
    }
    s.push('\n');
    s
}

/// `@location(3 + j) fold{j}: vec4<f32>,` members of a vertex output struct, `ceil(n / 4)` of them.
fn fold_members(n: usize) -> String {
    (0..n.div_ceil(4))
        .map(|j| format!("    @location({}) fold{j}: vec4<f32>,\n", 3 + j))
        .collect()
}

/// Statements filling `o.fold{j}` from `o.uv`, `o.rad_ang`, `o.diffuse`: component `k % 4` of `fold{k / 4}` is
/// `fold_k(..)`, the unused components of the last vec4 are 0.
fn fold_stmts(n: usize) -> String {
    let mut s = String::new();
    for j in 0..n.div_ceil(4) {
        let comps: Vec<String> = (0..4)
            .map(|c| {
                let k = 4 * j + c;
                if k < n {
                    format!("fold_{k}(o.uv, o.rad_ang, o.diffuse)")
                } else {
                    "0.0".into()
                }
            })
            .collect();
        s.push_str(&format!(
            "    o.fold{j} = vec4<f32>({});\n",
            comps.join(", ")
        ));
    }
    s
}

/// [`mesh_vs`] plus the fold varyings: module text = `WGSL_COMMON`, the fold functions and a vertex stage with the
/// same attributes, entry name and varyings 0..2 whose output also carries `fold{j}` (locations `3 + j`).
pub fn mesh_vs_folds(folds: &[String]) -> String {
    format!(
        "{}{}",
        fold_prelude(folds),
        mesh_vs_src(fold_members(folds.len()), fold_stmts(folds.len()))
    )
}

/// [`warp_vs`] plus the fold varyings (see [`mesh_vs_folds`]); the warp math is the same text. `group` must not be
/// 0 or 1, which `WGSL_COMMON` uses.
pub fn warp_vs_folds(group: u32, folds: &[String]) -> String {
    format!(
        "{}{}",
        fold_prelude(folds),
        warp_vs_src(group, false, folds.len())
    )
}

/// `n_folds` extra `fold{j}` outputs (see [`warp_vs_folds`]); the module must then declare the fold functions.
fn warp_vs_src(group: u32, probe: bool, n_folds: usize) -> String {
    let (vid_param, position) = if probe {
        (
            ", @builtin(vertex_index) vid: u32",
            "let gw = u32(wu.diffuse.x);\n    \
             o.position = vec4<f32>((f32(vid % gw) + 0.5) / wu.diffuse.x * 2.0 - 1.0, \
             1.0 - (f32(vid / gw) + 0.5) / wu.diffuse.y * 2.0, 0.0, 1.0);",
        )
    } else {
        (
            "",
            "// glm::ortho(-1, 1, 1, -1): y is flipped\n    o.position = vec4<f32>(pos.x, -pos.y, 0.0, 1.0);",
        )
    };
    let fs = if probe {
        r#"
@fragment
fn fs_probe(in: VOut) -> @location(0) vec4<f32> {
    return vec4<f32>(in.uv.xy, 0.0, 0.0);
}
"#
    } else {
        ""
    };
    format!(
        r#"
struct WarpVsUniforms {{
    aspect: vec4<f32>,     // aspectX, aspectY, invAspectX, invAspectY
    timing: vec4<f32>,     // warpTime, warpScaleInverse, texelOffset.x, texelOffset.y
    factors: vec4<f32>,    // warpFactors
    diffuse: vec4<f32>,    // frag_COLOR (decay or 1)
}};
@group({group}) @binding(0) var<uniform> wu: WarpVsUniforms;

struct VOut {{
    @builtin(position) position: vec4<f32>,
    @location(0) diffuse: vec4<f32>,
    @location(1) uv: vec4<f32>,
    @location(2) rad_ang: vec2<f32>,
{members}}};

@vertex
fn vs_main(@location(0) pos: vec2<f32>, @location(1) rad_ang: vec2<f32>, @location(2) transforms: vec4<f32>,
           @location(3) warp_center: vec2<f32>, @location(4) warp_distance: vec2<f32>,
           @location(5) stretch: vec2<f32>{vid_param}) -> VOut {{
    let radius = rad_ang.x;
    let zoom = transforms.x;
    let zoom_exp = transforms.y;
    let rot = transforms.z;
    let warp = transforms.w;
    let aspect_x = wu.aspect.x;
    let aspect_y = wu.aspect.y;
    let inv_aspect_x = wu.aspect.z;
    let inv_aspect_y = wu.aspect.w;
    let warp_time = wu.timing.x;
    let warp_scale_inverse = wu.timing.y;
    let texel_offset = wu.timing.zw;
    let wf = wu.factors;

    var o: VOut;
    {position}

    let zoom2 = pow(zoom, pow(zoom_exp, radius * 2.0 - 1.0));
    let zoom2_inverse = 1.0 / zoom2;

    var u = pos.x * aspect_x * 0.5 * zoom2_inverse + 0.5;
    var v = pos.y * aspect_y * 0.5 * zoom2_inverse + 0.5;

    let uv_original = vec2<f32>(pos.x * 0.5 + 0.5 + texel_offset.x,
                                pos.y * 0.5 + 0.5 + texel_offset.y);

    u = (u - warp_center.x) / stretch.x + warp_center.x;
    v = (v - warp_center.y) / stretch.y + warp_center.y;

    u += warp * 0.0035 * sin(warp_time * 0.333 + warp_scale_inverse * (pos.x * wf.x - pos.y * wf.w));
    v += warp * 0.0035 * cos(warp_time * 0.375 - warp_scale_inverse * (pos.x * wf.z + pos.y * wf.y));
    u += warp * 0.0035 * cos(warp_time * 0.753 - warp_scale_inverse * (pos.x * wf.y - pos.y * wf.z));
    v += warp * 0.0035 * sin(warp_time * 0.825 + warp_scale_inverse * (pos.x * wf.x + pos.y * wf.w));

    let u2 = u - warp_center.x;
    let v2 = v - warp_center.y;

    let cos_rotation = cos(rot);
    let sin_rotation = sin(rot);
    u = u2 * cos_rotation - v2 * sin_rotation + warp_center.x;
    v = u2 * sin_rotation + v2 * cos_rotation + warp_center.y;

    u -= warp_distance.x;
    v -= warp_distance.y;

    u = (u - 0.5) * inv_aspect_x + 0.5;
    v = (v - 0.5) * inv_aspect_y + 0.5;

    u += texel_offset.x;
    v += texel_offset.y;

    o.diffuse = wu.diffuse;
    o.uv = vec4<f32>(u, v, uv_original);
    o.rad_ang = rad_ang;
{stmts}    return o;
}}
{fs}"#,
        members = fold_members(n_folds),
        stmts = fold_stmts(n_folds),
    )
}

/// Fixed-function "texture modulate diffuse" (D3DTOP_MODULATE colour, alpha = diffuse alpha).
pub const TEX_MOD_FS: &str = r#"
@group(0) @binding(0) var tex: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;
struct FIn {
    @builtin(position) position: vec4<f32>,
    @location(0) diffuse: vec4<f32>,
    @location(1) uv: vec4<f32>,
    @location(2) rad_ang: vec2<f32>,
};
@fragment
fn fs_main(in: FIn) -> @location(0) vec4<f32> {
    let t = textureSample(tex, samp, in.uv.xy);
    return vec4<f32>(t.rgb * in.diffuse.rgb, in.diffuse.a);
}
// projectM (`TexturedDrawFragmentShader`): colour = diffuse * texel, alpha included.
@fragment
fn fs_main_ta(in: FIn) -> @location(0) vec4<f32> {
    return in.diffuse * textureSample(tex, samp, in.uv.xy);
}
"#;

/// Flat coloured geometry (`WFVERTEX`).
pub const FLAT_SRC: &str = r#"
struct VOut {
    @builtin(position) position: vec4<f32>,
    @location(0) color: vec4<f32>,
};
@vertex
fn vs_main(@location(0) pos: vec2<f32>, @location(1) color: vec4<f32>) -> VOut {
    var o: VOut;
    o.position = vec4<f32>(pos, 0.0, 1.0);
    o.color = color;
    return o;
}
@fragment
fn fs_main(in: VOut) -> @location(0) vec4<f32> {
    return in.color;
}
"#;

/// Blur passes (milkdropfs.cpp `BlurPasses`, blur1_ps.fx / blur2_ps.fx). One uniform block:
/// `c0` = source texsize + inverse, `c1` = w1..w4, `c2` = d1..d4, `c3` = (scale, bias, w_div, source offset),
/// `c5` = (w1, w2, d1, d2), `c6` = (w_div, edge_darken_c1, c2, c3).
pub const BLUR_SRC: &str = concat!(
    fullscreen_tri_fn!(),
    r#"
struct BlurParams {
    c0: vec4<f32>,
    c1: vec4<f32>,
    c2: vec4<f32>,
    c3: vec4<f32>,
    c5: vec4<f32>,
    c6: vec4<f32>,
};
@group(0) @binding(0) var<uniform> bp: BlurParams;
@group(0) @binding(1) var tex: texture_2d<f32>;
@group(0) @binding(2) var samp: sampler;

struct VOut {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};
@vertex
fn vs_main(@builtin(vertex_index) vi: u32) -> VOut {
    // full-screen triangle; uv.y = 0 at the top of the target
    let xy = fullscreen_tri(vi);
    var o: VOut;
    o.position = vec4<f32>(xy, 0.0, 1.0);
    o.uv = vec2<f32>(xy.x * 0.5 + 0.5, 0.5 - xy.y * 0.5);
    return o;
}

@fragment
fn fs_blur_h(in: VOut) -> @location(0) vec4<f32> {
    // LONG HORIZ. PASS 1 (blur1_ps.fx). "+ moves blur UP, LEFT by 1-pixel increments".
    // c3.w is the source offset in texels along y, its magnitude is the offset along x: 0 = none
    // (`CompatRules::blur_halfpixel_bias` off), +-1 = MD2's bias (sign: see `run_blur`).
    let uv2 = in.uv + bp.c0.zw * vec2<f32>(abs(bp.c3.w), bp.c3.w);
    let dx = bp.c0.z;
    var blur =
        (textureSampleLevel(tex, samp, uv2 + vec2<f32>( bp.c2.x * dx, 0.0), 0.0).xyz +
         textureSampleLevel(tex, samp, uv2 + vec2<f32>(-bp.c2.x * dx, 0.0), 0.0).xyz) * bp.c1.x +
        (textureSampleLevel(tex, samp, uv2 + vec2<f32>( bp.c2.y * dx, 0.0), 0.0).xyz +
         textureSampleLevel(tex, samp, uv2 + vec2<f32>(-bp.c2.y * dx, 0.0), 0.0).xyz) * bp.c1.y +
        (textureSampleLevel(tex, samp, uv2 + vec2<f32>( bp.c2.z * dx, 0.0), 0.0).xyz +
         textureSampleLevel(tex, samp, uv2 + vec2<f32>(-bp.c2.z * dx, 0.0), 0.0).xyz) * bp.c1.z +
        (textureSampleLevel(tex, samp, uv2 + vec2<f32>( bp.c2.w * dx, 0.0), 0.0).xyz +
         textureSampleLevel(tex, samp, uv2 + vec2<f32>(-bp.c2.w * dx, 0.0), 0.0).xyz) * bp.c1.w;
    blur = blur * bp.c3.z;
    blur = blur * bp.c3.x + bp.c3.y;
    return vec4<f32>(blur, 1.0);
}

@fragment
fn fs_blur_v(in: VOut) -> @location(0) vec4<f32> {
    // SHORT VERTICAL PASS 2 (blur2_ps.fx)
    let uv2 = in.uv;
    let dy = bp.c0.w;
    var blur =
        (textureSampleLevel(tex, samp, uv2 + vec2<f32>(0.0,  bp.c5.z * dy), 0.0).xyz +
         textureSampleLevel(tex, samp, uv2 + vec2<f32>(0.0, -bp.c5.z * dy), 0.0).xyz) * bp.c5.x +
        (textureSampleLevel(tex, samp, uv2 + vec2<f32>(0.0,  bp.c5.w * dy), 0.0).xyz +
         textureSampleLevel(tex, samp, uv2 + vec2<f32>(0.0, -bp.c5.w * dy), 0.0).xyz) * bp.c5.y;
    blur = blur * bp.c6.x;
    // tone it down at the edges (only on the 1st vertical pass)
    var t = min(min(in.uv.x, in.uv.y), 1.0 - max(in.uv.x, in.uv.y));
    t = sqrt(t);
    t = bp.c6.y + bp.c6.z * clamp(t * bp.c6.w, 0.0, 1.0);
    blur = blur * t;
    return vec4<f32>(blur, 1.0);
}
"#
);

/// Final blit of the internal Rgba8Unorm image to the host target. Nearest `textureLoad`, so
/// equal sizes copy bit-exactly; for `*Srgb` targets the value is sRGB-decoded first so the
/// hardware's linear->sRGB encode stores the original bytes.
pub const BLIT_SRC: &str = concat!(
    fullscreen_tri_fn!(),
    r#"
struct BlitParams {
    // x,y = src size, z,w = dst size
    sizes: vec4<f32>,
    // x = 1 when the target is an sRGB format
    flags: vec4<f32>,
};
@group(0) @binding(0) var<uniform> bp: BlitParams;
@group(0) @binding(1) var tex: texture_2d<f32>;

@vertex
fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
    return vec4<f32>(fullscreen_tri(vi), 0.0, 1.0);
}

fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
    let lo = c / 12.92;
    let hi = pow((c + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
    return select(hi, lo, c <= vec3<f32>(0.04045));
}

@fragment
fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
    let src = vec2<i32>(floor(pos.xy * bp.sizes.xy / bp.sizes.zw));
    let c = textureLoad(tex, clamp(src, vec2<i32>(0), vec2<i32>(bp.sizes.xy) - vec2<i32>(1)), 0);
    var rgb = c.rgb;
    if (bp.flags.x > 0.5) {
        rgb = srgb_to_linear(rgb);
    }
    return vec4<f32>(rgb, 1.0);
}

// Bilinear resample for sizes that differ (`textureLoad` x4: the source may not be filterable). `flags.y` > 0.5 keeps
// the source alpha (a feedback image), otherwise the output is opaque.
@fragment
fn fs_linear(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
    let hi = vec2<i32>(bp.sizes.xy) - vec2<i32>(1);
    let p = pos.xy * bp.sizes.xy / bp.sizes.zw - vec2<f32>(0.5);
    let p0 = floor(p);
    let f = p - p0;
    let i0 = vec2<i32>(p0);
    let a = textureLoad(tex, clamp(i0, vec2<i32>(0), hi), 0);
    let b = textureLoad(tex, clamp(i0 + vec2<i32>(1, 0), vec2<i32>(0), hi), 0);
    let c = textureLoad(tex, clamp(i0 + vec2<i32>(0, 1), vec2<i32>(0), hi), 0);
    let d = textureLoad(tex, clamp(i0 + vec2<i32>(1, 1), vec2<i32>(0), hi), 0);
    let m = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
    var rgb = m.rgb;
    if (bp.flags.x > 0.5) {
        rgb = srgb_to_linear(rgb);
    }
    return vec4<f32>(rgb, select(1.0, m.a, bp.flags.y > 0.5));
}
"#
);

/// Flash limiter: moves the previously shown frame towards the new one by at most `step.x` per colour channel
/// (`textureLoad` of both, same size). Alpha is opaque.
pub const FLASH_LIMIT_SRC: &str = concat!(
    fullscreen_tri_fn!(),
    r#"
struct LimitParams {
    // x = largest change of one channel for this frame
    step: vec4<f32>,
};
@group(0) @binding(0) var<uniform> lp: LimitParams;
@group(0) @binding(1) var src: texture_2d<f32>;
@group(0) @binding(2) var prev: texture_2d<f32>;

@vertex
fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
    return vec4<f32>(fullscreen_tri(vi), 0.0, 1.0);
}

@fragment
fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
    let xy = vec2<i32>(pos.xy);
    let want = textureLoad(src, xy, 0).rgb;
    let shown = textureLoad(prev, xy, 0).rgb;
    let d = clamp(want - shown, vec3<f32>(-lp.step.x), vec3<f32>(lp.step.x));
    return vec4<f32>(shown + d, 1.0);
}
"#
);