mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Tests: reuse canvas captures and batch mip readbacks (#15942)
This commit is contained in:
1 parent
1553cd3c9e
commit
1f7acffe94
7 files changed
+215
-174
No files matched your search
@@ -14,37 +14,48 @@ fn read_mips(gpu: &GpuCanvas, key: u64) -> Vec<Vec<[f32; 4]>> {
|
||||
let tile = &doc.tiles[0];
|
||||
let (device, queue) = (&gpu.rs.device, &gpu.rs.queue);
|
||||
let bpp = texel_bytes(doc.format) as usize;
|
||||
(0..tile.levels.len())
|
||||
// Each level starts after a whole number of padded rows, so each copy offset has
|
||||
// room for its own texels and meets the copy alignment for both canvas formats.
|
||||
let mut size = 0;
|
||||
let levels: Vec<_> = (0..tile.levels.len())
|
||||
.map(|level| {
|
||||
let (w, h) = ((doc.size[0] >> level).max(1), (doc.size[1] >> level).max(1));
|
||||
let row = (w as usize * bpp).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize);
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("mip_test_readback"),
|
||||
size: (row * h as usize) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row as u32), rows_per_image: Some(h) },
|
||||
},
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
buffer.slice(..).map_async(wgpu::MapMode::Read, |result| result.unwrap());
|
||||
assert!(gpu.health.wait(device, None));
|
||||
let data = buffer.slice(..).get_mapped_range().unwrap();
|
||||
let mut pixels = Vec::new();
|
||||
for y in 0..h as usize {
|
||||
for x in 0..w as usize {
|
||||
let offset = y * row + x * bpp;
|
||||
pixels.push(texel_to_f32(doc.format, &data[offset..offset + bpp]));
|
||||
}
|
||||
}
|
||||
pixels
|
||||
let offset = size;
|
||||
size += row * h as usize;
|
||||
(w, h, row, offset)
|
||||
})
|
||||
.collect();
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("mip_test_readback"),
|
||||
size: size as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
for (level, &(w, h, row, offset)) in levels.iter().enumerate() {
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: &tile.texture, mip_level: level as u32, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: offset as u64, bytes_per_row: Some(row as u32), rows_per_image: Some(h) },
|
||||
},
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
let submission = queue.submit([encoder.finish()]);
|
||||
let slice = buffer.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |result| result.expect("map mip readback"));
|
||||
assert!(gpu.health.wait_idle(device, Some(submission)));
|
||||
let data = slice.get_mapped_range().expect("read mip snapshot");
|
||||
levels
|
||||
.into_iter()
|
||||
.map(|(w, h, row, offset)| {
|
||||
data[offset..offset + row * h as usize]
|
||||
.chunks_exact(row)
|
||||
.flat_map(|line| line[..w as usize * bpp].chunks_exact(bpp))
|
||||
.map(|texel| texel_to_f32(doc.format, texel))
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -232,8 +243,9 @@ fn background_compositor_switch_preserves_pixels(gpu: &GpuCanvas) {
|
||||
}
|
||||
let second = gpu.refresh(key, &doc, Some(damage), None);
|
||||
assert_eq!(second.kind, "gpu-rect", "{:?}", second.fallback);
|
||||
let actual = read_mips(gpu, key).remove(0);
|
||||
let (_, _, actual) = gpu.read_texels(key).expect("read updated canvas");
|
||||
let expected = photocraft_compose::render(&doc, doc.bounds());
|
||||
assert_eq!(actual.len(), expected.px.len());
|
||||
for (got, want) in actual.iter().zip(expected.px.iter()) {
|
||||
for (g, w) in got.iter().zip(want.iter()) {
|
||||
assert!((g - w).abs() < 0.02, "{got:?} != {want:?}");
|
||||
|
||||
@@ -90,12 +90,14 @@ fn button(h: &mut Harness, at: Pos2, pressed: bool) {
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// The rendered frame's RGB at document point `(x, y)`.
|
||||
fn rgb_at(h: &mut Harness, x: f64, y: f64) -> [u8; 3] {
|
||||
let p = screen(h, x, y);
|
||||
/// Sample all points in the same rendered frame.
|
||||
fn rgb_at<const N: usize>(h: &mut Harness, points: [[f64; 2]; N]) -> [[u8; 3]; N] {
|
||||
let points = points.map(|[x, y]| screen(h, x, y));
|
||||
let img = h.render().expect("render");
|
||||
let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32);
|
||||
[px[0], px[1], px[2]]
|
||||
points.map(|p| {
|
||||
let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32);
|
||||
[px[0], px[1], px[2]]
|
||||
})
|
||||
}
|
||||
|
||||
fn is_red(c: [u8; 3]) -> bool {
|
||||
@@ -110,11 +112,12 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness(gpu_canvas) else { return };
|
||||
setup(&mut h);
|
||||
assert!(is_red(rgb_at(&mut h, 150.5, 150.5)), "the layer shows before the transform");
|
||||
let [before] = rgb_at(&mut h, [[150.5, 150.5]]);
|
||||
assert!(is_red(before), "the layer shows before the transform");
|
||||
|
||||
control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"}));
|
||||
assert!(h.state().ui.transform.is_some(), "Free Transform is open");
|
||||
let inside = rgb_at(&mut h, 150.5, 150.5);
|
||||
let [inside] = rgb_at(&mut h, [[150.5, 150.5]]);
|
||||
assert!(is_red(inside), "the layer shows inside the box once Free Transform opens, not the background: {inside:?}");
|
||||
|
||||
// Drag the box 60 px right from its middle and hold: the preview follows the pointer. The samples sit off the
|
||||
@@ -125,12 +128,11 @@ fn shows_the_layer_inside_the_box(gpu_canvas: bool) {
|
||||
for i in 1..=6 {
|
||||
pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0));
|
||||
}
|
||||
let moved = rgb_at(&mut h, 230.5, 130.5);
|
||||
let [moved, vacated] = rgb_at(&mut h, [[230.5, 130.5], [120.5, 130.5]]);
|
||||
assert!(is_red(moved), "the moved square shows where the drag took it: {moved:?}");
|
||||
let vacated = rgb_at(&mut h, 120.5, 130.5);
|
||||
assert!(is_white(vacated), "the place the square left shows the background: {vacated:?}");
|
||||
button(&mut h, to, false);
|
||||
let released = rgb_at(&mut h, 230.5, 130.5);
|
||||
let [released] = rgb_at(&mut h, [[230.5, 130.5]]);
|
||||
assert!(is_red(released), "the moved square still shows after the release: {released:?}");
|
||||
}
|
||||
|
||||
@@ -158,12 +160,13 @@ fn cancelling_shows_no_moved_pixels(gpu_canvas: bool) {
|
||||
pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0));
|
||||
}
|
||||
button(&mut h, to, false);
|
||||
assert!(is_red(rgb_at(&mut h, 230.5, 130.5)), "the box moved the square");
|
||||
let [before] = rgb_at(&mut h, [[230.5, 130.5]]);
|
||||
assert!(is_red(before), "the box moved the square");
|
||||
|
||||
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
assert!(h.state().ui.transform.is_none(), "Escape ended Free Transform");
|
||||
let moved = rgb_at(&mut h, 230.5, 130.5);
|
||||
let [moved, back] = rgb_at(&mut h, [[230.5, 130.5], [150.5, 150.5]]);
|
||||
assert!(is_white(moved), "the cancelling frame shows no moved pixels: {moved:?}");
|
||||
let back = rgb_at(&mut h, 150.5, 130.5);
|
||||
assert!(is_red(back), "the square is back in its place: {back:?}");
|
||||
|
||||
@@ -162,15 +162,22 @@ fn pm(p: &[f32; 4]) -> [f32; 4] {
|
||||
[p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]
|
||||
}
|
||||
|
||||
fn diffs(a: &[[f32; 4]], b: &[[f32; 4]]) -> Vec<f32> {
|
||||
a.iter().zip(b).map(|(x, y)| (0..4).map(|c| (pm(x)[c] - pm(y)[c]).abs()).fold(0.0, f32::max)).collect()
|
||||
}
|
||||
|
||||
/// Largest difference, ignoring up to `skip` outliers.
|
||||
fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]], skip: usize) -> f32 {
|
||||
let mut d = diffs(a, b);
|
||||
d.sort_by(|x, y| y.total_cmp(x));
|
||||
d.get(skip).copied().unwrap_or(0.0)
|
||||
assert_eq!(a.len(), b.len());
|
||||
let diffs = a.iter().zip(b).map(|(x, y)| {
|
||||
let (x, y) = (pm(x), pm(y));
|
||||
x.into_iter().zip(y).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max)
|
||||
});
|
||||
if skip == 0 {
|
||||
diffs.fold(0.0, f32::max)
|
||||
} else {
|
||||
let mut diffs = diffs.collect::<Vec<_>>();
|
||||
if skip >= diffs.len() {
|
||||
return 0.0;
|
||||
}
|
||||
*diffs.select_nth_unstable_by(skip, |x, y| y.total_cmp(x)).1
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -227,9 +227,10 @@ fn screens(cases: Vec<ScreenCase<'_>>) -> Option<Vec<Screen>> {
|
||||
}
|
||||
harness.run_steps(6);
|
||||
let img = harness.render().expect("render");
|
||||
let out = std::env::temp_dir().join(name);
|
||||
let _ = img.save(&out);
|
||||
eprintln!("screen: {}", out.display());
|
||||
if let Some(dir) = std::env::var_os("PHOTOCRAFT_CANVAS_16F_EVIDENCE_DIR") {
|
||||
std::fs::create_dir_all(&dir).expect("evidence directory");
|
||||
img.save(std::path::Path::new(&dir).join(name)).expect("save UI frame");
|
||||
}
|
||||
shown.push(Screen { w: img.width(), h: img.height(), px: img.into_raw() });
|
||||
if let Some((doc, setup, name)) = cases.next() {
|
||||
harness.state_mut().session.open_document(doc, None);
|
||||
@@ -252,7 +253,9 @@ fn screen_levels(img: &Screen, y: u32, x0: u32, x1: u32) -> (usize, i32) {
|
||||
fn sixteen_bit_gradient_on_screen() {
|
||||
let _gpu = gpu_lock();
|
||||
// A 16-bit ramp drawn by the app's canvas: smooth, monotonic, no visible steps.
|
||||
let doc = gradient(SampleType::U16, 2048, 1024, 0.0, 1.0);
|
||||
// The document still fits down to the same viewport and has more source levels than
|
||||
// the screen can display. The extra source pixels aren't needed to spot banding.
|
||||
let doc = gradient(SampleType::U16, 1024, 512, 0.0, 1.0);
|
||||
let Some(img) = screen(doc, &[], "photocraft-canvas-16f-gradient.png") else { return };
|
||||
let (n, step) = screen_levels(&img, img.h / 2, 150, 600);
|
||||
assert!(n > 100 && step <= 3, "{n} levels, max step {step}");
|
||||
@@ -263,7 +266,7 @@ fn thirty_two_bit_preview_exposes_values_above_one() {
|
||||
let _gpu = gpu_lock();
|
||||
// A dark 32-bit ramp brightened +4 stops by View › 32-bit Preview Options: with an 8-bit
|
||||
// canvas texture its 0..1/16 range has 16 codes (banding); the float texture keeps it smooth.
|
||||
let doc = gradient(SampleType::F32, 2048, 1024, 0.0, 1.0 / 16.0);
|
||||
let doc = gradient(SampleType::F32, 1024, 512, 0.0, 1.0 / 16.0);
|
||||
// Values above 1.0 are brought into range by a negative exposure instead of clipped: 2.0
|
||||
// at −3 stops shows as sRGB(lin(2.0) / 8) rather than sRGB(lin(1.0) / 8).
|
||||
let mut flat = Document::new("hdr", Size::new(512, 512), ColorMode::Rgb, SampleType::F32);
|
||||
|
||||
@@ -5,9 +5,13 @@
|
||||
//! These tests render the real app offscreen and read pixels back. They skip when no GPU adapter
|
||||
//! is available. The CPU canvas (no wgpu handed to the app) has its own pixel grid tests at the end.
|
||||
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_doc::{Document, Layer, LayerContent, Size};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Surface;
|
||||
use photocraft_ui_egui::PhotocraftApp;
|
||||
use photocraft_ui_egui::control::{ControlRequest, handle};
|
||||
use serde_json::{Value, json};
|
||||
use photocraft_ui_egui::control::{ControlRequest, Reply, handle};
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, Box<PhotocraftApp>>;
|
||||
|
||||
@@ -24,8 +28,11 @@ fn harness_with(gpu: bool) -> Option<Harness> {
|
||||
}
|
||||
|
||||
fn harness_with_scale(gpu: bool, ppp: f32) -> Option<Harness> {
|
||||
// At 2× the same document pixels take half as many points. Keep the samples
|
||||
// inside the viewport without reading back a 2800 × 1600 frame.
|
||||
let size = if ppp > 1.0 { egui::vec2(960.0, 600.0) } else { egui::vec2(1400.0, 800.0) };
|
||||
let built = std::panic::catch_unwind(|| {
|
||||
egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 800.0)).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| {
|
||||
egui_kittest::Harness::builder().with_size(size).with_pixels_per_point(ppp).with_max_steps(64).wgpu().build_eframe(|cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default());
|
||||
if let Some(rs) = cc.wgpu_render_state.as_ref().filter(|_| gpu) {
|
||||
@@ -43,10 +50,11 @@ fn harness_with_scale(gpu: bool, ppp: f32) -> Option<Harness> {
|
||||
}
|
||||
}
|
||||
|
||||
fn control(h: &mut Harness, method: &str, params: Value) {
|
||||
fn set_view(h: &mut Harness, zoom: f32, center: [f32; 2]) {
|
||||
let ctx = h.ctx.clone();
|
||||
let (req, _rx) = ControlRequest::new(method, params);
|
||||
handle(h.state_mut(), &ctx, &req);
|
||||
let (req, _rx) = ControlRequest::new("ui.set", json!({"zoom": zoom, "center": center}));
|
||||
let Reply::Done(reply) = handle(h.state_mut(), &ctx, &req) else { panic!("setting the view did not finish") };
|
||||
assert_eq!(reply["ok"], true, "{reply}");
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
@@ -87,30 +95,23 @@ impl Shot {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a `doc` px square document at `zoom` (transparent, or filled black when `black`), renders
|
||||
/// it with the pixel grid on or off, and returns the screenshot with the document's left and top
|
||||
/// screen edge and its width in screen pixels.
|
||||
fn render(h: &mut Harness, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) {
|
||||
render_on(h, true, zoom, doc, black, grid)
|
||||
fn open_document(h: &mut Harness, doc: u32, black: bool, grid: bool) {
|
||||
let app = h.state_mut();
|
||||
while app.session.active().is_some() {
|
||||
app.run("file.close", json!({"discard": true})).expect("close");
|
||||
}
|
||||
let background = if black { "white" } else { "transparent" };
|
||||
app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new");
|
||||
if black {
|
||||
app.run("edit.fill", json!({"color": "#000000"})).expect("fill");
|
||||
}
|
||||
app.sync_views();
|
||||
app.ui.view.show.pixel_grid = grid;
|
||||
}
|
||||
|
||||
/// [`render`] on the GPU canvas (`gpu`) or the CPU canvas.
|
||||
fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool, grid: bool) -> (Shot, u32, u32, u32) {
|
||||
{
|
||||
let app = h.state_mut();
|
||||
while app.session.active().is_some() {
|
||||
app.run("file.close", json!({"discard": true})).expect("close");
|
||||
}
|
||||
let background = if black { "white" } else { "transparent" };
|
||||
app.run("file.new", json!({"width": doc, "height": doc, "background": background})).expect("new");
|
||||
if black {
|
||||
app.run("edit.fill", json!({"color": "#000000"})).expect("fill");
|
||||
}
|
||||
app.sync_views();
|
||||
app.ui.view.show.pixel_grid = grid;
|
||||
}
|
||||
control(h, "ui.set", json!({"zoom": zoom, "center": [doc as f32 / 2.0, doc as f32 / 2.0]}));
|
||||
h.run_steps(3);
|
||||
/// Zooms the current document and returns the screenshot and the document's physical-pixel bounds.
|
||||
fn render_on(h: &mut Harness, gpu: bool, zoom: f32, doc: u32, black: bool) -> (Shot, u32, u32, u32) {
|
||||
set_view(h, zoom, [doc as f32 / 2.0; 2]);
|
||||
assert_eq!(h.state().perf.gpu, gpu, "zoom {zoom}: expected the {} canvas", if gpu { "GPU" } else { "CPU" });
|
||||
let rendered = h.render().expect("render");
|
||||
let (width, height) = (rendered.width(), rendered.height());
|
||||
@@ -136,8 +137,13 @@ fn checker_cells_are_8_screen_pixels_at_every_zoom() {
|
||||
let Some(mut h) = harness() else { return };
|
||||
h.run_steps(4);
|
||||
// The 8 px cell never changes with the zoom.
|
||||
let mut current_size = 0;
|
||||
for (zoom, doc) in [(0.5, 64), (1.0, 64), (1.1, 64), (2.0, 32), (3.3, 32), (5.5, 32), (8.0, 32), (13.0, 32), (32.0, 12)] {
|
||||
let (img, x0, y0, _) = render(&mut h, zoom, doc, false, false);
|
||||
if current_size != doc {
|
||||
open_document(&mut h, doc, false, false);
|
||||
current_size = doc;
|
||||
}
|
||||
let (img, x0, y0, _) = render_on(&mut h, true, zoom, doc, false);
|
||||
let n = ((doc as f32 * zoom) / 8.0) as u32;
|
||||
assert!(n >= 2, "zoom {zoom}: test needs at least two cells");
|
||||
for row in 0..n.min(4) {
|
||||
@@ -170,10 +176,11 @@ fn pixel_grid_shows_above_500_percent_and_lightens_a_dark_pixel_by_about_a_quart
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness() else { return };
|
||||
h.run_steps(4);
|
||||
let (flat, x0, y0, _) = render(&mut h, 5.0, 48, true, true);
|
||||
open_document(&mut h, 48, true, true);
|
||||
let (flat, x0, y0, _) = render_on(&mut h, true, 5.0, 48, true);
|
||||
assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%");
|
||||
for zoom in [6.0f32, 8.0, 12.0] {
|
||||
let (img, x0, y0, _) = render(&mut h, zoom, 48, true, true);
|
||||
let (img, x0, y0, _) = render_on(&mut h, true, zoom, 48, true);
|
||||
let lit = lit_columns(&img, x0, y0 + (zoom * 3.5) as u32, (zoom * 10.0) as u32);
|
||||
assert_eq!(lit.len(), 10, "zoom {zoom}: grid columns {lit:?}");
|
||||
assert!(lit.windows(2).all(|p| p[1] - p[0] == zoom as u32), "zoom {zoom}: spacing of {lit:?}");
|
||||
@@ -187,8 +194,9 @@ fn pixel_grid_is_not_drawn_over_empty_checker() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness() else { return };
|
||||
h.run_steps(4);
|
||||
open_document(&mut h, 24, false, true);
|
||||
for zoom in [8.0f32, 16.0] {
|
||||
let (img, x0, y0, _) = render(&mut h, zoom, 24, false, true);
|
||||
let (img, x0, y0, _) = render_on(&mut h, true, zoom, 24, false);
|
||||
for y in y0..y0 + 64 {
|
||||
for x in x0..x0 + 64 {
|
||||
let v = img.at(x, y)[0];
|
||||
@@ -204,10 +212,11 @@ fn cpu_pixel_grid_shows_above_500_percent_over_content() {
|
||||
for ppp in [1.0, 2.0] {
|
||||
let Some(mut h) = harness_with_scale(false, ppp) else { return };
|
||||
h.run_steps(4);
|
||||
let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 48, true, true);
|
||||
open_document(&mut h, 48, true, true);
|
||||
let (flat, x0, y0, _) = render_on(&mut h, false, 5.0, 48, true);
|
||||
assert!(lit_columns(&flat, x0, y0 + 20, 100).is_empty(), "no grid at 500%");
|
||||
for zoom in [6.0f32, 8.0, 12.0] {
|
||||
let (img, x0, y0, _) = render_on(&mut h, false, zoom, 48, true, true);
|
||||
let (img, x0, y0, _) = render_on(&mut h, false, zoom, 48, true);
|
||||
let y = y0 + (zoom * 3.5) as u32;
|
||||
let lit = lit_columns(&img, x0, y, (zoom * 10.0) as u32);
|
||||
assert_eq!(lit.len(), 10, "scale {ppp}, zoom {zoom}: one physical pixel per line, columns {lit:?}");
|
||||
@@ -224,9 +233,12 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() {
|
||||
let Some(mut h) = harness_with(false) else { return };
|
||||
h.run_steps(4);
|
||||
// The CPU checker has soft cell edges of its own, so compare with and without the grid.
|
||||
open_document(&mut h, 24, false, false);
|
||||
for zoom in [8.0f32, 16.0] {
|
||||
let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false, false);
|
||||
let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false, true);
|
||||
h.state_mut().ui.view.show.pixel_grid = false;
|
||||
let (without, x0, y0, _) = render_on(&mut h, false, zoom, 24, false);
|
||||
h.state_mut().ui.view.show.pixel_grid = true;
|
||||
let (with, x1, y1, _) = render_on(&mut h, false, zoom, 24, false);
|
||||
assert_eq!((x0, y0), (x1, y1), "zoom {zoom}: the document moved");
|
||||
for y in y0..y0 + 64 {
|
||||
for x in x0..x0 + 64 {
|
||||
@@ -236,56 +248,48 @@ fn cpu_pixel_grid_is_not_drawn_over_empty_checker() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel grid over a flat `grey` document at 800%: the largest difference, in 8-bit levels,
|
||||
/// between a grid line and the pixel interior beside it.
|
||||
fn grid_line_contrast_over_grey(h: &mut Harness, grey: u8) -> i32 {
|
||||
{
|
||||
let app = h.state_mut();
|
||||
while app.session.active().is_some() {
|
||||
app.run("file.close", json!({"discard": true})).expect("close");
|
||||
}
|
||||
app.run("file.new", json!({"width": 48, "height": 48, "background": "white"})).expect("new");
|
||||
app.run("edit.fill", json!({"color": format!("#{grey:02x}{grey:02x}{grey:02x}")})).expect("fill");
|
||||
app.sync_views();
|
||||
app.ui.view.show.pixel_grid = true;
|
||||
}
|
||||
control(h, "ui.set", json!({"zoom": 8.0, "center": [24.0, 24.0]}));
|
||||
h.run_steps(3);
|
||||
assert!(h.state().perf.gpu, "expected the GPU canvas");
|
||||
let rendered = h.render().expect("render");
|
||||
let img = Shot { w: rendered.width(), px: rendered.into_raw() };
|
||||
let r = h.state().last_canvas_rect;
|
||||
let (cx, cy) = (r.center().x as u32, r.center().y as u32);
|
||||
// The median of an 8 px block is a pixel interior whichever line the block straddles.
|
||||
let mut block: Vec<i32> = (0..64).map(|i| img.at(cx + i % 8, cy + i / 8)[0] as i32).collect();
|
||||
block.sort_unstable();
|
||||
let interior = block[32];
|
||||
// Walk out to the document edge: the pasteboard is far darker than any grid line.
|
||||
let near = |x: u32, y: u32| (img.at(x, y)[0] as i32 - interior).abs() < 50;
|
||||
let x0 = (0..=cx).rev().take_while(|x| near(*x, cy)).last().unwrap_or(cx);
|
||||
let y0 = (0..=cy).rev().take_while(|y| near(cx, *y)).last().unwrap_or(cy);
|
||||
// Pixel (col, row) owns the grid line on its left and top edge, 8 screen px apart.
|
||||
let y = y0 + 8 * 3 + 4;
|
||||
(2..6).map(|col| (img.at(x0 + 8 * col, y)[0] as i32 - img.at(x0 + 8 * col + 4, y)[0] as i32).abs()).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_grid_does_not_flip_colour_across_mid_tones() {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
let Some(mut h) = harness() else { return };
|
||||
h.run_steps(4);
|
||||
// 0x87 and 0x90 sit either side of luma 0.55, where the line used to switch from a full white
|
||||
// line to a full black one. Both now give a faint line, so neighbouring cells match.
|
||||
for grey in [0x87u8, 0x90] {
|
||||
let c = grid_line_contrast_over_grey(&mut h, grey);
|
||||
assert!(c <= 14, "grey {grey:#04x}: grid line differs from its pixel by {c} levels, want a faint line");
|
||||
// Put both sides of the old luma cutoff and the stronger dark/light lines in one frame.
|
||||
// Sample inside each swatch so an edge between swatches cannot pass as a grid line.
|
||||
let greys = [0x87u8, 0x90, 0x60, 0xd0, 0xff];
|
||||
let mut doc = Document::new("grid midtones", Size::new(40, 16), ColorMode::Rgb, SampleType::U8);
|
||||
let mut surface = Surface::new(doc.pixel_format());
|
||||
for (i, grey) in greys.into_iter().enumerate() {
|
||||
let x = i as i32 * 8;
|
||||
let v = f32::from(grey) / 255.0;
|
||||
surface.fill_rect(Rect::new(x, 0, x + 8, 16), &[v, v, v, 1.0]);
|
||||
}
|
||||
// The fade must not remove the grid where it is needed: dark and light pixels keep a clear
|
||||
// line (white over 0x60, black over 0xd0 and white; black itself is in the unit tests, as the
|
||||
// dark pasteboard defeats this walk to the document edge).
|
||||
for grey in [0x60u8, 0xd0, 0xff] {
|
||||
let c = grid_line_contrast_over_grey(&mut h, grey);
|
||||
assert!(c >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {c} levels");
|
||||
doc.layers.push(Layer::new("swatches", LayerContent::Raster(surface)));
|
||||
let app = h.state_mut();
|
||||
app.session.add_document(doc, None);
|
||||
app.sync_views();
|
||||
app.ui.view.show.pixel_grid = true;
|
||||
set_view(&mut h, 8.0, [20.0, 8.0]);
|
||||
assert!(h.state().perf.gpu);
|
||||
let img = h.render().expect("render swatches");
|
||||
let center = h.state().last_canvas_rect.center();
|
||||
let x0 = (center.x - 20.0 * 8.0).round() as u32;
|
||||
let y = (center.y + 3.5 * 8.0).round() as u32;
|
||||
for (i, grey) in greys.into_iter().enumerate() {
|
||||
let x = x0 + i as u32 * 64;
|
||||
let contrast = (2..6)
|
||||
.map(|col| {
|
||||
let edge = x + 8 * col;
|
||||
let inside = img.get_pixel(edge + 4, y)[0];
|
||||
assert!(inside.abs_diff(grey) <= 1, "wrong swatch at {edge}: {inside} vs {grey}");
|
||||
(edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, y)[0].abs_diff(inside)).max().expect("grid line")
|
||||
})
|
||||
.max()
|
||||
.expect("swatch columns");
|
||||
if i < 2 {
|
||||
assert!(contrast <= 14, "grey {grey:#04x}: grid line differs from its pixel by {contrast} levels, want a faint line");
|
||||
} else {
|
||||
assert!(contrast >= 20, "grey {grey:#04x}: grid line differs from its pixel by only {contrast} levels");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,8 +300,7 @@ fn pixel_grid_does_not_flip_colour_across_mid_tones() {
|
||||
/// it, which the `inside` assertion reads: on the GPU canvas its texture (`Rgba8Unorm` for 8-bit, `Rgba16Float` for
|
||||
/// 16/32-bit, see `canvas_16f.rs`). So every canvas and scale runs 8-bit, and the GPU canvas adds 16-bit at 1x and
|
||||
/// 32-bit at 2x.
|
||||
fn grid_depths(gpu: bool, ppp: f32) -> Vec<photocraft_color::SampleType> {
|
||||
use photocraft_color::SampleType;
|
||||
fn grid_depths(gpu: bool, ppp: f32) -> Vec<SampleType> {
|
||||
match (gpu, ppp > 1.0) {
|
||||
(true, false) => vec![SampleType::U8, SampleType::U16],
|
||||
(true, true) => vec![SampleType::U8, SampleType::F32],
|
||||
@@ -307,36 +310,42 @@ fn grid_depths(gpu: bool, ppp: f32) -> Vec<photocraft_color::SampleType> {
|
||||
|
||||
fn pixel_grid_is_solid_and_visible_at_scale(gpu: bool, ppp: f32) {
|
||||
let _gpu = photocraft_testkit::gpu_lock();
|
||||
use photocraft_color::{ColorMode, PixelFormat};
|
||||
use photocraft_doc::{Document, Layer, LayerContent, Size};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
let Some(mut h) = harness_with_scale(gpu, ppp) else { return };
|
||||
for depth in grid_depths(gpu, ppp) {
|
||||
for v in [0.0, 1.0] {
|
||||
let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth);
|
||||
let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true));
|
||||
surface.fill_rect(Rect::new(0, 0, 32, 16), &[v, v, v, 1.0]);
|
||||
doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface)));
|
||||
let app = h.state_mut();
|
||||
app.session.add_document(doc, None);
|
||||
app.sync_views();
|
||||
app.ui.view.show.pixel_grid = true;
|
||||
for zoom in [7.119, 8.0, 22.825] {
|
||||
control(&mut h, "ui.set", json!({"zoom": zoom, "center": [16.0, 8.0]}));
|
||||
assert_eq!(h.state().perf.gpu, gpu);
|
||||
let img = h.render().expect("render opaque grid");
|
||||
let center = h.state().last_canvas_rect.center() * ppp;
|
||||
let x0 = center.x - 16.0 * zoom;
|
||||
let y = (center.y + 3.25 * zoom).floor() as u32;
|
||||
let mut doc = Document::new("grid contrast", Size::new(32, 16), ColorMode::Rgb, depth);
|
||||
let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true));
|
||||
// Both neutral fills take the same grid draw path, with opposite line contrast.
|
||||
// Separate rows let them share one readback at each depth and zoom.
|
||||
surface.fill_rect(Rect::new(0, 0, 32, 8), &[0.0, 0.0, 0.0, 1.0]);
|
||||
surface.fill_rect(Rect::new(0, 8, 32, 16), &[1.0; 4]);
|
||||
doc.layers.push(Layer::new("opaque", LayerContent::Raster(surface)));
|
||||
let app = h.state_mut();
|
||||
app.session.add_document(doc, None);
|
||||
app.sync_views();
|
||||
app.ui.view.show.pixel_grid = true;
|
||||
// The 8-bit case also covers the threshold on both canvases at both display scales.
|
||||
let zooms: &[f32] = if depth == SampleType::U8 { &[5.0, 7.119, 8.0, 22.825] } else { &[7.119, 8.0, 22.825] };
|
||||
for &zoom in zooms {
|
||||
set_view(&mut h, zoom, [16.0, 8.0]);
|
||||
assert_eq!(h.state().perf.gpu, gpu);
|
||||
assert_eq!(h.ctx.pixels_per_point(), ppp);
|
||||
let img = h.render().expect("render opaque grid");
|
||||
let center = h.state().last_canvas_rect.center() * ppp;
|
||||
let x0 = center.x - 16.0 * zoom;
|
||||
for (v, dy) in [(0, -2.75), (255, 3.25)] {
|
||||
let y = (center.y + dy * zoom).floor() as u32;
|
||||
for x in 2..30 {
|
||||
let edge = (x0 + x as f32 * zoom).floor() as u32;
|
||||
for sy in y..y + 3 {
|
||||
let inside = img.get_pixel((x0 + (x as f32 + 0.5) * zoom).floor() as u32, sy)[0];
|
||||
assert_eq!(inside, (v * 255.0) as u8);
|
||||
assert_eq!(inside, v);
|
||||
let contrast = (edge - 1..=edge + 1).map(|sx| img.get_pixel(sx, sy)[0].abs_diff(inside)).max().expect("line");
|
||||
assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})");
|
||||
if zoom == 5.0 {
|
||||
assert_eq!(contrast, 0, "grid visible at 500%, {gpu:?}/{depth:?}, scale {ppp}, fill {v}");
|
||||
} else {
|
||||
assert!(contrast >= 28, "{gpu:?}/{depth:?}, scale {ppp}, zoom {zoom}, fill {v}, ({x}, {sy}): invisible grid ({contrast})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,8 +246,8 @@ fn marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x() {
|
||||
}
|
||||
// Each move's frame shows the outline where the pointer is now (no stale frame).
|
||||
pointer_move(&mut h, 340.0, 250.0);
|
||||
let img = render(&mut h);
|
||||
if tool == "rectMarquee" {
|
||||
let img = render(&mut h);
|
||||
let [top, right, ..] = edges(&h, a, [340.0, 250.0]);
|
||||
for (ink, test) in inks() {
|
||||
assert!(coverage(&img, ppp, top.0, top.1, test) > 0.3, "{tool} @{ppp}x: top edge follows the pointer ({ink})");
|
||||
|
||||
@@ -141,7 +141,6 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) {
|
||||
// The smoothing tool option syncs on the first frame with the Brush: set it after.
|
||||
h.state_mut().session.tools.brush.smoothing.amount = c.smoothing;
|
||||
let canvas = |h: &mut Harness| {
|
||||
h.run_steps(3);
|
||||
let r = h.state().last_canvas_rect.shrink(4.0);
|
||||
let img = h.render().expect("render");
|
||||
let mut px = Vec::new();
|
||||
@@ -152,6 +151,7 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) {
|
||||
}
|
||||
px
|
||||
};
|
||||
h.run_steps(3);
|
||||
let before = canvas(h);
|
||||
let pressure = |t: f64| if c.pressure { 0.3 + 0.7 * t } else { 1.0 };
|
||||
control(h, "ui.pointer", json!({"events": [{"kind": "down", "x": 100, "y": 100, "pressure": pressure(0.0)}]}));
|
||||
@@ -168,11 +168,12 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) {
|
||||
// The pointer stays held at its last point, as a mouse held still repeats its position.
|
||||
let held = |h: &mut Harness| {
|
||||
control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(1.0)}]}));
|
||||
canvas(h)
|
||||
h.run_steps(3);
|
||||
};
|
||||
let drawing = settled(h, held);
|
||||
let drawing = settled(h, held, canvas);
|
||||
let gpu = h.state().perf.gpu && !c.flip;
|
||||
control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]}));
|
||||
h.run_steps(3);
|
||||
let done = canvas(h);
|
||||
(before, drawing, done, gpu)
|
||||
}
|
||||
@@ -180,22 +181,28 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) {
|
||||
/// The canvas once the live stroke has stopped changing (#13477). The stroke paints on its own
|
||||
/// thread and a frame waits only a few real ms for it, so on a slow machine its newest step
|
||||
/// arrives late, and only a later pointer event shows it; release would then paint the rest.
|
||||
/// `picture` holds the pointer still and takes a picture, with short real waits between them,
|
||||
/// until the stroke is idle and three pictures in a row match (matching pixels alone don't prove
|
||||
/// a slow step has finished): at most `TRIES` times, so a canvas that never settles fails
|
||||
/// instead of hanging or comparing an unsettled picture.
|
||||
fn settled(h: &mut Harness, picture: impl Fn(&mut Harness) -> Pixels) -> Pixels {
|
||||
/// Keep feeding the held pointer until the stroke is idle and three pictures in a row match.
|
||||
/// A busy stroke can't be stable, so advance those frames without a GPU readback.
|
||||
fn settled(h: &mut Harness, held: impl Fn(&mut Harness), picture: impl Fn(&mut Harness) -> Pixels) -> Pixels {
|
||||
const TRIES: usize = 80;
|
||||
let mut last = picture(h);
|
||||
let mut last = None;
|
||||
let mut unchanged = 0;
|
||||
for _ in 0..TRIES {
|
||||
std::thread::sleep(std::time::Duration::from_millis(25));
|
||||
let next = picture(h);
|
||||
unchanged = if next == last { unchanged + 1 } else { 0 };
|
||||
last = next;
|
||||
if unchanged >= 2 && !h.state().live_stroke_busy() {
|
||||
return last;
|
||||
for attempt in 0..=TRIES {
|
||||
if attempt != 0 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(25));
|
||||
}
|
||||
held(h);
|
||||
if h.state().live_stroke_busy() {
|
||||
last = None;
|
||||
unchanged = 0;
|
||||
continue;
|
||||
}
|
||||
let next = picture(h);
|
||||
unchanged = if last.as_ref() == Some(&next) { unchanged + 1 } else { 0 };
|
||||
if unchanged >= 2 {
|
||||
return next;
|
||||
}
|
||||
last = Some(next);
|
||||
}
|
||||
panic!("the live stroke did not settle before release");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user