cranpose-render-wgpu 0.1.147

WGPU renderer backend for Cranpose
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
439
440
441
442
443
444
445
446
447
mod support;

#[path = "../src/test_support.rs"]
mod shared_test_support;

use cranpose_render_common::graph::{ProjectiveTransform, RenderGraph, RenderNode};
use cranpose_render_wgpu::CapturedFrame;
use cranpose_ui_graphics::{
    GradientBlurDirection, GraphicsLayer, Rect, RenderEffect, SubstrateSpec, gradient_blur_effect,
};
use support::{ReferenceEdge, SubstrateProbeRead, region_pixels};

const FRAME_WIDTH: u32 = 240;
const FRAME_HEIGHT: u32 = 120;
const GLASS: Rect = Rect {
    x: 40.0,
    y: 20.0,
    width: 96.0,
    height: 72.0,
};
const SUBSTRATE_RADIUS: f32 = 12.0;

#[test]
fn child_shader_tails_receive_their_substrates() {
    let mut renderer = support::headless_renderer().expect("child substrates require GPU");
    for spec in [
        SubstrateSpec::Mean,
        SubstrateSpec::Average { block: 4 },
        SubstrateSpec::Blur { radius_px: 2.0 },
    ] {
        let probe = support::substrate_probe(spec, SubstrateProbeRead::Held);
        let graph = |effect| {
            page(Some(RenderNode::Layer(Box::new(
                shared_test_support::layer_node(
                    rect(0.0, 0.0, GLASS.width, GLASS.height),
                    ProjectiveTransform::translation(GLASS.x, GLASS.y),
                    GraphicsLayer {
                        render_effect: Some(effect),
                        ..Default::default()
                    },
                    support::striped_page(GLASS.width as u32, GLASS.height as u32),
                ),
            ))))
        };
        let expected = capture(
            &mut renderer,
            graph(probe.clone().then(RenderEffect::offset(0.0, 0.0))),
        );
        let actual = capture(&mut renderer, graph(probe));
        assert!(
            region_pixels(&actual, GLASS) == region_pixels(&expected, GLASS),
            "child {spec:?} substrate differs from its full effect path"
        );
    }
}

#[test]
fn shader_chains_receive_each_stages_substrates() {
    let mut renderer = support::headless_renderer().expect("chained substrates require GPU");
    for spec in [
        SubstrateSpec::Mean,
        SubstrateSpec::Average { block: 4 },
        SubstrateSpec::Blur { radius_px: 2.0 },
    ] {
        let probe = support::substrate_probe(spec, SubstrateProbeRead::Held);
        let expected = capture(
            &mut renderer,
            page(Some(effect_layer(GLASS, probe.clone()))),
        );
        for terminal in [false, true] {
            let mut chained = RenderEffect::offset(0.0, 0.0).then(probe.clone());
            if !terminal {
                chained = chained.then(RenderEffect::offset(0.0, 0.0));
            }
            let actual = capture(&mut renderer, page(Some(effect_layer(GLASS, chained))));
            for (a, b) in region_pixels(&actual, GLASS)
                .iter()
                .zip(region_pixels(&expected, GLASS))
            {
                assert!(
                    a.abs_diff(b) <= 1,
                    "a chained {spec:?} substrate, terminal={terminal}, must equal the standalone path: {a} != {b}"
                );
            }
        }
    }
}
const BAND_TOP: f32 = 30.0;
const BAND_HEIGHT: f32 = 60.0;
const WIDE_RADIUS: f32 = 12.0;

fn rect(x: f32, y: f32, width: f32, height: f32) -> Rect {
    Rect {
        x,
        y,
        width,
        height,
    }
}

fn effect_layer(bounds: Rect, effect: RenderEffect) -> RenderNode {
    RenderNode::Layer(Box::new(shared_test_support::layer_node(
        rect(0.0, 0.0, bounds.width, bounds.height),
        ProjectiveTransform::translation(bounds.x, bounds.y),
        GraphicsLayer {
            backdrop_effect: Some(effect),
            ..GraphicsLayer::default()
        },
        Vec::new(),
    )))
}

fn page(layer: Option<RenderNode>) -> RenderGraph {
    let mut children = support::striped_page(FRAME_WIDTH, FRAME_HEIGHT);
    children.extend(layer);
    support::page_graph(FRAME_WIDTH, FRAME_HEIGHT, children)
}

fn capture(renderer: &mut support::LockedRenderer, graph: RenderGraph) -> CapturedFrame {
    support::capture_graph(renderer, graph, FRAME_WIDTH, FRAME_HEIGHT)
}

/// The page under `region` blurred by `radius` on the CPU, the region's
/// edge held, as the blur of a capture of exactly that region is.
fn reference_blur_of(page: &CapturedFrame, region: Rect, radius: f32) -> Vec<f32> {
    let pixels: Vec<f32> = region_pixels(page, region)
        .iter()
        .map(|value| f32::from(*value))
        .collect();
    support::reference_blur(
        &pixels,
        region.width as usize,
        region.height as usize,
        4,
        radius,
        ReferenceEdge::Clamp,
    )
}

/// The worst channel deviation of `frame` over `rows` of `region` from
/// `expected`, laid out over `region`.
fn worst_deviation(
    frame: &CapturedFrame,
    region: Rect,
    expected: &[f32],
    rows: std::ops::Range<usize>,
    inset: usize,
) -> (f32, (usize, usize)) {
    let actual = region_pixels(frame, region);
    let width = region.width as usize;
    let mut worst = (0.0f32, (0, 0));
    for y in rows {
        for x in inset..width - inset {
            for channel in 0..3 {
                let index = (y * width + x) * 4 + channel;
                let delta = (f32::from(actual[index]) - expected[index]).abs();
                if delta > worst.0 {
                    worst = (delta, (x, y));
                }
            }
        }
    }
    worst
}

/// A substrate blurred by twelve pixels runs at a quarter of its capture's
/// size and lands within this many levels of the CPU kernel away from its
/// edge (11.0 measured on a page of four-pixel stripes): the block average
/// of four, the truncation of the kernel at whole scratch texels and the
/// interpolation back, where a substrate never copied back into its slot
/// reads the pool's stale texels, 140 and more away. Its edge texels,
/// whose blocks reach past the region and hold to it, read the mean of a
/// block where the kernel weighs the corner texel, 32 away on the stripes.
const BLURRED_SUBSTRATE_BUDGET: f32 = 14.0;
const BLURRED_SUBSTRATE_EDGE_BUDGET: f32 = 36.0;

#[test]
fn transformed_child_receives_its_shared_mean_after_blur() {
    let mut renderer = support::headless_renderer().expect("mean substrate requires GPU");
    let mut glass = effect_layer(
        GLASS,
        RenderEffect::blur(6.0).then(support::substrate_probe(
            SubstrateSpec::Mean,
            SubstrateProbeRead::Held,
        )),
    );
    if let RenderNode::Layer(layer) = &mut glass {
        layer.transform_to_parent = ProjectiveTransform::uniform_scale(1.05)
            .then(ProjectiveTransform::translation(GLASS.x, GLASS.y));
    }
    let graph = support::page_graph(
        FRAME_WIDTH,
        FRAME_HEIGHT,
        vec![
            support::solid_rect(
                rect(0.0, 0.0, FRAME_WIDTH as f32, FRAME_HEIGHT as f32),
                cranpose_ui_graphics::Color(0.35, 0.35, 0.35, 1.0),
            ),
            glass,
        ],
    );
    let frame = capture(&mut renderer, graph);
    for pixel in region_pixels(&frame, rect(65.0, 45.0, 30.0, 25.0))
        .as_chunks::<4>()
        .0
    {
        assert!(
            pixel[..3].iter().all(|c| c.abs_diff(89) <= 1),
            "transformed child must receive its mean: {pixel:?}"
        );
    }
}

#[test]
fn shared_mean_uses_the_layer_extent_without_filter_padding() {
    let mut renderer = support::headless_renderer().expect("mean substrate requires GPU");
    let graph = support::page_graph(
        FRAME_WIDTH,
        FRAME_HEIGHT,
        vec![
            support::solid_rect(
                rect(0.0, 0.0, FRAME_WIDTH as f32, FRAME_HEIGHT as f32),
                cranpose_ui_graphics::Color::BLACK,
            ),
            support::solid_rect(GLASS, cranpose_ui_graphics::Color(0.5, 0.5, 0.5, 1.0)),
            effect_layer(
                GLASS,
                RenderEffect::blur(6.0).then(support::substrate_probe(
                    SubstrateSpec::Mean,
                    SubstrateProbeRead::Held,
                )),
            ),
        ],
    );
    let frame = capture(&mut renderer, graph);
    for pixel in region_pixels(&frame, rect(65.0, 45.0, 30.0, 25.0))
        .as_chunks::<4>()
        .0
    {
        assert!(
            pixel[..3].iter().all(|c| c.abs_diff(128) <= 1),
            "padding must not bias the mean: {pixel:?}"
        );
    }
}

#[test]
fn shared_mean_includes_every_texel_of_each_odd_sized_capture() {
    let mut renderer = support::headless_renderer().expect("mean substrate requires GPU");
    let regions = [rect(7.0, 5.0, 73.0, 51.0), rect(137.0, 11.0, 59.0, 83.0)];
    let plain = capture(&mut renderer, page(None));
    let mut children = support::striped_page(FRAME_WIDTH, FRAME_HEIGHT);
    for region in regions {
        children.push(effect_layer(
            region,
            support::substrate_probe(SubstrateSpec::Mean, SubstrateProbeRead::Held),
        ));
    }
    let actual = capture(
        &mut renderer,
        support::page_graph(FRAME_WIDTH, FRAME_HEIGHT, children),
    );
    for region in regions {
        let source = region_pixels(&plain, region);
        let mut mean = [0.0; 4];
        for pixel in source.as_chunks::<4>().0 {
            for channel in 0..4 {
                mean[channel] += f64::from(pixel[channel]);
            }
        }
        for value in &mut mean {
            *value /= (source.len() / 4) as f64;
        }
        for pixel in region_pixels(&actual, region).as_chunks::<4>().0 {
            for channel in 0..4 {
                assert!(
                    (f64::from(pixel[channel]) - mean[channel]).abs() <= 1.0,
                    "shared mean for {region:?}: {pixel:?}, expected {mean:?}"
                );
            }
        }
    }
}

#[test]
fn a_blurred_substrate_is_the_capture_blurred_by_its_radius() {
    let Ok(mut renderer) = support::headless_renderer() else {
        eprintln!("skipping (headless WGPU init failed)");
        return;
    };
    let plain = capture(&mut renderer, page(None));
    let probe = capture(
        &mut renderer,
        page(Some(effect_layer(
            GLASS,
            support::substrate_probe(
                SubstrateSpec::Blur {
                    radius_px: SUBSTRATE_RADIUS,
                },
                SubstrateProbeRead::Held,
            ),
        ))),
    );
    let expected = reference_blur_of(&plain, GLASS, SUBSTRATE_RADIUS);
    let height = GLASS.height as usize;
    let interior = worst_deviation(&probe, GLASS, &expected, 4..height - 4, 4);
    let edge = worst_deviation(&probe, GLASS, &expected, 0..height, 0);
    assert!(
        interior.0 <= BLURRED_SUBSTRATE_BUDGET && edge.0 <= BLURRED_SUBSTRATE_EDGE_BUDGET,
        "the substrate blurred by {SUBSTRATE_RADIUS} diverges from the kernel by {} at {:?} \
         inside and by {} at {:?} at its edge",
        interior.0,
        interior.1,
        edge.0,
        edge.1
    );
}

fn band() -> Rect {
    rect(0.0, BAND_TOP, FRAME_WIDTH as f32, BAND_HEIGHT)
}

/// The capture a gradient blur over `band()` reads: the band grown by the
/// wide radius, where its clamp edge lies.
fn band_capture() -> Rect {
    let reach = WIDE_RADIUS.ceil();
    rect(
        0.0,
        BAND_TOP - reach,
        FRAME_WIDTH as f32,
        BAND_HEIGHT + 2.0 * reach,
    )
}

fn gradient_band(renderer: &mut support::LockedRenderer) -> CapturedFrame {
    capture(
        renderer,
        page(Some(effect_layer(
            band(),
            gradient_blur_effect(WIDE_RADIUS, 0.0, GradientBlurDirection::TopToBottom),
        ))),
    )
}

/// A gradient blur's top row asks for the wide radius and reads the wide
/// level whole: within the level row's budget of the CPU kernel at that
/// radius.
#[test]
fn a_gradient_blur_realises_its_wide_radius_as_the_wide_level() {
    let Ok(mut renderer) = support::headless_renderer() else {
        eprintln!("skipping (headless WGPU init failed)");
        return;
    };
    let plain = capture(&mut renderer, page(None));
    let frame = gradient_band(&mut renderer);
    let capture_rect = band_capture();
    let expected = reference_blur_of(&plain, capture_rect, WIDE_RADIUS);
    let top_row = (BAND_TOP - capture_rect.y) as usize + 1;
    let (worst, at) = worst_deviation(
        &frame,
        capture_rect,
        &expected,
        top_row..top_row + 1,
        WIDE_RADIUS as usize + 2,
    );
    assert!(
        worst <= LEVEL_ROW_BUDGET,
        "the band's top row diverges from the radius-{WIDE_RADIUS} kernel by {worst} at {at:?}"
    );
}

/// The row of the band whose radius is `share` of the wide one: the taper
/// is a smoothstep of the band's height.
fn band_row_for(share: f32) -> usize {
    let progress = 1.0 - share;
    let mut low = 0.0f32;
    let mut high = 1.0f32;
    for _ in 0..40 {
        let mid = (low + high) * 0.5;
        if mid * mid * (3.0 - 2.0 * mid) < progress {
            low = mid;
        } else {
            high = mid;
        }
    }
    let local = (low + high) * 0.5;
    (BAND_TOP + BAND_HEIGHT * local - band_capture().y).round() as usize
}

/// The worst deviation of the band's row asking for `share` of the wide
/// radius from the CPU kernel at that radius.
fn band_row_deviation(frame: &CapturedFrame, plain: &CapturedFrame, share: f32) -> f32 {
    let capture_rect = band_capture();
    let expected = reference_blur_of(plain, capture_rect, WIDE_RADIUS * share);
    let row = band_row_for(share);
    worst_deviation(
        frame,
        capture_rect,
        &expected,
        row..row + 1,
        WIDE_RADIUS as usize + 2,
    )
    .0
}

/// A row asking for exactly a level's radius reads that level whole and
/// lands within this many levels of the kernel at that radius (3.3
/// measured at the wide level, 4.4 at the half); a row midway between two
/// levels blends them and lies within twice that of the kernel at its
/// radius on a page of four-pixel stripes (9.6 measured between the half
/// and the wide level, 4.4 between the quarter and the half), where
/// blending two levels four times apart in radius lands 44 away and a
/// level never copied back past 100.
const LEVEL_ROW_BUDGET: f32 = 7.0;
const BLENDED_LEVEL_BUDGET: f32 = 14.0;

#[test]
fn a_gradient_blur_blends_its_levels_between_sharp_and_wide() {
    let Ok(mut renderer) = support::headless_renderer() else {
        eprintln!("skipping (headless WGPU init failed)");
        return;
    };
    let plain = capture(&mut renderer, page(None));
    let frame = gradient_band(&mut renderer);
    let bottom = rect(0.0, BAND_TOP + BAND_HEIGHT - 2.0, FRAME_WIDTH as f32, 1.0);
    assert_eq!(
        region_pixels(&frame, bottom),
        region_pixels(&plain, bottom),
        "the band's bottom row asks for no blur and shows the page"
    );
    let rows = [
        (0.5, LEVEL_ROW_BUDGET),
        (0.75, BLENDED_LEVEL_BUDGET),
        (0.375, BLENDED_LEVEL_BUDGET),
    ];
    let deviations: Vec<(f32, f32, f32)> = rows
        .iter()
        .map(|(share, budget)| (*share, band_row_deviation(&frame, &plain, *share), *budget))
        .collect();
    assert!(
        deviations
            .iter()
            .all(|(_, deviation, budget)| deviation <= budget),
        "the band's rows diverge from the kernels at their radii (share of the wide radius, \
         deviation, budget): {deviations:?}"
    );
}