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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Image comparison utilities

use std::{borrow::Cow, ffi::OsStr, path::Path};

use wgpu::util::{align_to, DeviceExt};
use wgpu::*;

use crate::TestingContext;

#[cfg(not(target_arch = "wasm32"))]
async fn read_png(path: impl AsRef<Path>, width: u32, height: u32) -> Option<Vec<u8>> {
    let data = match std::fs::read(&path) {
        Ok(f) => f,
        Err(e) => {
            log::warn!(
                "image comparison invalid: file io error when comparing {}: {}",
                path.as_ref().display(),
                e
            );
            return None;
        }
    };
    let decoder = png::Decoder::new(std::io::Cursor::new(data));
    let mut reader = decoder.read_info().ok()?;

    let mut buffer = vec![0; reader.output_buffer_size()];
    let info = reader.next_frame(&mut buffer).ok()?;
    if info.width != width {
        log::warn!("image comparison invalid: size mismatch");
        return None;
    }
    if info.height != height {
        log::warn!("image comparison invalid: size mismatch");
        return None;
    }
    if info.color_type != png::ColorType::Rgba {
        log::warn!("image comparison invalid: color type mismatch");
        return None;
    }
    if info.bit_depth != png::BitDepth::Eight {
        log::warn!("image comparison invalid: bit depth mismatch");
        return None;
    }

    Some(buffer)
}

#[cfg(not(target_arch = "wasm32"))]
async fn write_png(
    path: impl AsRef<Path>,
    width: u32,
    height: u32,
    data: &[u8],
    compression: png::Compression,
) {
    let file = std::io::BufWriter::new(std::fs::File::create(path).unwrap());

    let mut encoder = png::Encoder::new(file, width, height);
    encoder.set_color(png::ColorType::Rgba);
    encoder.set_depth(png::BitDepth::Eight);
    encoder.set_compression(compression);
    let mut writer = encoder.write_header().unwrap();

    writer.write_image_data(data).unwrap();
}

#[cfg_attr(target_arch = "wasm32", allow(unused))]
fn add_alpha(input: &[u8]) -> Vec<u8> {
    input
        .chunks_exact(3)
        .flat_map(|chunk| [chunk[0], chunk[1], chunk[2], 255])
        .collect()
}

#[cfg_attr(target_arch = "wasm32", allow(unused))]
fn remove_alpha(input: &[u8]) -> Vec<u8> {
    input
        .chunks_exact(4)
        .flat_map(|chunk| &chunk[0..3])
        .copied()
        .collect()
}

#[cfg(not(target_arch = "wasm32"))]
fn print_flip(pool: &mut nv_flip::FlipPool) {
    println!("\tMean: {:.6}", pool.mean());
    println!("\tMin Value: {:.6}", pool.min_value());
    for percentile in [25, 50, 75, 95, 99] {
        println!(
            "\t      {percentile}%: {:.6}",
            pool.get_percentile(percentile as f32 / 100.0, true)
        );
    }
    println!("\tMax Value: {:.6}", pool.max_value());
}

/// The FLIP library generates a per-pixel error map where 0.0 represents "no error"
/// and 1.0 represents "maximum error" between the images. This is then put into
/// a weighted-histogram, which we query to determine if the errors between
/// the test and reference image is high enough to count as "different".
///
/// Error thresholds will be different for every test, but good initial values
/// to look at are in the [0.01, 0.1] range. The larger the area that might have
/// inherent variance, the larger this base value is. Using a high percentile comparison
/// (e.g. 95% or 99%) is good for images that are likely to have a lot of error
/// in a small area when they fail.
#[derive(Debug, Clone, Copy)]
pub enum ComparisonType {
    /// If the mean error is greater than the given value, the test will fail.
    Mean(f32),
    /// If the given percentile is greater than the given value, the test will fail.
    ///
    /// The percentile is given in the range [0, 1].
    Percentile { percentile: f32, threshold: f32 },
}

impl ComparisonType {
    #[cfg(not(target_arch = "wasm32"))]
    fn check(&self, pool: &mut nv_flip::FlipPool) -> bool {
        match *self {
            ComparisonType::Mean(v) => {
                let mean = pool.mean();
                let within = mean <= v;
                println!(
                    "\tExpected Mean ({:.6}) to be under expected maximum ({}): {}",
                    mean,
                    v,
                    if within { "PASS" } else { "FAIL" }
                );
                within
            }
            ComparisonType::Percentile {
                percentile: p,
                threshold: v,
            } => {
                let percentile = pool.get_percentile(p, true);
                let within = percentile <= v;
                println!(
                    "\tExpected {}% ({:.6}) to be under expected maximum ({}): {}",
                    p * 100.0,
                    percentile,
                    v,
                    if within { "PASS" } else { "FAIL" }
                );
                within
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub async fn compare_image_output(
    path: impl AsRef<Path> + AsRef<OsStr>,
    adapter_info: &wgt::AdapterInfo,
    width: u32,
    height: u32,
    test_with_alpha: &[u8],
    checks: &[ComparisonType],
) {
    use std::{ffi::OsString, str::FromStr};

    let reference_path = Path::new(&path);
    let reference_with_alpha = read_png(&path, width, height).await;

    let reference = match reference_with_alpha {
        Some(v) => remove_alpha(&v),
        None => {
            write_png(
                &path,
                width,
                height,
                test_with_alpha,
                png::Compression::Best,
            )
            .await;
            return;
        }
    };
    let test = remove_alpha(test_with_alpha);

    assert_eq!(reference.len(), test.len());

    let file_stem = reference_path.file_stem().unwrap().to_string_lossy();
    let renderer = format!(
        "{}-{}-{}",
        adapter_info.backend,
        sanitize_for_path(&adapter_info.name),
        sanitize_for_path(&adapter_info.driver)
    );
    // Determine the paths to write out the various intermediate files
    let actual_path = Path::new(&path).with_file_name(
        OsString::from_str(&format!("{}-{}-actual.png", file_stem, renderer)).unwrap(),
    );
    let difference_path = Path::new(&path).with_file_name(
        OsString::from_str(&format!("{}-{}-difference.png", file_stem, renderer,)).unwrap(),
    );

    let mut all_passed;
    let magma_image_with_alpha;
    {
        let reference_flip = nv_flip::FlipImageRgb8::with_data(width, height, &reference);
        let test_flip = nv_flip::FlipImageRgb8::with_data(width, height, &test);

        let error_map_flip = nv_flip::flip(
            reference_flip,
            test_flip,
            nv_flip::DEFAULT_PIXELS_PER_DEGREE,
        );
        let mut pool = nv_flip::FlipPool::from_image(&error_map_flip);

        println!(
            "Starting image comparison test with reference image \"{}\"",
            reference_path.display()
        );

        print_flip(&mut pool);

        // If there are no checks, we want to fail the test.
        all_passed = !checks.is_empty();
        // We always iterate all of these, as the call to check prints
        for check in checks {
            all_passed &= check.check(&mut pool);
        }

        // Convert the error values to a false color representation
        let magma_image = error_map_flip
            .apply_color_lut(&nv_flip::magma_lut())
            .to_vec();
        magma_image_with_alpha = add_alpha(&magma_image);
    }

    write_png(
        actual_path,
        width,
        height,
        test_with_alpha,
        png::Compression::Fast,
    )
    .await;
    write_png(
        &difference_path,
        width,
        height,
        &magma_image_with_alpha,
        png::Compression::Fast,
    )
    .await;

    if !all_passed {
        panic!("Image data mismatch: {}", difference_path.display())
    }
}

#[cfg(target_arch = "wasm32")]
pub async fn compare_image_output(
    path: impl AsRef<Path> + AsRef<OsStr>,
    adapter_info: &wgt::AdapterInfo,
    width: u32,
    height: u32,
    test_with_alpha: &[u8],
    checks: &[ComparisonType],
) {
    #[cfg(target_arch = "wasm32")]
    {
        let _ = (path, adapter_info, width, height, test_with_alpha, checks);
    }
}

#[cfg_attr(target_arch = "wasm32", allow(unused))]
fn sanitize_for_path(s: &str) -> String {
    s.chars()
        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
        .collect()
}

fn copy_via_compute(
    device: &Device,
    encoder: &mut CommandEncoder,
    texture: &Texture,
    buffer: &Buffer,
    aspect: TextureAspect,
) {
    let bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
        label: None,
        entries: &[
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::COMPUTE,
                ty: BindingType::Texture {
                    sample_type: match aspect {
                        TextureAspect::DepthOnly => TextureSampleType::Float { filterable: false },
                        TextureAspect::StencilOnly => TextureSampleType::Uint,
                        _ => unreachable!(),
                    },
                    view_dimension: TextureViewDimension::D2Array,
                    multisampled: false,
                },
                count: None,
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::COMPUTE,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Storage { read_only: false },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    });

    let view = texture.create_view(&TextureViewDescriptor {
        aspect,
        dimension: Some(TextureViewDimension::D2Array),
        ..Default::default()
    });

    let output_buffer = device.create_buffer(&BufferDescriptor {
        label: Some("output buffer"),
        size: buffer.size(),
        usage: BufferUsages::COPY_SRC | BufferUsages::STORAGE,
        mapped_at_creation: false,
    });

    let bg = device.create_bind_group(&BindGroupDescriptor {
        label: None,
        layout: &bgl,
        entries: &[
            BindGroupEntry {
                binding: 0,
                resource: BindingResource::TextureView(&view),
            },
            BindGroupEntry {
                binding: 1,
                resource: BindingResource::Buffer(BufferBinding {
                    buffer: &output_buffer,
                    offset: 0,
                    size: None,
                }),
            },
        ],
    });

    let pll = device.create_pipeline_layout(&PipelineLayoutDescriptor {
        label: None,
        bind_group_layouts: &[&bgl],
        push_constant_ranges: &[],
    });

    let source = String::from(include_str!("copy_texture_to_buffer.wgsl"));

    let processed_source = source.replace(
        "{{type}}",
        match aspect {
            TextureAspect::DepthOnly => "f32",
            TextureAspect::StencilOnly => "u32",
            _ => unreachable!(),
        },
    );

    let sm = device.create_shader_module(ShaderModuleDescriptor {
        label: Some("shader copy_texture_to_buffer.wgsl"),
        source: ShaderSource::Wgsl(Cow::Borrowed(&processed_source)),
    });

    let pipeline_copy = device.create_compute_pipeline(&ComputePipelineDescriptor {
        label: Some("pipeline read"),
        layout: Some(&pll),
        module: &sm,
        entry_point: Some("copy_texture_to_buffer"),
        compilation_options: Default::default(),
        cache: None,
    });

    {
        let mut pass = encoder.begin_compute_pass(&ComputePassDescriptor::default());

        pass.set_pipeline(&pipeline_copy);
        pass.set_bind_group(0, Some(&bg), &[]);
        pass.dispatch_workgroups(1, 1, 1);
    }

    encoder.copy_buffer_to_buffer(&output_buffer, 0, buffer, 0, buffer.size());
}

fn copy_texture_to_buffer_with_aspect(
    encoder: &mut CommandEncoder,
    texture: &Texture,
    buffer: &Buffer,
    buffer_stencil: &Option<Buffer>,
    aspect: TextureAspect,
) {
    let (block_width, block_height) = texture.format().block_dimensions();
    let block_size = texture.format().block_copy_size(Some(aspect)).unwrap();
    let bytes_per_row = align_to(
        (texture.width() / block_width) * block_size,
        COPY_BYTES_PER_ROW_ALIGNMENT,
    );
    let mip_level = 0;
    encoder.copy_texture_to_buffer(
        ImageCopyTexture {
            texture,
            mip_level,
            origin: Origin3d::ZERO,
            aspect,
        },
        ImageCopyBuffer {
            buffer: match aspect {
                TextureAspect::StencilOnly => buffer_stencil.as_ref().unwrap(),
                _ => buffer,
            },
            layout: ImageDataLayout {
                offset: 0,
                bytes_per_row: Some(bytes_per_row),
                rows_per_image: Some(texture.height() / block_height),
            },
        },
        texture
            .size()
            .mip_level_size(mip_level, texture.dimension()),
    );
}

fn copy_texture_to_buffer(
    device: &Device,
    encoder: &mut CommandEncoder,
    texture: &Texture,
    buffer: &Buffer,
    buffer_stencil: &Option<Buffer>,
) {
    match texture.format() {
        TextureFormat::Depth24Plus => {
            copy_via_compute(device, encoder, texture, buffer, TextureAspect::DepthOnly);
        }
        TextureFormat::Depth24PlusStencil8 => {
            copy_via_compute(device, encoder, texture, buffer, TextureAspect::DepthOnly);
            copy_texture_to_buffer_with_aspect(
                encoder,
                texture,
                buffer,
                buffer_stencil,
                TextureAspect::StencilOnly,
            );
        }
        TextureFormat::Depth32FloatStencil8 => {
            copy_texture_to_buffer_with_aspect(
                encoder,
                texture,
                buffer,
                buffer_stencil,
                TextureAspect::DepthOnly,
            );
            copy_texture_to_buffer_with_aspect(
                encoder,
                texture,
                buffer,
                buffer_stencil,
                TextureAspect::StencilOnly,
            );
        }
        _ => {
            copy_texture_to_buffer_with_aspect(
                encoder,
                texture,
                buffer,
                buffer_stencil,
                TextureAspect::All,
            );
        }
    }
}

pub struct ReadbackBuffers {
    /// texture format
    texture_format: TextureFormat,
    /// texture width
    texture_width: u32,
    /// texture height
    texture_height: u32,
    /// texture depth or array layer count
    texture_depth_or_array_layers: u32,
    /// buffer for color or depth aspects
    buffer: Buffer,
    /// buffer for stencil aspect
    buffer_stencil: Option<Buffer>,
}

impl ReadbackBuffers {
    pub fn new(device: &Device, texture: &Texture) -> Self {
        let (block_width, block_height) = texture.format().block_dimensions();
        const SKIP_ALIGNMENT_FORMATS: [TextureFormat; 2] = [
            TextureFormat::Depth24Plus,
            TextureFormat::Depth24PlusStencil8,
        ];
        let should_align_buffer_size = !SKIP_ALIGNMENT_FORMATS.contains(&texture.format());
        if texture.format().is_combined_depth_stencil_format() {
            let mut buffer_depth_bytes_per_row = (texture.width() / block_width)
                * texture
                    .format()
                    .block_copy_size(Some(TextureAspect::DepthOnly))
                    .unwrap_or(4);
            if should_align_buffer_size {
                buffer_depth_bytes_per_row =
                    align_to(buffer_depth_bytes_per_row, COPY_BYTES_PER_ROW_ALIGNMENT);
            }
            let buffer_size = buffer_depth_bytes_per_row
                * (texture.height() / block_height)
                * texture.depth_or_array_layers();

            let buffer_stencil_bytes_per_row = align_to(
                (texture.width() / block_width)
                    * texture
                        .format()
                        .block_copy_size(Some(TextureAspect::StencilOnly))
                        .unwrap_or(4),
                COPY_BYTES_PER_ROW_ALIGNMENT,
            );
            let buffer_stencil_size = buffer_stencil_bytes_per_row
                * (texture.height() / block_height)
                * texture.depth_or_array_layers();

            let buffer = device.create_buffer_init(&util::BufferInitDescriptor {
                label: Some("Texture Readback"),
                usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
                contents: &vec![255; buffer_size as usize],
            });
            let buffer_stencil = device.create_buffer_init(&util::BufferInitDescriptor {
                label: Some("Texture Stencil-Aspect Readback"),
                usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
                contents: &vec![255; buffer_stencil_size as usize],
            });
            ReadbackBuffers {
                texture_format: texture.format(),
                texture_width: texture.width(),
                texture_height: texture.height(),
                texture_depth_or_array_layers: texture.depth_or_array_layers(),
                buffer,
                buffer_stencil: Some(buffer_stencil),
            }
        } else {
            let mut bytes_per_row = (texture.width() / block_width)
                * texture.format().block_copy_size(None).unwrap_or(4);
            if should_align_buffer_size {
                bytes_per_row = align_to(bytes_per_row, COPY_BYTES_PER_ROW_ALIGNMENT);
            }
            let buffer_size =
                bytes_per_row * (texture.height() / block_height) * texture.depth_or_array_layers();
            let buffer = device.create_buffer_init(&util::BufferInitDescriptor {
                label: Some("Texture Readback"),
                usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
                contents: &vec![255; buffer_size as usize],
            });
            ReadbackBuffers {
                texture_format: texture.format(),
                texture_width: texture.width(),
                texture_height: texture.height(),
                texture_depth_or_array_layers: texture.depth_or_array_layers(),
                buffer,
                buffer_stencil: None,
            }
        }
    }

    // TODO: also copy and check mips
    pub fn copy_from(&self, device: &Device, encoder: &mut CommandEncoder, texture: &Texture) {
        copy_texture_to_buffer(device, encoder, texture, &self.buffer, &self.buffer_stencil);
    }

    async fn retrieve_buffer(
        &self,
        ctx: &TestingContext,
        buffer: &Buffer,
        aspect: Option<TextureAspect>,
    ) -> Vec<u8> {
        let buffer_slice = buffer.slice(..);
        buffer_slice.map_async(MapMode::Read, |_| ());
        ctx.async_poll(Maintain::wait()).await.panic_on_timeout();
        let (block_width, block_height) = self.texture_format.block_dimensions();
        let expected_bytes_per_row = (self.texture_width / block_width)
            * self.texture_format.block_copy_size(aspect).unwrap_or(4);
        let expected_buffer_size = expected_bytes_per_row
            * (self.texture_height / block_height)
            * self.texture_depth_or_array_layers;
        let data: BufferView = buffer_slice.get_mapped_range();
        if expected_buffer_size as usize == data.len() {
            data.to_vec()
        } else {
            bytemuck::cast_slice(&data)
                .chunks_exact(
                    align_to(expected_bytes_per_row, COPY_BYTES_PER_ROW_ALIGNMENT) as usize,
                )
                .flat_map(|x| x.iter().take(expected_bytes_per_row as usize))
                .copied()
                .collect()
        }
    }

    fn buffer_aspect(&self) -> Option<TextureAspect> {
        if self.texture_format.is_combined_depth_stencil_format() {
            Some(TextureAspect::DepthOnly)
        } else {
            None
        }
    }

    async fn is_zero(
        &self,
        ctx: &TestingContext,
        buffer: &Buffer,
        aspect: Option<TextureAspect>,
    ) -> bool {
        let is_zero = self
            .retrieve_buffer(ctx, buffer, aspect)
            .await
            .iter()
            .all(|b| *b == 0);
        buffer.unmap();
        is_zero
    }

    pub async fn are_zero(&self, ctx: &TestingContext) -> bool {
        let buffer_zero = self.is_zero(ctx, &self.buffer, self.buffer_aspect()).await;
        let mut stencil_buffer_zero = true;
        if let Some(buffer) = &self.buffer_stencil {
            stencil_buffer_zero = self
                .is_zero(ctx, buffer, Some(TextureAspect::StencilOnly))
                .await;
        };
        buffer_zero && stencil_buffer_zero
    }

    pub async fn assert_buffer_contents(&self, ctx: &TestingContext, expected_data: &[u8]) {
        let result_buffer = self
            .retrieve_buffer(ctx, &self.buffer, self.buffer_aspect())
            .await;
        assert!(
            result_buffer.len() >= expected_data.len(),
            "Result buffer ({}) smaller than expected buffer ({})",
            result_buffer.len(),
            expected_data.len()
        );
        let result_buffer = &result_buffer[..expected_data.len()];
        assert_eq!(result_buffer, expected_data);
        self.buffer.unmap();
    }
}