mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
11476 lines
511 KiB
Rust
11476 lines
511 KiB
Rust
//! Renders scenes that stress Vello GPU on the machine's GPU, skipping when none is available.
|
||
//!
|
||
//! wgpu's environment variables pick the backend and shader compiler they run on, so one machine can cover several. On Windows, for instance,
|
||
//! `WGPU_BACKEND` takes `dx12`, `vulkan`, or `gl`, `WGPU_DX12_COMPILER` takes `fxc` or `dxc`, and `WGPU_DEBUG=0` builds shaders as a release build does.
|
||
|
||
use crate::WgpuExecutor;
|
||
use core_types::blending::BlendMode;
|
||
use glam::{DAffine2, UVec2};
|
||
use graphic_types::MinimumMaximumMode;
|
||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||
use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2};
|
||
use vello_gpu::peniko::{self, Color, Fill};
|
||
|
||
/// The executor every test shares, or `None` without a GPU.
|
||
fn executor() -> Option<&'static WgpuExecutor> {
|
||
static EXECUTOR: std::sync::OnceLock<Option<WgpuExecutor>> = std::sync::OnceLock::new();
|
||
EXECUTOR
|
||
.get_or_init(|| futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(WgpuExecutor::with_context))
|
||
.as_ref()
|
||
}
|
||
|
||
/// Held while a test uses the shared GPU, since another test's work can delay a render's readback.
|
||
fn take_turn() -> std::sync::MutexGuard<'static, ()> {
|
||
static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||
TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||
}
|
||
|
||
/// Renders the scene `draw` draws into straight-alpha RGBA8 pixels, or `None` without a GPU.
|
||
fn render(size: UVec2, draw: impl FnMut(&mut VelloSceneBuilder)) -> Option<Vec<[u8; 4]>> {
|
||
render_timed(size, draw).map(|(pixels, _)| pixels)
|
||
}
|
||
|
||
/// Like [`render`], through a `view` from the document into the render's pixels.
|
||
fn render_in_view(size: UVec2, view: DAffine2, mut draw: impl FnMut(&mut VelloSceneBuilder)) -> Option<Vec<[u8; 4]>> {
|
||
let executor = executor()?;
|
||
let _turn = take_turn();
|
||
|
||
let texture = executor.render_vello(size, view, &mut draw).unwrap_or_else(|error| panic!("Render failed: {error}"));
|
||
let pixels = executor.read_texture_pixels(&texture).expect("Failed to read back the render");
|
||
Some(pixels.as_chunks::<4>().0.to_vec())
|
||
}
|
||
|
||
/// Renders the scene `draw` draws into straight-alpha RGBA8 pixels, with how long the render and its readback took, or `None` without a GPU.
|
||
fn render_timed(size: UVec2, mut draw: impl FnMut(&mut VelloSceneBuilder)) -> Option<(Vec<[u8; 4]>, std::time::Duration)> {
|
||
let executor = executor()?;
|
||
let _turn = take_turn();
|
||
let start = std::time::Instant::now();
|
||
|
||
let texture = match executor.render_vello(size, DAffine2::IDENTITY, &mut draw) {
|
||
Ok(texture) => texture,
|
||
Err(error) => panic!("Render failed: {error}"),
|
||
};
|
||
let pixels = executor.read_texture_pixels(&texture).expect("Failed to read back the render");
|
||
|
||
Some((pixels.as_chunks::<4>().0.to_vec(), start.elapsed()))
|
||
}
|
||
|
||
/// A circle drawn with four cubic segments, as Graphite's vector shapes are, rather than kurbo's tolerance-dependent count.
|
||
fn circle(center: (f64, f64), radius: f64) -> BezPath {
|
||
const HANDLE: f64 = 0.552_284_749_830_793_4;
|
||
let (x, y) = center;
|
||
let (r, h) = (radius, radius * HANDLE);
|
||
|
||
let mut path = BezPath::new();
|
||
path.move_to((x + r, y));
|
||
path.curve_to((x + r, y + h), (x + h, y + r), (x, y + r));
|
||
path.curve_to((x - h, y + r), (x - r, y + h), (x - r, y));
|
||
path.curve_to((x - r, y - h), (x - h, y - r), (x, y - r));
|
||
path.curve_to((x + h, y - r), (x + r, y - h), (x + r, y));
|
||
path.close_path();
|
||
path
|
||
}
|
||
|
||
fn pixel(pixels: &[[u8; 4]], size: UVec2, x: u32, y: u32) -> [u8; 4] {
|
||
pixels[(y * size.x + x) as usize]
|
||
}
|
||
|
||
/// A Minimum/Maximum effect of the `radius` in the `mode`.
|
||
fn minimum_maximum(radius: f64, mode: MinimumMaximumMode) -> graphic_types::EffectOperation {
|
||
graphic_types::EffectOperation::MinimumMaximum { radius, mode }
|
||
}
|
||
|
||
const RED: Color = Color::from_rgb8(255, 0, 0);
|
||
const BLUE: Color = Color::from_rgb8(0, 0, 255);
|
||
|
||
#[test]
|
||
fn dense_strokes_render() {
|
||
let size = UVec2::new(2048, 2048);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
for i in 0..40_000 {
|
||
let y = (i as f64 * 0.0511) % 2048.;
|
||
scene.stroke(&Stroke::new(1.), Affine::IDENTITY, RED, None, &Line::new((0., y), (2048., y + 3.)));
|
||
}
|
||
};
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 1024, 1024)[3], 255);
|
||
}
|
||
|
||
#[test]
|
||
fn huge_circle_edge_lands_on_the_right_pixel() {
|
||
let size = UVec2::new(256, 256);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
for radius in [1e6, 1e9, 1e12] {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &circle((128. - radius, 128.), radius));
|
||
}
|
||
};
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 120, 128)[3], 255, "inside");
|
||
assert_eq!(pixel(&pixels, size, 136, 128)[3], 0, "outside");
|
||
}
|
||
|
||
#[test]
|
||
fn huge_curves_through_the_viewport_render_quickly() {
|
||
let size = UVec2::new(256, 256);
|
||
for radius in [1e13, 1e14, 1e15] {
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &circle((128. - radius, 128.), radius));
|
||
scene.stroke(&Stroke::new(4.), Affine::IDENTITY, RED, None, &circle((200. + radius, 128.), radius));
|
||
};
|
||
|
||
let Some((pixels, duration)) = render_timed(size, draw) else { return };
|
||
println!("Radius {radius}: {duration:?}");
|
||
assert!(duration.as_secs_f64() < 2., "radius {radius} took {duration:?}");
|
||
assert_eq!(pixel(&pixels, size, 120, 128)[3], 255, "inside at radius {radius}");
|
||
assert_eq!(pixel(&pixels, size, 160, 128)[3], 0, "outside at radius {radius}");
|
||
assert_eq!(pixel(&pixels, size, 200, 128)[3], 255, "stroke at radius {radius}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn astronomical_fills_render_quickly() {
|
||
let size = UVec2::new(256, 256);
|
||
for radius in [1e18, 1e30, 1e100, 1e300] {
|
||
let draw = |scene: &mut VelloSceneBuilder| scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &circle((0., 0.), radius));
|
||
|
||
let Some((pixels, duration)) = render_timed(size, draw) else { return };
|
||
println!("Fill radius {radius}: {duration:?}");
|
||
assert!(duration.as_secs_f64() < 2., "radius {radius} took {duration:?}");
|
||
assert_eq!(pixel(&pixels, size, 128, 128)[3], 255, "inside at radius {radius}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn astronomical_strokes_render_quickly() {
|
||
let size = UVec2::new(256, 256);
|
||
for radius in [1e18, 1e30, 1e100, 1e300] {
|
||
let draw = |scene: &mut VelloSceneBuilder| scene.stroke(&Stroke::new(1e3), Affine::IDENTITY, RED, None, &circle((0., 0.), radius));
|
||
|
||
let Some((pixels, duration)) = render_timed(size, draw) else { return };
|
||
println!("Stroke radius {radius}: {duration:?}");
|
||
assert!(duration.as_secs_f64() < 2., "radius {radius} took {duration:?}");
|
||
assert_eq!(pixel(&pixels, size, 128, 128)[3], 0, "far inside at radius {radius}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn enormous_line_renders() {
|
||
let size = UVec2::new(256, 256);
|
||
let draw = |scene: &mut VelloSceneBuilder| scene.stroke(&Stroke::new(4.), Affine::IDENTITY, RED, None, &Line::new((-1e30, 100.), (1e30, 100.)));
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 128, 100)[3], 255);
|
||
}
|
||
|
||
#[test]
|
||
fn infinite_line_renders() {
|
||
let size = UVec2::new(256, 256);
|
||
let mut path = BezPath::new();
|
||
path.move_to((-5., f64::INFINITY));
|
||
path.line_to((5., f64::NEG_INFINITY));
|
||
let draw = |scene: &mut VelloSceneBuilder| scene.stroke(&Stroke::new(4.), Affine::translate((128., 0.)), RED, None, &path);
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 128, 128)[3], 255);
|
||
}
|
||
|
||
/// A view at `zoom` and `tilt` that places the document point `target` at the pixel `pixel`.
|
||
fn deep_view(zoom: f64, tilt: f64, target: Point, pixel: Point) -> Affine {
|
||
Affine::translate(pixel.to_vec2()) * Affine::rotate(tilt) * Affine::scale(zoom) * Affine::translate(-target.to_vec2())
|
||
}
|
||
|
||
#[test]
|
||
fn deep_zoomed_edges_land_on_the_right_pixel() {
|
||
let size = UVec2::new(256, 256);
|
||
let middle = Point::new(128., 128.);
|
||
let (center, radius) = ((1234.5678, -987.6543), 100.);
|
||
let path = circle(center, radius);
|
||
|
||
// The middle of a segment, where a stroke's fitted outline strays furthest, and outward from the circle by the segment's symmetry
|
||
let Some(PathSeg::Cubic(segment)) = path.get_seg(2) else {
|
||
panic!("The circle's second segment is a cubic")
|
||
};
|
||
let on_curve = segment.eval(0.5);
|
||
let outward = (on_curve - Point::from(center)).normalize();
|
||
|
||
for zoom in [1e4, 1e7, 1e10] {
|
||
for tilt in [0., 0.3, std::f64::consts::FRAC_PI_2, 2.4] {
|
||
// The edge belongs at the middle pixel, with the shape covering what's inward of it
|
||
for (label, target, stroke) in [("fill", on_curve, None), ("stroke", on_curve + outward, Some(Stroke::new(2.)))] {
|
||
let view = deep_view(zoom, tilt, target, middle);
|
||
let Some(pixels) = render(size, |scene| match &stroke {
|
||
Some(stroke) => scene.stroke(stroke, view, RED, None, &path),
|
||
None => scene.fill(Fill::NonZero, view, RED, None, &path),
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// Walking inward from outside to the first mostly covered pixel
|
||
let screen_outward = (view * (target + outward / zoom)) - middle;
|
||
let covered_at = (-40..=40_i32).rev().find(|&distance| {
|
||
let point = middle + screen_outward * distance as f64;
|
||
pixel(&pixels, size, point.x as u32, point.y as u32)[3] >= 128
|
||
});
|
||
assert!(
|
||
covered_at.is_some_and(|distance| distance.abs() <= 2),
|
||
"the {label} edge at zoom {zoom} and tilt {tilt} lands {covered_at:?} pixels outward"
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn deep_zoomed_images_blend_their_texels_precisely() {
|
||
let size = UVec2::new(256, 256);
|
||
|
||
// A red texel beside a blue one, sampled as Graphite draws images, viewed a quarter texel past the edge between them
|
||
let image = peniko::ImageBrush::new(peniko::ImageData {
|
||
data: [255, 0, 0, 255, 0, 0, 255, 255].to_vec().into(),
|
||
format: peniko::ImageFormat::Rgba8,
|
||
alpha_type: peniko::ImageAlphaType::Alpha,
|
||
width: 2,
|
||
height: 1,
|
||
})
|
||
.with_extend(peniko::Extend::Pad);
|
||
let origin = Point::new(1234.5678, -987.6543);
|
||
let target = origin + Vec2::new(1.25, 0.5);
|
||
|
||
for zoom in [1e6, 1e8, 1e10] {
|
||
let view = deep_view(zoom, 0., target, Point::new(128., 128.)) * Affine::translate(origin.to_vec2());
|
||
let Some(pixels) = render(size, |scene| scene.draw_image(&image, view)) else { return };
|
||
|
||
for x in [0, 128, 255] {
|
||
let red = pixel(&pixels, size, x, 128)[0];
|
||
assert!(red.abs_diff(64) <= 2, "the image at zoom {zoom} blends to red {red} rather than 64 at pixel {x}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn nan_points_render_nothing_wrong() {
|
||
let size = UVec2::new(256, 256);
|
||
let mut path = BezPath::new();
|
||
path.move_to((10., 10.));
|
||
path.line_to((f64::NAN, 100.));
|
||
path.line_to((100., 100.));
|
||
path.close_path();
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &path);
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(200., 200., 250., 250.));
|
||
};
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 225, 225)[3], 255);
|
||
}
|
||
|
||
#[test]
|
||
fn many_gradients_render() {
|
||
let size = UVec2::new(1024, 1024);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
for i in 0..250_000_u32 {
|
||
let (x, y) = ((i % 500) as f64 * 2., (i / 500) as f64 * 2.);
|
||
let gradient = peniko::Gradient::new_linear((x, y), (x + 2., y)).with_stops([Color::from_rgb8((i % 256) as u8, 0, 0), Color::from_rgb8(0, (i / 256 % 256) as u8, 255)]);
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, &gradient, None, &Rect::new(x, y, x + 2., y + 2.));
|
||
}
|
||
};
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 500, 500)[3], 255);
|
||
}
|
||
|
||
#[test]
|
||
fn deep_layer_nesting_renders() {
|
||
let size = UVec2::new(256, 256);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
for _ in 0..2000 {
|
||
scene.push_layer(Fill::NonZero, peniko::Mix::Multiply, 1., Affine::IDENTITY, &Rect::new(0., 0., 256., 256.));
|
||
}
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 256., 256.));
|
||
for _ in 0..2000 {
|
||
scene.pop_layer();
|
||
}
|
||
};
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 128, 128)[3], 255);
|
||
}
|
||
|
||
#[test]
|
||
fn render_larger_than_the_texture_limit_is_refused() {
|
||
let Some(executor) = executor() else { return };
|
||
let limit = executor.context().device.limits().max_texture_dimension_2d;
|
||
let size = UVec2::new(limit + 100, 16);
|
||
let texture = executor.render_vello(size, DAffine2::IDENTITY, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 1e6, 1e6))
|
||
});
|
||
assert!(texture.is_err());
|
||
}
|
||
|
||
#[test]
|
||
fn layer_four_times_the_layer_limit_renders_across_nested_splits() {
|
||
let Some(executor) = executor() else { return };
|
||
let quarter = crate::MAX_LAYER_RENDER_SIZE;
|
||
if executor.context().device.limits().max_texture_dimension_2d < 4 * quarter {
|
||
return;
|
||
}
|
||
|
||
// The layer spans the whole render, so it only fits once the render is halved twice
|
||
let size = UVec2::new(4 * quarter, 8);
|
||
let boundary = quarter * 3 / 2;
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.push_layer(Fill::NonZero, peniko::Mix::Normal, 0.5, Affine::IDENTITY, &Rect::new(0., 0., size.x as f64, 8.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., boundary as f64, 8.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(boundary as f64, 0., size.x as f64, 8.));
|
||
scene.pop_layer();
|
||
};
|
||
|
||
// Each side of the seams between quarters, and of the color boundary, which must land where it was drawn
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
for x in [quarter - 1, quarter, boundary - 1, boundary, 2 * quarter - 1, 2 * quarter, 3 * quarter - 1, 3 * quarter] {
|
||
let [r, g, b, a] = pixel(&pixels, size, x, 4);
|
||
let expected = if x < boundary { [255, 0, 0] } else { [0, 0, 255] };
|
||
assert_eq!([r, g, b], expected, "color at x = {x}");
|
||
assert!(a.abs_diff(128) <= 1, "alpha {a} at x = {x}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn huge_image_renders() {
|
||
let size = UVec2::new(256, 256);
|
||
let (width, height) = (70_000_u32, 4_u32);
|
||
let data: Vec<u8> = (0..width * height).flat_map(|_| [255, 0, 0, 255]).collect();
|
||
let image = peniko::ImageBrush::new(peniko::ImageData {
|
||
data: data.into(),
|
||
format: peniko::ImageFormat::Rgba8,
|
||
alpha_type: peniko::ImageAlphaType::Alpha,
|
||
width,
|
||
height,
|
||
});
|
||
let draw = |scene: &mut VelloSceneBuilder| scene.draw_image(&image, Affine::scale_non_uniform(256. / width as f64, 64.));
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert_eq!(pixel(&pixels, size, 128, 128)[3], 255);
|
||
}
|
||
|
||
#[test]
|
||
fn degenerate_strokes_render() {
|
||
let size = UVec2::new(256, 256);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.stroke(&Stroke::new(1e20), Affine::IDENTITY, RED, None, &Line::new((10., 10.), (20., 20.)));
|
||
scene.stroke(&Stroke::new(f64::NAN), Affine::IDENTITY, RED, None, &Line::new((10., 10.), (20., 20.)));
|
||
scene.stroke(&Stroke::new(5.), Affine::scale(0.), RED, None, &Line::new((10., 10.), (20., 20.)));
|
||
scene.stroke(&Stroke::new(5.), Affine::scale(f64::INFINITY), RED, None, &Line::new((10., 10.), (20., 20.)));
|
||
scene.stroke(&Stroke::new(5.), Affine::IDENTITY, RED, None, &Line::new((50., 50.), (50., 50.)));
|
||
};
|
||
|
||
let Some(_) = render(size, draw) else { return };
|
||
}
|
||
|
||
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
|
||
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||
render_square_with_effects_in(effects, DAffine2::IDENTITY, fill, min, max, size)
|
||
}
|
||
|
||
/// Like [`render_square_with_effects`], carrying out the effects in an `effect_space` placed in the document.
|
||
fn render_square_with_effects_in(effects: Vec<graphic_types::EffectOperation>, effect_space: DAffine2, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||
render_square_over_backdrop_in(effects, effect_space, fill, 1., core_types::blending::BlendMode::Normal, None, Color::WHITE, min, max, size)
|
||
}
|
||
|
||
/// Renders a square of the `content` color from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`, `opacity`, and `blend_mode`, over a `backdrop` color filling the render if there is one.
|
||
#[expect(clippy::too_many_arguments)]
|
||
fn render_square_over_backdrop(
|
||
effects: Vec<graphic_types::EffectOperation>,
|
||
fill: f32,
|
||
opacity: f32,
|
||
blend_mode: core_types::blending::BlendMode,
|
||
backdrop: Option<Color>,
|
||
content: Color,
|
||
min: f64,
|
||
max: f64,
|
||
size: UVec2,
|
||
) -> Option<Vec<[u8; 4]>> {
|
||
render_square_over_backdrop_in(effects, DAffine2::IDENTITY, fill, opacity, blend_mode, backdrop, content, min, max, size)
|
||
}
|
||
|
||
/// Like [`render_square_over_backdrop`], carrying out the effects in an `effect_space` placed in the document.
|
||
#[expect(clippy::too_many_arguments)]
|
||
fn render_square_over_backdrop_in(
|
||
effects: Vec<graphic_types::EffectOperation>,
|
||
effect_space: DAffine2,
|
||
fill: f32,
|
||
opacity: f32,
|
||
blend_mode: core_types::blending::BlendMode,
|
||
backdrop: Option<Color>,
|
||
content: Color,
|
||
min: f64,
|
||
max: f64,
|
||
size: UVec2,
|
||
) -> Option<Vec<[u8; 4]>> {
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let square = Rect::new(min, min, max, max);
|
||
|
||
// The effects' drawn paints, drawn as the renderer does for content placed in the scene's space
|
||
let paints: Vec<graphic_types::Graphic> = effects.iter().flat_map(|operation| operation.drawn_paints().cloned()).collect();
|
||
let mut draw_paint = |index: usize, scene: &mut VelloSceneBuilder| {
|
||
if let Some(paint) = paints.get(index) {
|
||
paint.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default().for_pattern());
|
||
}
|
||
};
|
||
|
||
let effects = graphic_types::Effects::from_operations(effects);
|
||
let frame = graphic_types::resampling::frame_of_bounds([glam::DVec2::splat(min), glam::DVec2::splat(max)], DAffine2::IDENTITY);
|
||
render(size, |scene| {
|
||
if let Some(backdrop) = backdrop {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, backdrop, None, &Rect::new(0., 0., size.x as f64, size.y as f64));
|
||
}
|
||
scene.draw_effects(
|
||
&effects,
|
||
fill,
|
||
opacity,
|
||
blend_mode,
|
||
true,
|
||
Some(square),
|
||
effect_space,
|
||
Some((frame, 0.)),
|
||
&mut draw_paint,
|
||
&mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, content, None, &square),
|
||
);
|
||
})
|
||
}
|
||
|
||
/// A drop shadow falling at `offset` from the content, with its own `size` and `spread` percentage, knocked out by the content.
|
||
fn drop_shadow(color: core_types::Color, offset: glam::DVec2, size: f64, spread: f64) -> graphic_types::EffectOperation {
|
||
graphic_types::EffectOperation::DropShadow {
|
||
color,
|
||
blend_mode: core_types::blending::BlendMode::Normal,
|
||
angle: offset.y.atan2(-offset.x).to_degrees(),
|
||
distance: offset.length(),
|
||
spread,
|
||
size,
|
||
contour: Default::default(),
|
||
knockout: true,
|
||
}
|
||
}
|
||
|
||
/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7.
|
||
fn normal_cdf(x: f64) -> f64 {
|
||
let z = x.abs() / std::f64::consts::SQRT_2;
|
||
let t = 1. / (1. + 0.327_591_1 * z);
|
||
let polynomial = t * (0.254_829_592 + t * (-0.284_496_736 + t * (1.421_413_741 + t * (-1.453_152_027 + t * 1.061_405_429))));
|
||
let erf = 1. - polynomial * (-z * z).exp();
|
||
|
||
if x >= 0. { 0.5 * (1. + erf) } else { 0.5 * (1. - erf) }
|
||
}
|
||
|
||
#[test]
|
||
fn gaussian_blur_follows_the_normal_distribution() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(512, 256);
|
||
// Small kernels run directly, and larger ones on halved textures
|
||
for sigma in [2., 6., 20.] {
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: sigma,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
// A square much larger than the blur, so across its left edge at x = 100, on a row far from its other edges, the coverage is the one-dimensional profile
|
||
let Some(pixels) = render_square_with_effects(vec![blur], 1., 100., 400., size) else { return };
|
||
|
||
let mut worst = 0_f64;
|
||
for x in 40..160 {
|
||
let expected = normal_cdf((x as f64 + 0.5 - 100.) / sigma);
|
||
let actual = pixel(&pixels, size, x, 200)[3] as f64 / 255.;
|
||
worst = worst.max((expected - actual).abs());
|
||
}
|
||
assert!(worst < 0.03, "σ {sigma} strays from the normal distribution by {worst}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blurs_stretch_with_an_effect_space_scaled_unevenly() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Three times as wide as it is tall, the effect space renders in a texture of its own, so the blur of 4 spreads 12 pixels across and 4 down
|
||
let size = UVec2::new(512, 512);
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 4.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let Some(pixels) = render_square_with_effects_in(vec![blur], DAffine2::from_scale(glam::DVec2::new(3., 1.)), 1., 100., 400., size) else {
|
||
return;
|
||
};
|
||
|
||
let stray = |sigma: f64, coverage: &dyn Fn(u32) -> u8| (40..160).map(|at| (normal_cdf((at as f64 + 0.5 - 100.) / sigma) - coverage(at) as f64 / 255.).abs()).fold(0., f64::max);
|
||
let across = stray(12., &|x| pixel(&pixels, size, x, 250)[3]);
|
||
let down = stray(4., &|y| pixel(&pixels, size, 250, y)[3]);
|
||
assert!(across < 0.04 && down < 0.04, "the blur strays from σ 12 across by {across} and σ 4 down by {down}");
|
||
}
|
||
|
||
#[test]
|
||
fn shadows_turn_with_their_effect_space() {
|
||
use core_types::Color as GraphicColor;
|
||
|
||
// A shadow cast to the right of the content in an effect space turned a quarter clockwise falls below it in the document
|
||
let size = UVec2::new(256, 256);
|
||
let shadow = drop_shadow(GraphicColor::BLACK, glam::DVec2::new(30., 0.), 0., 0.);
|
||
let Some(pixels) = render_square_with_effects_in(vec![shadow], DAffine2::from_angle(std::f64::consts::FRAC_PI_2), 1., 50., 150., size) else {
|
||
return;
|
||
};
|
||
|
||
assert!(pixel(&pixels, size, 100, 165)[3] > 200, "the shadow should fall below the square");
|
||
assert_eq!(pixel(&pixels, size, 165, 100)[3], 0, "the shadow shouldn't fall to its right");
|
||
}
|
||
|
||
#[test]
|
||
fn shadows_and_glows_fall_where_they_should() {
|
||
use core_types::Color as GraphicColor;
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let black = GraphicColor::BLACK;
|
||
|
||
// A hard drop shadow offset down and right shows past the square's bottom right corner, beneath it
|
||
let shadow = drop_shadow(black, DVec2::new(10., 10.), 0., 0.);
|
||
let Some(pixels) = render_square_with_effects(vec![shadow.clone()], 1., 30., 80., size) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 50, 50), [255, 255, 255, 255], "the content covers its shadow");
|
||
assert_eq!(pixel(&pixels, size, 85, 85), [0, 0, 0, 255], "the shadow shows past the content");
|
||
assert_eq!(pixel(&pixels, size, 25, 25)[3], 0, "no shadow before the offset");
|
||
|
||
// With no fill, the content vanishes and its shadow stays knocked out where the content would be
|
||
let Some(pixels) = render_square_with_effects(vec![shadow], 0., 30., 80., size) else { return };
|
||
assert_eq!(pixel(&pixels, size, 50, 50)[3], 0, "the shadow is knocked out by the faded content");
|
||
assert_eq!(pixel(&pixels, size, 85, 85), [0, 0, 0, 255], "the shadow stays at full strength");
|
||
|
||
// An inner shadow darkens the content's top left edges from inside and stays within it
|
||
let inner_shadow = EffectOperation::InnerShadow {
|
||
color: black,
|
||
blend_mode: BlendMode::Normal,
|
||
angle: 135.,
|
||
distance: 6. * std::f64::consts::SQRT_2,
|
||
choke: 0.,
|
||
size: 0.,
|
||
contour: Default::default(),
|
||
};
|
||
let Some(pixels) = render_square_with_effects(vec![inner_shadow], 1., 30., 80., size) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 32, 50), [0, 0, 0, 255], "inside the left edge");
|
||
assert_eq!(pixel(&pixels, size, 50, 50), [255, 255, 255, 255], "deep inside");
|
||
assert_eq!(pixel(&pixels, size, 78, 50), [255, 255, 255, 255], "inside the right edge, away from the offset");
|
||
assert_eq!(pixel(&pixels, size, 25, 50)[3], 0, "outside");
|
||
|
||
// A glow grown by its whole size surrounds the content evenly
|
||
let glow = EffectOperation::OuterGlow {
|
||
color: GraphicColor::from_rgbaf32_unchecked(1., 0., 0., 1.).into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: Default::default(),
|
||
spread: 100.,
|
||
size: 5.,
|
||
range: 50.,
|
||
contour: Default::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
};
|
||
let Some(pixels) = render_square_with_effects(vec![glow], 1., 30., 80., size) else { return };
|
||
for (x, y) in [(27, 55), (82, 55), (55, 27), (55, 82)] {
|
||
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "glow at ({x}, {y})");
|
||
}
|
||
for (x, y) in [(23, 55), (87, 55)] {
|
||
assert_eq!(pixel(&pixels, size, x, y)[3], 0, "past the glow at ({x}, {y})");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn inner_glows_satins_outlines_and_bevels_fall_where_they_should() {
|
||
use core_types::Color as GraphicColor;
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||
use graphic_types::{BevelDirection, BevelStyle, BevelTechnique, EffectOperation, GlowSource, GlowTechnique};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let black = GraphicColor::BLACK;
|
||
let render_square = |effect| render_square_with_effects(vec![effect], 1., 30., 80., size);
|
||
let (white, clear) = ([255, 255, 255, 255], 0);
|
||
|
||
// A fully choked inner glow from the edges covers a band inside them, and one from the center covers the rest
|
||
let inner_glow = |source| EffectOperation::InnerGlow {
|
||
color: black.into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Softer,
|
||
source,
|
||
choke: 100.,
|
||
size: 3.,
|
||
range: 100.,
|
||
contour: Default::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
};
|
||
let Some(pixels) = render_square(inner_glow(GlowSource::Edge)) else { return };
|
||
assert_eq!(pixel(&pixels, size, 31, 55), [0, 0, 0, 255], "the edge glows");
|
||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the center doesn't");
|
||
assert_eq!(pixel(&pixels, size, 25, 55)[3], clear, "nothing outside");
|
||
let Some(pixels) = render_square(inner_glow(GlowSource::Center)) else { return };
|
||
assert_eq!(pixel(&pixels, size, 31, 55), white, "the edge doesn't glow");
|
||
assert_eq!(pixel(&pixels, size, 55, 55), [0, 0, 0, 255], "the center does");
|
||
|
||
// Satin shades where the two casts of the silhouette disagree, which for a horizontal offset is a band along each side
|
||
let satin = EffectOperation::Satin {
|
||
color: black,
|
||
blend_mode: BlendMode::Normal,
|
||
angle: 180.,
|
||
distance: 10.,
|
||
size: 0.,
|
||
invert: false,
|
||
contour: Default::default(),
|
||
};
|
||
let Some(pixels) = render_square(satin) else { return };
|
||
assert_eq!(pixel(&pixels, size, 35, 55), [0, 0, 0, 255], "the left band");
|
||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the middle, where both casts cover");
|
||
assert_eq!(pixel(&pixels, size, 75, 55), [0, 0, 0, 255], "the right band");
|
||
|
||
// An outline outside the edge rounds the corners it grows around, and one inside stays within the content
|
||
let outline = |align| EffectOperation::Outline {
|
||
paint: black.into(),
|
||
blend_mode: BlendMode::Normal,
|
||
weight: 5.,
|
||
align,
|
||
contour_gradient: false,
|
||
};
|
||
let Some(pixels) = render_square(outline(StrokeAlign::Outside)) else { return };
|
||
assert_eq!(pixel(&pixels, size, 26, 55), [0, 0, 0, 255], "within the weight of the edge");
|
||
assert_eq!(pixel(&pixels, size, 23, 55)[3], clear, "past the weight");
|
||
assert_eq!(pixel(&pixels, size, 27, 27), [0, 0, 0, 255], "near the corner");
|
||
assert_eq!(pixel(&pixels, size, 25, 25)[3], clear, "beyond the rounded corner, where a square would reach");
|
||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the content shows");
|
||
let Some(pixels) = render_square(outline(StrokeAlign::Inside)) else { return };
|
||
assert_eq!(pixel(&pixels, size, 32, 55), [0, 0, 0, 255], "inside the edge");
|
||
assert_eq!(pixel(&pixels, size, 40, 55), white, "past the weight inside");
|
||
assert_eq!(pixel(&pixels, size, 28, 55)[3], clear, "nothing outside");
|
||
|
||
// A contour gradient starts at the outline's outer edge and ends at its inner edge, around the corners too
|
||
let stops = [(0., GraphicColor::RED), (1., GraphicColor::BLUE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||
let contour_gradient = EffectOperation::Outline {
|
||
paint: Gradient::new(stops).into(),
|
||
blend_mode: BlendMode::Normal,
|
||
weight: 10.,
|
||
align: StrokeAlign::Center,
|
||
contour_gradient: true,
|
||
};
|
||
let at_start = |[red, _, blue, alpha]: [u8; 4]| red as i32 > blue as i32 + 100 && alpha == 255;
|
||
let at_end = |[red, _, blue, alpha]: [u8; 4]| blue as i32 > red as i32 + 100 && alpha == 255;
|
||
let Some(pixels) = render_square(contour_gradient) else { return };
|
||
for (x, y) in [(25, 55), (55, 84), (27, 27)] {
|
||
assert!(at_start(pixel(&pixels, size, x, y)), "the start at the outer edge ({x}, {y}): {:?}", pixel(&pixels, size, x, y));
|
||
}
|
||
for (x, y) in [(34, 55), (55, 75), (33, 33)] {
|
||
assert!(at_end(pixel(&pixels, size, x, y)), "the end at the inner edge ({x}, {y}): {:?}", pixel(&pixels, size, x, y));
|
||
}
|
||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the content within the outline");
|
||
|
||
// A gradient placed from 20 to 90 runs across the content and the outline's reach outside it
|
||
let across_outline = DAffine2::from_translation(glam::DVec2::splat(20.)) * DAffine2::from_scale(glam::DVec2::splat(70.));
|
||
let placed = EffectOperation::Outline {
|
||
paint: core_types::list::Item::new_from_element(Gradient::new(stops))
|
||
.with_attribute(core_types::ATTR_TRANSFORM, across_outline)
|
||
.into(),
|
||
blend_mode: BlendMode::Normal,
|
||
weight: 10.,
|
||
align: StrokeAlign::Outside,
|
||
contour_gradient: false,
|
||
};
|
||
let Some(pixels) = render_square(placed) else { return };
|
||
assert!(at_start(pixel(&pixels, size, 21, 55)), "the start at the outline's left edge: {:?}", pixel(&pixels, size, 21, 55));
|
||
assert!(at_end(pixel(&pixels, size, 88, 55)), "the end at its right edge: {:?}", pixel(&pixels, size, 88, 55));
|
||
|
||
// Lit from the upper left, a raised bevel's top slope catches the highlight and its bottom slope falls into shadow, which swap when it sinks
|
||
let bevel = |style, direction| EffectOperation::BevelAndEmboss {
|
||
style,
|
||
technique: BevelTechnique::Smooth,
|
||
depth: 100.,
|
||
direction,
|
||
size: 5.,
|
||
soften: 0.,
|
||
angle: 120.,
|
||
altitude: 30.,
|
||
highlight_color: GraphicColor::RED,
|
||
highlight_blend_mode: core_types::blending::BlendMode::Normal,
|
||
shadow_color: GraphicColor::BLUE,
|
||
shadow_blend_mode: core_types::blending::BlendMode::Normal,
|
||
gloss_contour: Default::default(),
|
||
gloss_antialiased: false,
|
||
slope_contour: Default::default(),
|
||
slope_antialiased: false,
|
||
slope_range: 100.,
|
||
texture: Default::default(),
|
||
texture_depth: 100.,
|
||
};
|
||
let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 128 && blue < 128 && alpha > 128;
|
||
let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 128 && green < 128 && alpha > 128;
|
||
let Some(pixels) = render_square(bevel(BevelStyle::InnerBevel, BevelDirection::Up)) else { return };
|
||
assert!(reddish(pixel(&pixels, size, 55, 32)), "the top slope is highlighted: {:?}", pixel(&pixels, size, 55, 32));
|
||
assert!(bluish(pixel(&pixels, size, 55, 77)), "the bottom slope is shaded: {:?}", pixel(&pixels, size, 55, 77));
|
||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the flat top inside the slopes is unlit");
|
||
assert_eq!(pixel(&pixels, size, 55, 20)[3], clear, "nothing outside");
|
||
let Some(pixels) = render_square(bevel(BevelStyle::InnerBevel, BevelDirection::Down)) else {
|
||
return;
|
||
};
|
||
assert!(bluish(pixel(&pixels, size, 55, 32)), "a sunken top slope is shaded: {:?}", pixel(&pixels, size, 55, 32));
|
||
assert!(reddish(pixel(&pixels, size, 55, 77)), "a sunken bottom slope is highlighted: {:?}", pixel(&pixels, size, 55, 77));
|
||
|
||
// A light nearly overhead lights the flat top most, which it still shades none, so even the slope facing the light gets less and is faintly shaded
|
||
let mut overhead = bevel(BevelStyle::InnerBevel, BevelDirection::Up);
|
||
if let EffectOperation::BevelAndEmboss { altitude, .. } = &mut overhead {
|
||
*altitude = 88.;
|
||
}
|
||
let Some(pixels) = render_square(overhead) else { return };
|
||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the flat top is unlit");
|
||
let [red, green, blue, alpha] = pixel(&pixels, size, 55, 32);
|
||
assert!(
|
||
alpha == 255 && blue == 255 && red == green && red < 255,
|
||
"the top slope is faintly shaded: {:?}",
|
||
pixel(&pixels, size, 55, 32)
|
||
);
|
||
|
||
// An outer bevel's slopes lie outside the content, beneath it
|
||
let Some(pixels) = render_square(bevel(BevelStyle::OuterBevel, BevelDirection::Up)) else { return };
|
||
assert!(reddish(pixel(&pixels, size, 55, 27)), "the top slope outside is highlighted: {:?}", pixel(&pixels, size, 55, 27));
|
||
assert!(bluish(pixel(&pixels, size, 55, 82)), "the bottom slope outside is shaded: {:?}", pixel(&pixels, size, 55, 82));
|
||
assert_eq!(pixel(&pixels, size, 55, 40), white, "the content inside is unlit");
|
||
|
||
// An inverted gloss contour maps the light a flat top gets at an altitude of 60° to far less than its brightness, shading it 85%
|
||
let mut glossy = bevel(BevelStyle::InnerBevel, BevelDirection::Up);
|
||
if let EffectOperation::BevelAndEmboss { gloss_contour, altitude, .. } = &mut glossy {
|
||
*gloss_contour = core_types::transfer_curve::TransferCurve::new(vec![glam::DVec2::Y, glam::DVec2::X]);
|
||
*altitude = 60.;
|
||
}
|
||
let Some(pixels) = render_square(glossy.clone()) else { return };
|
||
let [red, green, blue, _] = pixel(&pixels, size, 55, 55);
|
||
assert!(red < 60 && green < 60 && blue > 200, "the flat top is shaded blue: {:?}", pixel(&pixels, size, 55, 55));
|
||
|
||
// With no slopes at all, the gloss contour still shades the flat surface alike
|
||
let mut flat = glossy;
|
||
if let EffectOperation::BevelAndEmboss { size: bevel_size, .. } = &mut flat {
|
||
*bevel_size = 0.;
|
||
}
|
||
let Some(flat_pixels) = render_square(flat) else { return };
|
||
assert_eq!(pixel(&flat_pixels, size, 55, 55), pixel(&pixels, size, 55, 55), "the flat top is shaded the same without slopes");
|
||
}
|
||
|
||
#[test]
|
||
fn satins_reshape_each_cast_by_the_contour_before_comparing_them_on_the_cpu_gpu_and_svg() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::transfer_curve::TransferCurve;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::effects::EffectCapture;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
fn render_raster(item: Item<Raster<graphic_types::raster_types::CPU>>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(item));
|
||
render_in_view(size, DAffine2::IDENTITY, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
}
|
||
|
||
// Columns of white content at these alphas, unsoftened, so the casts a pixel to each side of the opaque columns 1, 3, 4, 5, and 7
|
||
// take the alphas 0.25 and 0.5, 0.5 and 1, 1 and 1, 1 and 0, and 0 and 0.25
|
||
let alphas = [0.25, 1., 0.5, 1., 1., 1., 0., 1., 0.25];
|
||
let opaque_columns = [1, 3, 4, 5, 7];
|
||
let (width, height) = (alphas.len() as u32, 3);
|
||
let data: Vec<GraphicColor> = (0..width * height).map(|index| GraphicColor::WHITE.with_alpha(alphas[(index % width) as usize])).collect();
|
||
let corner = UVec2::new(12, 6);
|
||
let size = UVec2::new(32, 16);
|
||
|
||
// An arch from nothing up to full at the middle and back, 3x - 4x³ over its first half, which takes 0.25 to 0.6875 and both 0 and 1 to 0
|
||
let arch = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.5, 1.), DVec2::X]);
|
||
|
||
for (invert, strengths) in [(false, [0.3125, 1., 0., 0., 0.6875]), (true, [0.6875, 0., 1., 1., 0.3125])] {
|
||
let satin = EffectOperation::Satin {
|
||
color: GraphicColor::BLACK,
|
||
blend_mode: BlendMode::Normal,
|
||
angle: 0.,
|
||
distance: 1.,
|
||
size: 0.,
|
||
invert,
|
||
contour: arch.clone(),
|
||
};
|
||
let placement = DAffine2::from_translation(corner.as_dvec2()) * DAffine2::from_scale(DVec2::new(width as f64, height as f64));
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width, height, data: data.clone() })).with_attribute(ATTR_TRANSFORM, placement);
|
||
stamp_effect(&mut item, Effect::new(&satin));
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return };
|
||
assert!(worst <= 2, "with invert {invert}, the CPU and GPU differ by up to {worst} levels");
|
||
|
||
// Black shading over opaque white leaves 1 minus its strength
|
||
let Some(gpu) = render_raster(item.clone(), size) else { return };
|
||
for (column, strength) in opaque_columns.into_iter().zip(strengths) {
|
||
let shaded = pixel(&gpu, size, corner.x + column, corner.y + 1);
|
||
let expected = ((1. - strength) * 255_f64).round() as u8;
|
||
assert!(
|
||
shaded[0].abs_diff(expected) <= 2 && shaded[3] == 255,
|
||
"with invert {invert}, the GPU shades column {column} to {shaded:?} rather than {expected}"
|
||
);
|
||
}
|
||
|
||
// SVG shades by the GPU's map of the strength, captured in black
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
List::new_from_item(item).render_svg(&mut svg, &export);
|
||
let Some(map) = svg.effect_maps.iter().find(|map| map.capture == EffectCapture { index: 0, plane: 0 }) else {
|
||
panic!("SVG takes no map of the satin's strength: {}", svg.svg_defs);
|
||
};
|
||
let Some(executor) = executor() else { return };
|
||
let layout = map.layout(DAffine2::IDENTITY, size.as_dvec2(), 4096).expect("the map is in view");
|
||
let pixels = {
|
||
let _turn = take_turn();
|
||
let texture = executor
|
||
.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout))
|
||
.expect("the map renders");
|
||
executor.read_texture_pixels(&texture).expect("the map reads back")
|
||
};
|
||
for (column, strength) in opaque_columns.into_iter().zip(strengths) {
|
||
let texel = layout.document_to_pixels.transform_point2(corner.as_dvec2() + DVec2::new(column as f64 + 0.5, 1.5)).floor().as_uvec2();
|
||
let alpha = pixels[((texel.y * layout.size.x + texel.x) * 4 + 3) as usize];
|
||
let expected = (strength * 255_f64).round() as u8;
|
||
assert!(alpha.abs_diff(expected) <= 2, "with invert {invert}, SVG's map holds {alpha} at column {column} rather than {expected}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn convolution_kernels_filter_endless_gradients_and_colors() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::Color;
|
||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||
use glam::DVec2;
|
||
use graphic_types::vector_types::gradient::Gradient;
|
||
use graphic_types::{Effect, EffectOperation, Effects, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::new(64, 16);
|
||
let render_graphic = |graphic: Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||
let difference = EffectOperation::convolution_kernel("-1 0 1", Some(1.), 128., false);
|
||
|
||
// A difference across a gradient from black to white over the view finds its slope, lifted from middle gray by the offset
|
||
let gradient = |effects: Vec<EffectOperation>| {
|
||
let mut item = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(64., 1.)));
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
Graphic::GradientList(List::new_from_item(item))
|
||
};
|
||
let Some(plain) = render_graphic(gradient(Vec::new())) else { return };
|
||
let Some(filtered) = render_graphic(gradient(vec![difference.clone()])) else { return };
|
||
let sloped = pixel(&filtered, size, 32, 8);
|
||
assert!(sloped[0] > 128 && sloped[0] < 160 && sloped[0] != pixel(&plain, size, 32, 8)[0], "{sloped:?}");
|
||
|
||
// A flat color changes by its weights' sum and the offset exactly as a rectangle of it covering the view does
|
||
let halved_and_raised = EffectOperation::convolution_kernel("1", Some(2.), 64., false);
|
||
let color = |effects: Vec<EffectOperation>| {
|
||
Graphic::ColorList(List::new_from_item(
|
||
Item::new_from_element(Color::WHITE).with_attribute(ATTR_EFFECTS, Effects::from_operations(effects)),
|
||
))
|
||
};
|
||
let Some(flat) = render_graphic(color(vec![halved_and_raised.clone()])) else { return };
|
||
let Some(rectangle) = render_square_with_effects(vec![halved_and_raised], 1., -50., 178., size) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&flat, size, 32, 8), pixel(&rectangle, size, 32, 8));
|
||
assert_eq!(pixel(&flat, size, 32, 8), [191, 191, 191, 255]);
|
||
}
|
||
|
||
#[test]
|
||
fn random_fields_match_the_cpu_zoomed_out_and_away_from_the_origin() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, NoiseDistribution, stamp_effect};
|
||
use raster_kernels::evaluate_raster_effects;
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
|
||
// A raster whose pixels each span two document pixels, far out on the negative side of the origin, rendered one texel per pixel, so each takes four samples
|
||
let (width, origin) = (32, glam::DVec2::new(-1000., -600.));
|
||
let placement = DAffine2::from_translation(origin) * DAffine2::from_scale(glam::DVec2::splat(2. * width as f64));
|
||
let view = DAffine2::from_scale(glam::DVec2::splat(0.5)) * DAffine2::from_translation(-origin);
|
||
let noise = |amount, distribution, monochromatic| EffectOperation::AddNoise {
|
||
amount,
|
||
distribution,
|
||
monochromatic,
|
||
seed: 11,
|
||
};
|
||
let operations = [
|
||
noise(40., NoiseDistribution::Uniform, false),
|
||
noise(20., NoiseDistribution::Gaussian, true),
|
||
EffectOperation::Dissolve { opacity: 60., seed: 4 },
|
||
];
|
||
|
||
for operation in operations {
|
||
let image = Image::new(width, width, GraphicColor::from_gamma_srgb_channels(0.4, 0.6, 0.5, 1.));
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, placement);
|
||
stamp_effect(&mut item, Effect::new(&operation));
|
||
|
||
let graphic = Graphic::RasterCPU(Box::new(item.clone()));
|
||
let gpu = {
|
||
let _turn = take_turn();
|
||
let texture = executor
|
||
.render_vello(UVec2::splat(width), view, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
.expect("the render succeeds");
|
||
executor.read_texture_pixels(&texture).expect("the render reads back")
|
||
};
|
||
|
||
// Compared premultiplied, so a nearly transparent pixel's color can't dominate
|
||
let evaluated = evaluate_raster_effects(item);
|
||
let mut worst = 0;
|
||
for (cpu, gpu) in evaluated.element().data.iter().zip(gpu.as_chunks::<4>().0) {
|
||
let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels();
|
||
let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.);
|
||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||
for channel in 0..4 {
|
||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||
worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32);
|
||
}
|
||
}
|
||
assert!(worst <= 2, "{operation:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn random_fields_stay_in_place_far_from_the_origin() {
|
||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, Effects, Graphic, NoiseDistribution};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Noise over an endless color whose cells lie past where 32-bit floats hold every integer, rendered there and a pixel further right
|
||
let size = UVec2::splat(16);
|
||
let noise = EffectOperation::AddNoise {
|
||
amount: 40.,
|
||
distribution: NoiseDistribution::Uniform,
|
||
monochromatic: false,
|
||
seed: 3,
|
||
};
|
||
let color = Item::new_from_element(core_types::Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.)).with_attribute(ATTR_EFFECTS, Effects::from_operations([noise]));
|
||
let graphic = Graphic::ColorList(List::new_from_item(color));
|
||
let render_at = |x: f64| {
|
||
render(size, |scene| {
|
||
graphic.render_to_vello(scene, DAffine2::from_translation(-DVec2::new(x, 16_777_219.)), &RenderParams::default())
|
||
})
|
||
};
|
||
let Some(placed) = render_at(33_554_433.) else { return };
|
||
let Some(moved) = render_at(33_554_434.) else { return };
|
||
|
||
// Each pixel of the second render shows the cell the next pixel of the first one does
|
||
for y in 0..size.y {
|
||
for x in 0..size.x - 1 {
|
||
assert_eq!(pixel(&moved, size, x, y), pixel(&placed, size, x + 1, y), "at ({x}, {y})");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn random_fields_change_endless_colors() {
|
||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||
use graphic_types::{EffectOperation, Effects, Graphic};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::splat(16);
|
||
let effects = Effects::from_operations([EffectOperation::Dissolve { opacity: 50., seed: 0 }]);
|
||
let color = Item::new_from_element(core_types::Color::from_gamma_srgb_channels(0.8, 0.2, 0.4, 1.)).with_attribute(ATTR_EFFECTS, effects);
|
||
let graphic = Graphic::ColorList(List::new_from_item(color));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
let shown = pixels.iter().filter(|pixel| pixel[3] == 255).count();
|
||
assert!(shown > 64 && shown < 192 && pixels.iter().all(|pixel| pixel[3] == 0 || pixel[3] == 255), "{shown} of 256 shown");
|
||
}
|
||
|
||
#[test]
|
||
fn filters_carry_out_over_endless_colors() {
|
||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||
use graphic_types::{EffectOperation, Effects, Graphic};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::splat(16);
|
||
let effects = Effects::from_operations([
|
||
EffectOperation::Emboss {
|
||
angle: 135.,
|
||
height: 3.,
|
||
amount: 100.,
|
||
},
|
||
EffectOperation::FindEdges,
|
||
]);
|
||
let color = Item::new_from_element(core_types::Color::from_gamma_srgb_channels(0.8, 0.2, 0.4, 1.)).with_attribute(ATTR_EFFECTS, effects);
|
||
let graphic = Graphic::ColorList(List::new_from_item(color));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
// Embossing a flat color grays it, and finding the edges of flat gray whitens it, as for a rectangle of it covering the view
|
||
assert_eq!(pixel(&pixels, size, 8, 8), [255, 255, 255, 255]);
|
||
}
|
||
|
||
#[test]
|
||
fn convolution_kernels_read_colors_continuing_past_the_edges() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
|
||
// A difference across the white square finds no edge at its silhouette, since the colors beyond it continue, so the offset leaves middle gray within it
|
||
let difference = EffectOperation::convolution_kernel("-1 0 1", Some(1.), 128., false);
|
||
let Some(pixels) = render_square_with_effects(vec![difference], 1., 30., 80., size) else { return };
|
||
for x in [30, 55, 79] {
|
||
assert_eq!(pixel(&pixels, size, x, 55), [128, 128, 128, 255], "at x = {x}");
|
||
}
|
||
assert_eq!(pixel(&pixels, size, 28, 55)[3], 0, "the coverage stays as it is");
|
||
|
||
// An empty kernel, like an identity kernel, leaves the content as it is beside other effects
|
||
let empty = EffectOperation::convolution_kernel("", Some(1.), 0., false);
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 1.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let Some(pixels) = render_square_with_effects(vec![empty, blur], 1., 30., 80., size) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 55, 55), [255; 4]);
|
||
}
|
||
|
||
#[test]
|
||
fn stylize_filters_show_the_silhouette_and_move_its_coverage() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let render_square = |effect| render_square_with_effects(vec![effect], 1., 30., 80., size);
|
||
|
||
// Embossed with the light from the left, the flat inside is middle gray, and the edges show against the gray matted beyond them, dark on the left and light on the right
|
||
let emboss = EffectOperation::Emboss {
|
||
angle: 180.,
|
||
height: 2.,
|
||
amount: 100.,
|
||
};
|
||
let Some(pixels) = render_square(emboss) else { return };
|
||
let inside = pixel(&pixels, size, 55, 55);
|
||
assert!(inside[..3].iter().all(|channel| (127..=128).contains(channel)) && inside[3] == 255, "the flat inside is {inside:?}");
|
||
assert!(pixel(&pixels, size, 30, 55)[0] < 128 && pixel(&pixels, size, 79, 55)[0] > 128, "the edges in relief");
|
||
assert_eq!(pixel(&pixels, size, 28, 55)[3], 0, "nothing outside");
|
||
|
||
// The neighborhood maximum of the white square shrinks it, and the minimum grows it
|
||
let Some(pixels) = render_square(minimum_maximum(3., MinimumMaximumMode::Maximum)) else { return };
|
||
assert_eq!(pixel(&pixels, size, 32, 55)[3], 0, "within the radius of the edge");
|
||
assert_eq!(pixel(&pixels, size, 33, 55), [255; 4]);
|
||
let Some(pixels) = render_square(minimum_maximum(3., MinimumMaximumMode::Minimum)) else { return };
|
||
assert_eq!(pixel(&pixels, size, 27, 55), [255; 4], "within the radius past the edge");
|
||
assert_eq!(pixel(&pixels, size, 26, 55)[3], 0);
|
||
}
|
||
|
||
#[test]
|
||
fn paint_overlays_draw_paints_by_their_own_placement() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::blending::BlendMode;
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||
use graphic_types::{EffectOperation, Graphic};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let overlay = |paint: Graphic| EffectOperation::PaintOverlay {
|
||
paint,
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
};
|
||
let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 64 && blue < 64 && alpha == 255;
|
||
let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 64 && green < 64 && alpha == 255;
|
||
let across_square = DAffine2::from_translation(glam::DVec2::splat(30.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
|
||
// A gradient from red to blue placed across the square runs from its left edge to its right edge
|
||
let stops = [(0., GraphicColor::RED), (1., GraphicColor::BLUE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||
let gradient = Item::new_from_element(Gradient::new(stops)).with_attribute(core_types::ATTR_TRANSFORM, across_square);
|
||
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(gradient))], 1., 30., 80., size) else {
|
||
return;
|
||
};
|
||
assert!(reddish(pixel(&pixels, size, 31, 55)), "the start at the left edge: {:?}", pixel(&pixels, size, 31, 55));
|
||
assert!(bluish(pixel(&pixels, size, 78, 55)), "the end at the right edge: {:?}", pixel(&pixels, size, 78, 55));
|
||
assert_eq!(pixel(&pixels, size, 25, 55)[3], 0, "nothing outside the content");
|
||
|
||
// An image of a red pixel beside a blue one placed across the square covers it, each pixel half of it
|
||
let image = Image {
|
||
width: 2,
|
||
height: 1,
|
||
data: vec![GraphicColor::RED, GraphicColor::BLUE],
|
||
};
|
||
let image = Item::new_from_element(Raster::new_cpu(image)).with_attribute(core_types::ATTR_TRANSFORM, across_square);
|
||
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(image))], 1., 30., 80., size) else {
|
||
return;
|
||
};
|
||
assert!(reddish(pixel(&pixels, size, 35, 40)), "the left half: {:?}", pixel(&pixels, size, 35, 40));
|
||
assert!(bluish(pixel(&pixels, size, 75, 70)), "the right half: {:?}", pixel(&pixels, size, 75, 70));
|
||
}
|
||
|
||
#[test]
|
||
fn masks_show_the_content_where_their_graphic_is_light_or_opaque() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{EffectOperation, Graphic, MaskMode};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let white = [255, 255, 255, 255];
|
||
|
||
// An image placed across the square with a pixel for each of its columns, so its left half covers the square's left half without interpolation
|
||
let across_square = DAffine2::from_translation(DVec2::splat(30.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
let halves = |left: GraphicColor, right: GraphicColor| {
|
||
let data = (0..50).map(|column| if column < 25 { left } else { right }).collect();
|
||
Graphic::from(Item::new_from_element(Raster::new_cpu(Image { width: 50, height: 1, data })).with_attribute(core_types::ATTR_TRANSFORM, across_square))
|
||
};
|
||
let mask = |mask, mode, density, feather, invert| EffectOperation::Mask { mask, mode, density, feather, invert };
|
||
let render = |effects| render_square_with_effects(effects, 1., 30., 80., size);
|
||
|
||
let Some(pixels) = render(vec![mask(halves(GraphicColor::BLACK, GraphicColor::WHITE), MaskMode::Luminance, 100., 0., false)]) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 40, 55)[3], 0, "black hides the content");
|
||
assert_eq!(pixel(&pixels, size, 70, 55), white, "white shows it");
|
||
|
||
let Some(pixels) = render(vec![mask(halves(GraphicColor::BLACK, GraphicColor::WHITE), MaskMode::Luminance, 100., 0., true)]) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 40, 55), white, "inverted, black shows the content");
|
||
assert_eq!(pixel(&pixels, size, 70, 55)[3], 0, "inverted, white hides it");
|
||
|
||
let Some(pixels) = render(vec![mask(halves(GraphicColor::BLACK, GraphicColor::WHITE), MaskMode::Luminance, 50., 0., false)]) else {
|
||
return;
|
||
};
|
||
assert!(pixel(&pixels, size, 40, 55)[3].abs_diff(128) <= 1, "half the density half hides it: {:?}", pixel(&pixels, size, 40, 55));
|
||
|
||
// By alpha, transparent hides the content where an opaque black shows it
|
||
let Some(pixels) = render(vec![mask(halves(GraphicColor::TRANSPARENT, GraphicColor::BLACK), MaskMode::Alpha, 100., 0., false)]) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 40, 55)[3], 0, "transparent hides it");
|
||
assert_eq!(pixel(&pixels, size, 70, 55), white, "opaque shows it");
|
||
|
||
// Each luminance mode shows the content by its own weights of pure red, green, and blue
|
||
for (mode, levels) in [(MaskMode::Luminance, [77, 150, 28]), (MaskMode::LuminanceSvg, [54, 182, 18])] {
|
||
for (primary, level) in [GraphicColor::RED, GraphicColor::GREEN, GraphicColor::BLUE].into_iter().zip(levels) {
|
||
let Some(pixels) = render(vec![mask(halves(primary, primary), mode, 100., 0., false)]) else {
|
||
return;
|
||
};
|
||
let shown = pixel(&pixels, size, 55, 55)[3];
|
||
assert!(shown.abs_diff(level) <= 1, "{mode:?} shows {shown} of the content by {primary:?} rather than {level}");
|
||
}
|
||
}
|
||
|
||
// A feather softens the mask's edge at the middle of the square by a Gaussian
|
||
let Some(pixels) = render(vec![mask(halves(GraphicColor::BLACK, GraphicColor::WHITE), MaskMode::Luminance, 100., 4., false)]) else {
|
||
return;
|
||
};
|
||
for x in [48, 52, 54, 55, 58, 62] {
|
||
let expected = normal_cdf((x as f64 + 0.5 - 55.) / 4.);
|
||
let actual = pixel(&pixels, size, x, 55)[3] as f64 / 255.;
|
||
assert!((expected - actual).abs() < 0.03, "at {x} the feathered mask shows {actual} rather than {expected}");
|
||
}
|
||
|
||
// A mask before a shadow shapes the shadow, and one after it hides the shadow too
|
||
let shadow = drop_shadow(GraphicColor::BLACK, DVec2::new(-10., 0.), 0., 0.);
|
||
let left_hidden = || mask(halves(GraphicColor::BLACK, GraphicColor::WHITE), MaskMode::Luminance, 100., 0., false);
|
||
let Some(pixels) = render(vec![left_hidden(), shadow.clone()]) else { return };
|
||
assert_eq!(pixel(&pixels, size, 50, 55), [0, 0, 0, 255], "the shown half casts its shadow over the hidden half");
|
||
assert_eq!(pixel(&pixels, size, 40, 55)[3], 0, "the hidden half casts none");
|
||
assert_eq!(pixel(&pixels, size, 60, 55), white, "the shown half covers its shadow");
|
||
let Some(pixels) = render(vec![shadow, left_hidden()]) else { return };
|
||
assert_eq!(pixel(&pixels, size, 50, 55)[3], 0, "the mask hides the shadow with the content");
|
||
assert_eq!(pixel(&pixels, size, 25, 55)[3], 0, "and past the content, which the mask graphic doesn't cover");
|
||
assert_eq!(pixel(&pixels, size, 60, 55), white, "the shown half stays");
|
||
}
|
||
|
||
#[test]
|
||
fn a_feathered_mask_finds_its_edge_just_past_the_view() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::List;
|
||
use graphic_types::{Appearance, Coverage, EffectOperation, Graphic, MaskMode, Vector};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
// Content past the view on every side, masked by a rectangle whose right edge lies 2 pixels past the view's
|
||
let size = UVec2::new(128, 128);
|
||
let mut shown = Vector::item_from_bezpath(&Rect::new(-50., -50., 130., 178.).to_path(0.1));
|
||
shown.set_attribute(
|
||
core_types::list::ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
|
||
);
|
||
let mask = EffectOperation::Mask {
|
||
mask: Graphic::Vector(Box::new(shown)),
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 4.,
|
||
invert: false,
|
||
};
|
||
let Some(pixels) = render_square_with_effects(vec![mask], 1., -50., 178., size) else { return };
|
||
|
||
// The last column of the view is feathered by that edge, rather than by its own pixels stretched past the view
|
||
let expected = normal_cdf((130. - 127.5) / 4.);
|
||
let actual = pixel(&pixels, size, 127, 64)[3] as f64 / 255.;
|
||
assert!((expected - actual).abs() < 0.04, "the view's edge shows {actual} rather than {expected}");
|
||
assert_eq!(pixel(&pixels, size, 64, 64)[3], 255, "the mask shows the content well within its edge");
|
||
}
|
||
|
||
#[test]
|
||
fn a_feather_on_a_clipping_base_fades_what_clips_to_it() {
|
||
use core_types::list::List;
|
||
use core_types::{ATTR_CLIPPING_MASK, Color as GraphicColor};
|
||
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = |color: GraphicColor| {
|
||
let mut item = Vector::item_from_bezpath(&Rect::new(30., 30., 80., 80.).to_path(0.1));
|
||
item.set_attribute(
|
||
core_types::list::ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))),
|
||
);
|
||
item
|
||
};
|
||
|
||
// A white base feathered by 10, with a red square of the same size clipped to it
|
||
let mut base = square(GraphicColor::WHITE);
|
||
stamp_effect(&mut base, Effect::new(&EffectOperation::Feather { distance: 10. }));
|
||
let clipped = square(GraphicColor::RED).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
let graphic = Graphic::VectorList([base, clipped].into_iter().collect());
|
||
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 55, 55), [255, 0, 0, 255], "the clipped square shows fully well within the feather");
|
||
assert!(
|
||
pixel(&pixels, size, 31, 55)[3] < 128,
|
||
"the clipped square fades with the base at its edge: {:?}",
|
||
pixel(&pixels, size, 31, 55)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_mask_on_a_clipping_base_shapes_what_clips_to_it() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_CLIPPING_MASK, Color as GraphicColor};
|
||
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Graphic, MaskMode, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = |color: GraphicColor, rect: Rect| {
|
||
let mut item = Vector::item_from_bezpath(&rect.to_path(0.1));
|
||
item.set_attribute(
|
||
core_types::list::ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))),
|
||
);
|
||
item
|
||
};
|
||
let content = Rect::new(30., 30., 80., 80.);
|
||
|
||
// A white base masked to its left half, with a red square of the same size clipped to it
|
||
let mut base = square(GraphicColor::WHITE, content);
|
||
let left_half = Graphic::Vector(Box::new(square(GraphicColor::WHITE, Rect::new(30., 30., 55., 80.))));
|
||
let mask = EffectOperation::Mask {
|
||
mask: left_half,
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
stamp_effect(&mut base, Effect::new(&mask));
|
||
let clipped = square(GraphicColor::RED, content).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
|
||
// Clipped within a list of vectors, and within a list of graphics, where the base's effects lie on its row
|
||
let vectors = Graphic::VectorList([base.clone(), clipped.clone()].into_iter().collect());
|
||
let base_effects: graphic_types::Effects = base.attribute_cloned_or_default(core_types::list::ATTR_EFFECTS);
|
||
let mut bare_base = base;
|
||
bare_base.remove_attribute::<graphic_types::Effects>(core_types::list::ATTR_EFFECTS);
|
||
let mut graphics: List<Graphic> = [Item::new_from_element(Graphic::Vector(Box::new(bare_base))), Item::new_from_element(Graphic::Vector(Box::new(clipped)))]
|
||
.into_iter()
|
||
.collect();
|
||
graphics.set_attribute(core_types::list::ATTR_EFFECTS, 0, base_effects);
|
||
graphics.set_attribute(ATTR_CLIPPING_MASK, 1, true);
|
||
|
||
for (name, graphic) in [("vectors", vectors), ("graphics", Graphic::GraphicList(graphics))] {
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 40, 55), [255, 0, 0, 255], "{name}: the clipped square shows over the base's shown half");
|
||
assert_eq!(pixel(&pixels, size, 70, 55)[3], 0, "{name}: the base's mask hides the clipped square with the base");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_clipping_base_clips_by_its_blur_but_not_by_its_shadow() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, Color as GraphicColor};
|
||
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = |color: GraphicColor, rect: Rect| {
|
||
let mut item = Vector::item_from_bezpath(&rect.to_path(0.1));
|
||
item.set_attribute(
|
||
core_types::list::ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))),
|
||
);
|
||
item
|
||
};
|
||
|
||
// A white base its fill hides, with a red square twice its size clipped to it, as siblings in a list of vectors and as layers of a stack
|
||
let render_clipped = |effect: &EffectOperation, as_layers: bool| {
|
||
let mut base = square(GraphicColor::WHITE, Rect::new(40., 40., 80., 80.)).with_attribute(ATTR_OPACITY_FILL, 0.);
|
||
stamp_effect(&mut base, Effect::new(effect));
|
||
let clipped = square(GraphicColor::RED, Rect::new(20., 20., 100., 100.)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
|
||
let graphic = match as_layers {
|
||
true => {
|
||
let layer = |item: Item<Vector>| Item::new_from_element(Graphic::VectorList(List::new_from_item(item)));
|
||
Graphic::GraphicList([layer(base), layer(clipped)].into_iter().collect())
|
||
}
|
||
false => Graphic::VectorList([base, clipped].into_iter().collect()),
|
||
};
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask: Graphic::default(),
|
||
radius: 4.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let shadow = drop_shadow(GraphicColor::BLACK, glam::DVec2::new(10., 10.), 0., 0.);
|
||
for (name, as_layers) in [("vectors", false), ("layers", true)] {
|
||
let Some(pixels) = render_clipped(&blur, as_layers) else { return };
|
||
assert_eq!(
|
||
pixel(&pixels, size, 60, 60),
|
||
[255, 0, 0, 255],
|
||
"{name}: the clipped square shows fully within the base, unfaded by its fill"
|
||
);
|
||
let past_edge = pixel(&pixels, size, 82, 60);
|
||
assert!(past_edge[0] > 200 && past_edge[3] > 0, "{name}: and past its edge, where its blur reaches: {past_edge:?}");
|
||
|
||
let Some(pixels) = render_clipped(&shadow, as_layers) else { return };
|
||
assert_eq!(pixel(&pixels, size, 60, 60), [255, 0, 0, 255], "{name}: the clipped square shows fully within the base");
|
||
assert_eq!(pixel(&pixels, size, 85, 85), [0, 0, 0, 255], "{name}: but not over the shadow the base casts");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn feathers_fade_the_content_to_nothing_at_its_edges() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let distance = 12.;
|
||
let Some(pixels) = render_square_with_effects(vec![EffectOperation::Feather { distance }], 1., 30., 80., size) else {
|
||
return;
|
||
};
|
||
|
||
// Across the left edge, on the middle row, the strength rises along the normal curve from the edge to the distance, halfway at half the distance
|
||
for x in 30..48 {
|
||
let depth = x as f64 + 0.5 - 30.;
|
||
let expected = normal_cdf((depth - distance / 2.) / (distance / 6.));
|
||
let actual = pixel(&pixels, size, x, 55)[3] as f64 / 255.;
|
||
assert!((expected - actual).abs() < 0.03, "at {depth} in from the edge the feather keeps {actual} rather than {expected}");
|
||
}
|
||
assert_eq!(pixel(&pixels, size, 29, 55)[3], 0, "nothing outside");
|
||
assert_eq!(pixel(&pixels, size, 55, 55), [255, 255, 255, 255], "the middle is untouched");
|
||
assert!(pixel(&pixels, size, 31, 31)[3] <= 1, "the corner fades to nothing");
|
||
}
|
||
|
||
#[test]
|
||
fn masked_radius_blur_image_maps_blur_by_their_own_adjustments_and_opacity_on_the_cpu_and_gpu() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Image maps placed in the content's own space over it grown by 30 on each side: plain white, black inverted to white, and white at half opacity
|
||
let past_content = DAffine2::from_translation(DVec2::splat(-0.6)) * DAffine2::from_scale(DVec2::splat(2.2));
|
||
let image = |color| Item::new_from_element(Raster::new_cpu(Image::new(4, 4, color))).with_attribute(core_types::ATTR_TRANSFORM, past_content);
|
||
let mut inverted = image(GraphicColor::BLACK);
|
||
stamp_effect(&mut inverted, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
|
||
let faded = image(GraphicColor::WHITE).with_attribute(core_types::ATTR_OPACITY, 0.5_f64);
|
||
|
||
// Each blurs a shadow cast 20 right of the content, so its far edge 20 past the content is soft where the map reaches it
|
||
let shadow = drop_shadow(GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 1.), DVec2::new(20., 0.), 0., 0.);
|
||
let size = UVec2::new(160, 160);
|
||
for (name, map) in [("plain", image(GraphicColor::WHITE)), ("inverted", inverted), ("faded", faded)] {
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask: Graphic::from(map),
|
||
radius: 3.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let item = patterned_raster(55., &[shadow.clone(), blur], 1.);
|
||
let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return };
|
||
assert!(worst <= 3, "the {name} map differs from the GPU by up to {worst} levels");
|
||
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let soft = (118..132).filter(|&x| (10..245).contains(&pixel(&pixels, size, x, 80)[3])).count();
|
||
assert!(soft >= 3, "only {soft} pixels soften the shadow's far edge with the {name} map");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn masked_radius_blurs_blur_as_much_as_their_map_is_bright() {
|
||
use core_types::Color as GraphicColor;
|
||
use graphic_types::{EffectOperation, Graphic};
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let radius = 8.;
|
||
let masked_by = |radius_mask: Graphic, box_blur: bool| EffectOperation::Blur {
|
||
radius_mask,
|
||
radius,
|
||
box_blur,
|
||
gamma: false,
|
||
};
|
||
let masked_by_color = |radius_mask: GraphicColor| masked_by(Graphic::from(radius_mask), false);
|
||
let render = |effect| render_square_with_effects(vec![effect], 1., 50., 110., size);
|
||
let column = |pixels: &[[u8; 4]], x: u32| pixel(pixels, size, x, 80)[3] as f64 / 255.;
|
||
|
||
// A white map blurs fully, the same as a blur of the radius
|
||
let Some(white) = render(masked_by_color(GraphicColor::WHITE)) else { return };
|
||
for x in 30..70 {
|
||
let expected = normal_cdf((x as f64 + 0.5 - 50.) / radius);
|
||
assert!((column(&white, x) - expected).abs() < 0.03, "at {x} a white map blurs to {} rather than {expected}", column(&white, x));
|
||
}
|
||
|
||
// Likewise as a box blur, the same as an even box blur of the radius
|
||
let Some(white_box) = render(masked_by(Graphic::from(GraphicColor::WHITE), true)) else { return };
|
||
let Some(even_box) = render(masked_by(Graphic::default(), true)) else { return };
|
||
for x in 30..70 {
|
||
assert!(
|
||
(column(&white_box, x) - column(&even_box, x)).abs() <= 1. / 255.,
|
||
"at {x} a white map's box blur differs from an even one"
|
||
);
|
||
}
|
||
|
||
// A white image placed over the whole render blurs like a blur of the radius too
|
||
let white_image = core_types::list::Item::new_from_element(graphic_types::raster_types::Raster::new_cpu(graphic_types::raster_types::Image::new(1, 1, GraphicColor::WHITE)));
|
||
let white_image = Graphic::from(white_image.with_attribute(core_types::ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2())));
|
||
let Some(pixels) = render(masked_by(white_image, false)) else { return };
|
||
for x in 30..70 {
|
||
let expected = normal_cdf((x as f64 + 0.5 - 50.) / radius);
|
||
assert!(
|
||
(column(&pixels, x) - expected).abs() < 0.03,
|
||
"at {x} a white image map blurs to {} rather than {expected}",
|
||
column(&pixels, x)
|
||
);
|
||
}
|
||
|
||
// A black map leaves the content sharp
|
||
let Some(black) = render(masked_by_color(GraphicColor::BLACK)) else { return };
|
||
assert_eq!(column(&black, 49), 0.);
|
||
assert_eq!(column(&black, 50), 1.);
|
||
|
||
// A middle gray blurs about as much as a blur of the fraction of the radius its luminance gives, which the interpolation between levels approximates
|
||
let gray = GraphicColor::from_gamma_srgb_channels(0.4, 0.4, 0.4, 1.);
|
||
let Some(pixels) = render(masked_by_color(gray)) else { return };
|
||
for x in 40..60 {
|
||
let expected = normal_cdf((x as f64 + 0.5 - 50.) / (0.4 * radius));
|
||
assert!(
|
||
(column(&pixels, x) - expected).abs() < 0.06,
|
||
"at {x} a gray map blurs to {} rather than about {expected}",
|
||
column(&pixels, x)
|
||
);
|
||
}
|
||
|
||
// As a box blur, it's exactly the box of the fraction of the radius its luminance code gives
|
||
let Some(gray_box) = render(masked_by(Graphic::from(gray), true)) else { return };
|
||
let Some(fraction_box) = render(EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: radius * 102. / 255.,
|
||
box_blur: true,
|
||
gamma: false,
|
||
}) else {
|
||
return;
|
||
};
|
||
for x in 40..60 {
|
||
assert!(
|
||
(column(&gray_box, x) - column(&fraction_box, x)).abs() <= 1. / 255.,
|
||
"at {x} a gray map's box blur differs from the box of its radius"
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blurs_without_a_radius_mask_drawing_something_blur_evenly() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::{Item, List};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic};
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let blur = |radius_mask: Graphic| EffectOperation::Blur {
|
||
radius_mask,
|
||
radius: 8.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let render = |radius_mask| render_square_with_effects(vec![blur(radius_mask)], 1., 50., 110., size);
|
||
|
||
// A radius mask left out of the row, and those the row carries that draw nothing, render the very same even blur
|
||
let Some(plain) = render(Graphic::default()) else { return };
|
||
let no_pixels = Graphic::from(Item::new_from_element(Raster::new_cpu(Image::new(0, 0, GraphicColor::WHITE))));
|
||
let nested_nothing = Graphic::Graphic(Box::new(Item::new_from_element(Graphic::default())));
|
||
for radius_mask in [Graphic::GraphicList(List::new()), no_pixels, nested_nothing] {
|
||
assert!(Effect::new(&blur(radius_mask.clone())).0.attribute::<Graphic>("radius_mask").is_some());
|
||
let Some(pixels) = render(radius_mask) else { return };
|
||
assert!(pixels == plain, "a radius mask drawing nothing changes the blur");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn zoomed_in_masked_radius_blurs_blur_by_the_fraction_of_their_radius_without_ghosting() {
|
||
use core_types::Color as GraphicColor;
|
||
use graphic_types::{EffectOperation, Graphic};
|
||
|
||
// Zoomed in to 400%, a quarter of the radius of 2 spans 2 pixels, half a document pixel, which a level of its own blurs to rather than a sharp copy mixed with a wider blur
|
||
let (size, radius, zoom) = (UVec2::new(160, 160), 2., 4.);
|
||
let gray = GraphicColor::from_gamma_srgb_channels(0.25, 0.25, 0.25, 1.);
|
||
let effect = EffectOperation::Blur {
|
||
radius_mask: Graphic::from(gray),
|
||
radius,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let Some(pixels) = render_square_with_effects_in(vec![effect], DAffine2::from_scale(glam::DVec2::splat(zoom)), 1., 50., 110., size) else {
|
||
return;
|
||
};
|
||
|
||
let sigma = 64. / 255. * radius * zoom;
|
||
for x in 40..60 {
|
||
let alpha = pixel(&pixels, size, x, 80)[3] as f64 / 255.;
|
||
let expected = normal_cdf((x as f64 + 0.5 - 50.) / sigma);
|
||
assert!((alpha - expected).abs() < 0.03, "at {x} the zoomed blur reaches {alpha} rather than {expected}");
|
||
}
|
||
}
|
||
|
||
/// What the GPU's effect passes leave of `texels` (premultiplied gamma-encoded half floats, `width` to a row) carrying out `effects` with lengths one to a pixel,
|
||
/// reading the effects' drawn paints from `paints` of the same size, unrounded.
|
||
fn gpu_effect_texels(effects: &graphic_types::Effects, texels: &[[half::f16; 4]], width: usize, paints: &[&[[half::f16; 4]]]) -> Option<Vec<[f32; 4]>> {
|
||
use wgpu::util::DeviceExt;
|
||
|
||
let executor = executor()?;
|
||
let effect_passes = &executor.inner.vello_renderer.effect_passes;
|
||
if !effect_passes.renders_working_formats {
|
||
return None;
|
||
}
|
||
let device = &executor.context().device;
|
||
let _turn = take_turn();
|
||
|
||
let descriptor = wgpu::TextureDescriptor {
|
||
label: Some("effect_test_texels"),
|
||
size: wgpu::Extent3d {
|
||
width: width as u32,
|
||
height: (texels.len() / width) as u32,
|
||
depth_or_array_layers: 1,
|
||
},
|
||
mip_level_count: 1,
|
||
sample_count: 1,
|
||
dimension: wgpu::TextureDimension::D2,
|
||
format: wgpu::TextureFormat::Rgba16Float,
|
||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||
view_formats: &[],
|
||
};
|
||
|
||
let queue = executor.context().queue.lock();
|
||
let upload = |texels: &[[half::f16; 4]]| device.create_texture_with_data(&queue, &descriptor, wgpu::util::TextureDataOrder::LayerMajor, bytemuck::cast_slice(texels));
|
||
let content = upload(texels);
|
||
let paints: Vec<wgpu::Texture> = paints.iter().map(|paint| upload(paint)).collect();
|
||
|
||
let mut textures = crate::vello_effects::EffectTextures::default();
|
||
let layers = graphic_types::effect_layers::EffectLayers::plan(effects, BlendMode::Normal, 1., false);
|
||
let results = effect_passes.apply(executor, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None);
|
||
let (result, _) = results.into_iter().next()?;
|
||
drop(queue);
|
||
|
||
let bytes = executor.read_texture_pixels(&result).ok()?;
|
||
let half_floats: Vec<f32> = bytes.as_chunks::<2>().0.iter().map(|&bytes| half::f16::from_le_bytes(bytes).to_f32()).collect();
|
||
Some(half_floats.as_chunks::<4>().0.to_vec())
|
||
}
|
||
|
||
/// A masked box blur of `radius` pixels, in gamma if `gamma`, with its map given to the passes as a paint texture.
|
||
fn masked_box_blur(radius: f64, gamma: bool) -> graphic_types::Effects {
|
||
graphic_types::Effects::from_operations([graphic_types::EffectOperation::Blur {
|
||
radius_mask: graphic_types::Graphic::from(core_types::Color::WHITE),
|
||
radius,
|
||
box_blur: true,
|
||
gamma,
|
||
}])
|
||
}
|
||
|
||
/// The box of `half_width` along each axis around a pixel of `width` by `height` premultiplied channels, summed pixel by pixel with the edge pixels held past the edges.
|
||
fn summed_box(channels: &[[f32; 4]], width: usize, height: usize, x: usize, y: usize, half_width: f64) -> [f64; 4] {
|
||
use raster_kernels::effect_kernels::box_weight;
|
||
|
||
let reach = half_width.ceil() as i64;
|
||
let (mut sum, mut total) = ([0.; 4], 0.);
|
||
for offset_y in -reach..=reach {
|
||
for offset_x in -reach..=reach {
|
||
let weight = box_weight(half_width, offset_x.unsigned_abs() as usize) * box_weight(half_width, offset_y.unsigned_abs() as usize);
|
||
let source_x = (x as i64 + offset_x).clamp(0, width as i64 - 1) as usize;
|
||
let source_y = (y as i64 + offset_y).clamp(0, height as i64 - 1) as usize;
|
||
let pixel = channels[source_y * width + source_x];
|
||
|
||
sum = std::array::from_fn(|channel| sum[channel] + weight * pixel[channel] as f64);
|
||
total += weight;
|
||
}
|
||
}
|
||
sum.map(|channel| channel / total)
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_masked_box_blurs_match_the_cpu() {
|
||
use graphic_types::masks::{MaskMode, mask_coverage};
|
||
use half::f16;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// Colorful content reaching the edges, every fifth pixel transparent and others translucent, which the CPU blurs as the GPU reads it
|
||
let (width, height) = (96, 72);
|
||
let texels: Vec<[f16; 4]> = (0..width * height)
|
||
.map(|index| {
|
||
let (x, y) = ((index % width) as f32 / width as f32, (index / width) as f32 / height as f32);
|
||
let alpha = [0., 0.4, 1., 1., 1.][index % 5];
|
||
[x * alpha, y * y * alpha, (1. - x * y) * alpha, alpha].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let plane = Plane {
|
||
width,
|
||
height,
|
||
data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(),
|
||
};
|
||
|
||
// Opaque gray maps of each pixel's luminance: one gray, a ramp across, scattered values, and checks of none and all of the radius
|
||
type CodeAt = fn(usize, usize) -> usize;
|
||
let maps: [(&str, CodeAt); 4] = [
|
||
("gray", |_, _| 102),
|
||
("ramp", |x, _| x * 255 / 95),
|
||
("scattered", |x, y| (x * 7919 + y * 104_729) % 256),
|
||
("checks", |x, y| if (x / 6 + y / 6) % 2 == 0 { 0 } else { 255 }),
|
||
];
|
||
for (name, code_at) in maps {
|
||
let map: Vec<[f16; 4]> = (0..width * height)
|
||
.map(|index| {
|
||
let gray = code_at(index % width, index / width) as f32 / 255.;
|
||
[gray, gray, gray, 1.].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let luminance = |texel: &[f16; 4]| mask_coverage(texel.map(f16::to_f32), MaskMode::LuminanceSvg).clamp(0., 1.);
|
||
let luminances: Vec<f32> = map.iter().map(|texel| f16::from_f32(luminance(texel)).to_f32()).collect();
|
||
|
||
for (radius, gamma) in [(7.3, false), (7.3, true), (16., false), (30.5, true)] {
|
||
let Some(gpu) = gpu_effect_texels(&masked_box_blur(radius, gamma), &texels, width, &[&map]) else {
|
||
return;
|
||
};
|
||
let cpu = raster_kernels::masks::variable_box_blur(&plane, &luminances, glam::DVec2::splat(radius), !gamma);
|
||
|
||
// Within the rounding of the GPU's half floats
|
||
let differences = gpu.iter().zip(&cpu.data).flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs()));
|
||
let worst = differences.fold(0., f32::max) * 255.;
|
||
assert!(worst < 0.3, "a {name} map at {radius} pixels (gamma: {gamma}) differs from the CPU by {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_box_blurs_with_a_white_radius_mask_match_those_without_at_any_radius() {
|
||
use half::f16;
|
||
|
||
// Colorful content blurred past the widest box the GPU runs directly, where both sum the same running sums
|
||
let (width, height) = (96, 72);
|
||
let texels: Vec<[f16; 4]> = (0..width * height)
|
||
.map(|index| {
|
||
let (x, y) = ((index % width) as f32 / width as f32, (index / width) as f32 / height as f32);
|
||
let alpha = [0., 0.4, 1., 1., 1.][index % 5];
|
||
[x * alpha, y * y * alpha, (1. - x * y) * alpha, alpha].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let white = vec![[f16::ONE; 4]; width * height];
|
||
|
||
for gamma in [false, true] {
|
||
let plain = graphic_types::Effects::from_operations([graphic_types::EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 40.,
|
||
box_blur: true,
|
||
gamma,
|
||
}]);
|
||
let Some(plain) = gpu_effect_texels(&plain, &texels, width, &[]) else { return };
|
||
let Some(masked) = gpu_effect_texels(&masked_box_blur(40., gamma), &texels, width, &[&white]) else {
|
||
return;
|
||
};
|
||
|
||
let differences = plain.iter().zip(&masked).flat_map(|(plain, masked)| (0..4).map(|channel| (plain[channel] - masked[channel]).abs()));
|
||
let worst = differences.fold(0., f32::max) * 255.;
|
||
assert!(worst < 0.3, "a white radius mask differs from none by {worst} levels (gamma: {gamma})");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_masked_box_blurs_stay_exact_across_large_images() {
|
||
use half::f16;
|
||
|
||
// Nearly white content of 8 million pixels, whose running sums reach the millions, too many for one f32 to hold to a pixel's worth
|
||
let (width, height) = (4096, 2048);
|
||
let texels: Vec<[f16; 4]> = (0..width * height)
|
||
.map(|index: usize| {
|
||
let value = 0.9 + 0.1 * (index.wrapping_mul(2_654_435_761) % 1000) as f32 / 1000.;
|
||
[value, value, value, 1.].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let map = vec![[f16::ONE; 4]; width * height];
|
||
|
||
for gamma in [true, false] {
|
||
// The opaque content's colors in the light the blur sums them in
|
||
let transfer = |convert: fn(f32) -> f32, [red, green, blue, alpha]: [f32; 4]| [convert(red), convert(green), convert(blue), alpha];
|
||
let channels: Vec<[f32; 4]> = (texels.iter().map(|texel| texel.map(f16::to_f32)))
|
||
.map(|channels| if gamma { channels } else { transfer(core_types::color::srgb_to_linear, channels) })
|
||
.collect();
|
||
|
||
let radius = 1.5;
|
||
let Some(gpu) = gpu_effect_texels(&masked_box_blur(radius, gamma), &texels, width, &[&map]) else {
|
||
return;
|
||
};
|
||
|
||
// The smallest boxes in the corner the sums end at, where a single f32's rounding would outweigh them, and in the corner they start at
|
||
let mut worst = 0_f32;
|
||
for y in (height - 32..height).chain(0..4) {
|
||
for x in (width - 32..width).chain(0..4) {
|
||
let summed = summed_box(&channels, width, height, x, y, radius).map(|channel| channel as f32);
|
||
let expected = if gamma { summed } else { transfer(core_types::color::linear_to_srgb, summed) };
|
||
let actual = gpu[y * width + x];
|
||
worst = worst.max((0..4).map(|channel| (actual[channel] - expected[channel]).abs()).fold(0., f32::max));
|
||
}
|
||
}
|
||
assert!(worst * 255. < 0.3, "a box blur strays {} levels from the exact box at the far corner (gamma: {gamma})", worst * 255.);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn later_shadows_stack_over_earlier_ones_beneath_the_content() {
|
||
use core_types::Color as GraphicColor;
|
||
use glam::DVec2;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let shadow = |color, offset: f64| drop_shadow(color, DVec2::splat(offset), 0., 0.);
|
||
|
||
// Both shadows are cast from the content rather than from each other, and the later one is on top where they overlap
|
||
let effects = vec![shadow(GraphicColor::BLACK, 10.), shadow(GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 1.), 5.)];
|
||
let Some(pixels) = render_square_with_effects(effects, 1., 30., 80., size) else { return };
|
||
assert_eq!(pixel(&pixels, size, 82, 82), [0, 0, 255, 255], "the later shadow is on top");
|
||
assert_eq!(pixel(&pixels, size, 88, 88), [0, 0, 0, 255], "the earlier shadow reaches further");
|
||
assert_eq!(pixel(&pixels, size, 93, 93)[3], 0, "no shadow of a shadow");
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_blur_what_lies_beneath_within_the_content() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = Rect::new(32., 32., 96., 96.);
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
}]);
|
||
|
||
// Red to the left of x = 64 and blue to the right, beneath a square of no fill straddling the border, inside a clip of all but the bottom rows, which the restart keeps clipping
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &Rect::new(0., 0., 128., 120.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 0, 0), None, &Rect::new(0., 0., 64., 128.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(0, 0, 255), None, &Rect::new(64., 0., 128., 128.));
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||
});
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(0, 255, 0), None, &Rect::new(0., 100., 128., 128.));
|
||
scene.pop_layer();
|
||
};
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
|
||
let [red, _, blue, alpha] = pixel(&pixels, size, 64, 64);
|
||
assert!(red > 100 && blue > 100 && alpha == 255, "the border blurs within the content: {:?}", pixel(&pixels, size, 64, 64));
|
||
assert_eq!(pixel(&pixels, size, 40, 64), [255, 0, 0, 255], "far from the border, the blur leaves red");
|
||
assert_eq!(pixel(&pixels, size, 63, 20), [255, 0, 0, 255], "outside the content, the border stays sharp");
|
||
assert_eq!(pixel(&pixels, size, 64, 20), [0, 0, 255, 255], "on both sides");
|
||
assert_eq!(pixel(&pixels, size, 20, 110), [0, 255, 0, 255], "what's drawn after it is clipped as before");
|
||
assert_eq!(pixel(&pixels, size, 20, 124)[3], 0, "past the clip");
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_show_what_lies_beneath_them_in_any_effect_space() {
|
||
use glam::{DMat2, DVec2};
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = Rect::new(32., 32., 96., 96.);
|
||
let background_blur = EffectOperation::BackgroundBlur {
|
||
radius: 1.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let box_blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 1.,
|
||
box_blur: true,
|
||
gamma: false,
|
||
};
|
||
|
||
// Glass stretched or sheared since its blur was stamped, and turned glass with a box blur, each rendered along its effect space's axes
|
||
let stretched = DAffine2::from_scale(DVec2::new(2., 1.));
|
||
let sheared = DAffine2::from_mat2(DMat2::from_cols(DVec2::X, DVec2::new(0.5, 1.)));
|
||
let turned = DAffine2::from_angle(30_f64.to_radians());
|
||
let cases = [
|
||
("stretched", stretched, vec![background_blur.clone()]),
|
||
("sheared", sheared, vec![background_blur.clone()]),
|
||
("turned", turned, vec![background_blur, box_blur]),
|
||
];
|
||
|
||
// A color in each quarter of the render, beneath a square of no fill covering part of each
|
||
let (green, white) = (Color::from_rgb8(0, 255, 0), Color::from_rgb8(255, 255, 255));
|
||
let quarters = [(0., 0., RED), (64., 0., green), (0., 64., BLUE), (64., 64., white)];
|
||
|
||
for (name, effect_space, operations) in cases {
|
||
let effects = Effects::from_operations(operations);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
for (x, y, color) in quarters {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, color, None, &Rect::new(x, y, x + 64., y + 64.));
|
||
}
|
||
scene.draw_effects(&effects, 0., 1., BlendMode::Normal, true, Some(square), effect_space, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||
});
|
||
};
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
|
||
// Each quarter shows through the glass where it lies, near the borders between them and near the glass's corners
|
||
let shown = [
|
||
(54, 54, [255, 0, 0]),
|
||
(74, 54, [0, 255, 0]),
|
||
(54, 74, [0, 0, 255]),
|
||
(74, 74, [255, 255, 255]),
|
||
(38, 38, [255, 0, 0]),
|
||
(90, 38, [0, 255, 0]),
|
||
(38, 90, [0, 0, 255]),
|
||
(90, 90, [255, 255, 255]),
|
||
];
|
||
for (x, y, expected) in shown {
|
||
let [red, green, blue, alpha] = pixel(&pixels, size, x, y);
|
||
let close = [red, green, blue].iter().zip(expected).all(|(&channel, expected)| channel.abs_diff(expected) <= 2);
|
||
assert!(close && alpha == 255, "{name} glass at ({x}, {y}): {:?} against {expected:?}", pixel(&pixels, size, x, y));
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn masks_cut_what_background_blurs_blur_as_they_cut_the_content() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, MaskMode, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Red to the left of x = 64 and blue to the right, then glass of no fill straddling the border, masked to its top half
|
||
let image = |color: core_types::Color, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let top_half = image(core_types::Color::WHITE, DVec2::ZERO, DVec2::new(1., 0.5));
|
||
let operations = [
|
||
EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
},
|
||
EffectOperation::Mask {
|
||
mask: Graphic::RasterCPU(Box::new(top_half)),
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
},
|
||
];
|
||
let mut glass = image(core_types::Color::WHITE, DVec2::splat(32.), DVec2::splat(64.)).with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||
operations.iter().for_each(|operation| stamp_effect(&mut glass, Effect::new(operation)));
|
||
let mut images = List::new_from_item(image(core_types::Color::RED, DVec2::ZERO, DVec2::new(64., 128.)));
|
||
images.push(image(core_types::Color::BLUE, DVec2::new(64., 0.), DVec2::new(64., 128.)));
|
||
images.push(glass);
|
||
let graphic = Graphic::RasterCPUList(images);
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
let [red, _, blue, _] = pixel(&pixels, size, 64, 40);
|
||
assert!(red > 100 && blue > 100, "the border blurs within the shown glass: {:?}", pixel(&pixels, size, 64, 40));
|
||
assert_eq!(pixel(&pixels, size, 64, 88), [0, 0, 255, 255], "where the mask hides the glass, the border stays sharp");
|
||
assert_eq!(pixel(&pixels, size, 63, 88), [255, 0, 0, 255], "on both sides");
|
||
}
|
||
|
||
#[test]
|
||
fn masks_trailing_background_blurs_fade_the_copy_with_the_content_as_one_layer_on_the_gpu_and_in_svg() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::{Item, List};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, MaskMode, stamp_effect};
|
||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||
|
||
// Black to the left of x = 64 and white to the right, then opaque white glass over the border, faded by half by a black luminance mask at half density
|
||
let image = |color: core_types::Color, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let operations = [
|
||
EffectOperation::BackgroundBlur {
|
||
radius: 8.,
|
||
box_blur: false,
|
||
gamma: true,
|
||
},
|
||
EffectOperation::Mask {
|
||
mask: Graphic::RasterCPU(Box::new(image(core_types::Color::BLACK, DVec2::ZERO, DVec2::ONE))),
|
||
mode: MaskMode::Luminance,
|
||
density: 50.,
|
||
feather: 0.,
|
||
invert: false,
|
||
},
|
||
];
|
||
let mut glass = image(core_types::Color::WHITE, DVec2::splat(32.), DVec2::splat(64.));
|
||
operations.iter().for_each(|operation| stamp_effect(&mut glass, Effect::new(operation)));
|
||
let mut images = List::new_from_item(image(core_types::Color::BLACK, DVec2::ZERO, DVec2::new(64., 128.)));
|
||
images.push(image(core_types::Color::WHITE, DVec2::new(64., 0.), DVec2::new(64., 128.)));
|
||
images.push(glass);
|
||
let graphic = Graphic::RasterCPUList(images);
|
||
|
||
// SVG applies the mask once, to a group around the blurred copy and the content, so the copy doesn't show through the faded content
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
graphic.render_svg(&mut svg, &export);
|
||
let markup = svg.svg.to_svg_string();
|
||
assert_eq!(markup.matches(r#"mask="url(#mask-"#).count(), 1, "{markup}");
|
||
let faded = element_markup(&markup, r#"<g mask="url(#mask-"#).unwrap_or_default();
|
||
assert!(faded.contains(r##"<use href="#backdrop-"##) && faded.contains("<image"), "{markup}");
|
||
|
||
// On the GPU, the opaque content hides the copy, so the faded layer shows half white over each side of the border, blurred or not
|
||
let size = UVec2::new(128, 128);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
for (x, expected) in [(40, 128), (60, 128), (68, 255), (88, 255)] {
|
||
let [red, green, blue, alpha] = pixel(&pixels, size, x, 64);
|
||
let close = [red, green, blue].iter().all(|channel| channel.abs_diff(expected) <= 2);
|
||
assert!(close && alpha == 255, "at x = {x}: {:?} against {expected}", pixel(&pixels, size, x, 64));
|
||
}
|
||
}
|
||
|
||
/// The markup of the first element with an opening tag starting with `opening`, through its closing tag, so it holds just that element and those inside it.
|
||
fn element_markup<'a>(markup: &'a str, opening: &str) -> Option<&'a str> {
|
||
let start = markup.find(opening)?;
|
||
let name = opening.strip_prefix('<')?.split([' ', '/', '>']).next()?;
|
||
let (open, close) = (format!("<{name}"), format!("</{name}>"));
|
||
|
||
// Its closing tag is the one returning the nesting of tags of its name to none
|
||
let (mut depth, mut index) = (0, start);
|
||
while let Some(offset) = markup[index..].find('<') {
|
||
let tag_start = index + offset;
|
||
index = tag_start + markup[tag_start..].find('>')? + 1;
|
||
let tag = &markup[tag_start..index];
|
||
|
||
if tag == close {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
return Some(&markup[start..index]);
|
||
}
|
||
} else if tag.strip_prefix(&open).is_some_and(|rest| rest.starts_with([' ', '>'])) && !tag.ends_with("/>") {
|
||
depth += 1;
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_inside_a_faded_group_blur_what_the_group_drew_beneath_them() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Red to the left of x = 64 and blue to the right, then glass of no fill straddling the border, in a group at half opacity
|
||
let image = |color: core_types::Color, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let mut images = List::new_from_item(image(core_types::Color::RED, DVec2::ZERO, DVec2::new(64., 128.)));
|
||
images.push(image(core_types::Color::BLUE, DVec2::new(64., 0.), DVec2::new(64., 128.)));
|
||
let blur = EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let mut glass = image(core_types::Color::WHITE, DVec2::splat(32.), DVec2::splat(64.)).with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||
stamp_effect(&mut glass, Effect::new(&blur));
|
||
images.push(glass);
|
||
let group = Graphic::Graphic(Box::new(Item::new_from_element(Graphic::RasterCPUList(images)).with_attribute(ATTR_OPACITY, 0.5_f64)));
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let Some(pixels) = render(size, |scene| group.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// The group renders offscreen, where its glass finds what it drew so far beneath it, all faded by half
|
||
let [red, _, blue, alpha] = pixel(&pixels, size, 64, 64);
|
||
assert!(
|
||
red > 100 && blue > 100 && alpha.abs_diff(128) <= 2,
|
||
"the border blurs within the glass: {:?}",
|
||
pixel(&pixels, size, 64, 64)
|
||
);
|
||
let [red, _, blue, _] = pixel(&pixels, size, 64, 20);
|
||
assert!(red == 0 && blue > 200, "outside the glass, the border stays sharp: {:?}", pixel(&pixels, size, 64, 20));
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_blur_an_image_the_gpu_renders_of_what_lies_beneath_glass_over_other_glass() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::deferred_image::DeferredContent;
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
|
||
// Red to the left of x = 64 and blue to the right, then a pane of glass of no fill over the border, and a larger pane over that
|
||
let image = |color: GraphicColor, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let glass = |min: DVec2, size: DVec2| {
|
||
let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||
let blur = EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
stamp_effect(&mut glass, Effect::new(&blur));
|
||
glass
|
||
};
|
||
let mut beneath = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::new(64., 128.)));
|
||
beneath.push(image(GraphicColor::BLUE, DVec2::new(64., 0.), DVec2::new(64., 128.)));
|
||
beneath.push(glass(DVec2::new(32., 16.), DVec2::new(64., 32.)));
|
||
let mut images = beneath.clone();
|
||
images.push(glass(DVec2::new(16., 8.), DVec2::new(96., 64.)));
|
||
|
||
// SVG blurs an image of what lies beneath the upper pane, the lower pane included, rather than a copy holding the lower pane's copy
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
Graphic::RasterCPUList(images).render_svg(&mut svg, &export);
|
||
let [deferred] = &svg.deferred_images[..] else {
|
||
panic!("expected one image, got {}", svg.deferred_images.len())
|
||
};
|
||
assert!(matches!(deferred.content, DeferredContent::Beneath { .. }));
|
||
|
||
let size = UVec2::splat(128);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: size,
|
||
..Default::default()
|
||
};
|
||
let (placement, image_size, image_pixels) = {
|
||
let _turn = take_turn();
|
||
let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint);
|
||
let [(placement, texture)] = &rendered[..] else {
|
||
panic!("expected one image, got {}", rendered.len())
|
||
};
|
||
(placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap())
|
||
};
|
||
let image_pixel = |x: u32, y: u32| {
|
||
let unit = placement.transform.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||
let texel = (unit * image_size.as_dvec2()).floor().as_uvec2();
|
||
let start = ((texel.y * image_size.x + texel.x) * 4) as usize;
|
||
<[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap()
|
||
};
|
||
|
||
// The image matches the GPU's own render of what lies beneath: the border blurred within the lower pane and sharp beside it
|
||
let beneath = Graphic::RasterCPUList(beneath);
|
||
let Some(pixels) = render(size, |scene| beneath.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let [red, _, blue, _] = image_pixel(64, 32);
|
||
assert!(red > 100 && blue > 100, "the border blurs within the lower pane: {:?}", image_pixel(64, 32));
|
||
assert_eq!([image_pixel(63, 60), image_pixel(64, 60)], [[255, 0, 0, 255], [0, 0, 255, 255]], "beside it, the border stays sharp");
|
||
for (x, y) in [(64, 32), (40, 32), (88, 32), (60, 20), (68, 44), (20, 12), (108, 68)] {
|
||
let (expected, actual) = (pixel(&pixels, size, x, y), image_pixel(x, y));
|
||
assert!(expected.iter().zip(actual).all(|(&a, b)| a.abs_diff(b) <= 2), "at ({x}, {y}): {actual:?} against {expected:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_its_clipping_artboard_before_the_glass_beneath_blurs_it() {
|
||
use core_types::list::{ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_BACKGROUND, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Artboard, Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
|
||
// A white clipping artboard holding red just past its left edge, then two overlapping panes of glass of no fill just inside it
|
||
let image = |color: GraphicColor, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let glass = |min: DVec2, size: DVec2| {
|
||
let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||
let blur = EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
stamp_effect(&mut glass, Effect::new(&blur));
|
||
glass
|
||
};
|
||
let artboards = |panes: usize| {
|
||
let mut content = List::new_from_item(image(GraphicColor::RED, DVec2::new(-24., 8.), DVec2::new(20., 48.)));
|
||
content.push(glass(DVec2::new(2., 16.), DVec2::new(40., 32.)));
|
||
if panes > 1 {
|
||
content.push(glass(DVec2::new(4., 12.), DVec2::new(48., 40.)));
|
||
}
|
||
let mut artboards = List::new_from_element(Artboard::new(List::new_from_element(Graphic::RasterCPUList(content))));
|
||
artboards.set_attribute(ATTR_LOCATION, 0, DVec2::new(32., 0.));
|
||
artboards.set_attribute(ATTR_DIMENSIONS, 0, DVec2::new(96., 64.));
|
||
artboards.set_attribute(ATTR_BACKGROUND, 0, GraphicColor::WHITE);
|
||
artboards.set_attribute(ATTR_CLIP, 0, true);
|
||
artboards
|
||
};
|
||
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
artboards(2).render_svg(&mut svg, &export);
|
||
let size = UVec2::new(128, 64);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: size,
|
||
..Default::default()
|
||
};
|
||
let (placement, image_size, image_pixels) = {
|
||
let _turn = take_turn();
|
||
let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint);
|
||
let [(placement, texture)] = &rendered[..] else {
|
||
panic!("expected one image, got {}", rendered.len())
|
||
};
|
||
(placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap())
|
||
};
|
||
let image_pixel = |x: u32, y: u32| {
|
||
let user = placement.user_to_document.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||
let texel = (placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2();
|
||
let start = ((texel.y * image_size.x + texel.x) * 4) as usize;
|
||
<[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap()
|
||
};
|
||
|
||
// The image of what lies beneath the upper pane matches the GPU's own render, where the lower pane blurs only the white the artboard clips to
|
||
let beneath = artboards(1);
|
||
let Some(pixels) = render(size, |scene| beneath.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
for (x, y) in [(33, 32), (35, 24), (38, 40), (60, 32)] {
|
||
let (expected, actual) = (pixel(&pixels, size, x, y), image_pixel(x, y));
|
||
let [red, green, blue, _] = actual;
|
||
assert!(green.abs_diff(red) <= 2 && blue.abs_diff(red) <= 2, "no red reaches in at ({x}, {y}): {actual:?}");
|
||
assert!(expected.iter().zip(actual).all(|(&a, b)| a.abs_diff(b) <= 2), "at ({x}, {y}): {actual:?} against {expected:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_the_faces_a_branching_clipping_mask_fills() {
|
||
use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_PATHS, Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::vector::{CurveType, Path, PointId, SegmentId};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
|
||
// A diamond in a 64 unit square, its walls separate segments branching at every point, so it fills its five faces rather than its contours
|
||
let corners_and_midpoints = [(0., 0.), (64., 0.), (64., 64.), (0., 64.), (32., 0.), (64., 32.), (32., 64.), (0., 32.)];
|
||
let walls = [(0, 4), (1, 4), (1, 5), (2, 5), (2, 6), (3, 6), (3, 7), (0, 7), (4, 5), (5, 6), (6, 7), (4, 7)];
|
||
let mut mesh = Vector::default();
|
||
let mut point_id = PointId::ZERO;
|
||
for (index, (x, y)) in corners_and_midpoints.into_iter().enumerate() {
|
||
mesh.0.push(Item::new_from_element(DVec2::new(x, y)));
|
||
mesh.0.set_attribute(ATTR_ID, index, point_id.next_id());
|
||
}
|
||
let mut paths = List::new();
|
||
let mut segment_id = SegmentId::ZERO;
|
||
for (start, end) in walls {
|
||
let mut path = Path::from_references([start, end]);
|
||
path.0.set_attribute(ATTR_ID, 0, segment_id.next_id());
|
||
paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear));
|
||
}
|
||
let base = Item::new_from_element(mesh)
|
||
.with_attribute(ATTR_PATHS, paths)
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(32.)));
|
||
|
||
// The mesh clipping a group of red filling the render and two overlapping panes of glass of no fill inside the square
|
||
let image = |color: GraphicColor, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let glass = |min: DVec2, size: DVec2| {
|
||
let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||
let blur = EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
stamp_effect(&mut glass, Effect::new(&blur));
|
||
glass
|
||
};
|
||
let mut clipped = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::splat(128.)));
|
||
clipped.push(glass(DVec2::new(44., 52.), DVec2::new(40., 24.)));
|
||
clipped.push(glass(DVec2::new(40., 48.), DVec2::new(48., 32.)));
|
||
let group = Item::new_from_element(Graphic::RasterCPUList(clipped)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
let graphic = Graphic::GraphicList(
|
||
[
|
||
Item::new_from_element(Graphic::VectorList(List::new_from_item(base))),
|
||
Item::new_from_element(Graphic::Graphic(Box::new(group))),
|
||
]
|
||
.into_iter()
|
||
.collect(),
|
||
);
|
||
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
graphic.render_svg(&mut svg, &export);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: UVec2::splat(128),
|
||
..Default::default()
|
||
};
|
||
let (placement, image_size, image_pixels) = {
|
||
let _turn = take_turn();
|
||
let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint);
|
||
let [(placement, texture)] = &rendered[..] else {
|
||
panic!("expected one image, got {}", rendered.len())
|
||
};
|
||
(placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap())
|
||
};
|
||
let image_pixel = |x: u32, y: u32| {
|
||
let user = placement.user_to_document.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||
let texel = (placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2();
|
||
let start = ((texel.y * image_size.x + texel.x) * 4) as usize;
|
||
<[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap()
|
||
};
|
||
|
||
// The image of what lies beneath the upper pane holds the red within every face and across the walls between them, and nothing past the square
|
||
for (x, y) in [(64, 64), (36, 36), (92, 36), (36, 92), (92, 92), (64, 40), (88, 64), (47, 48), (79, 48), (48, 79), (79, 79)] {
|
||
assert_eq!(image_pixel(x, y), [255, 0, 0, 255], "within the faces at ({x}, {y})");
|
||
}
|
||
for (x, y) in [(26, 64), (64, 31), (101, 64)] {
|
||
assert_eq!(image_pixel(x, y)[3], 0, "past the square at ({x}, {y})");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_the_union_of_shapes_a_clipping_mask_fills_whatever_their_windings() {
|
||
use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_PATHS, Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::vector::{CurveType, Path, PointId, SegmentId};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
|
||
// Two triangles from the origin, crossing as one loop through their shared corners, a spur making the vector branch, and a rectangle inside the lower lobe.
|
||
// Its faces' windings cancel within the rectangle, which SVG still fills, filling each face apart.
|
||
let points = [(0., 0.), (10., 10.), (0., 10.), (6., 0.), (0., -2.), (2., 0.5), (4., 0.5), (4., 1.5), (2., 1.5)];
|
||
let paths: [&[u32]; 4] = [&[0, 1, 2], &[0, 3, 2], &[0, 4], &[5, 6, 7, 8, 5]];
|
||
let mut vector = Vector::default();
|
||
let mut point_id = PointId::ZERO;
|
||
for (index, (x, y)) in points.into_iter().enumerate() {
|
||
vector.0.push(Item::new_from_element(DVec2::new(x, y)));
|
||
vector.0.set_attribute(ATTR_ID, index, point_id.next_id());
|
||
}
|
||
let mut path_list = List::new();
|
||
let mut segment_id = SegmentId::ZERO;
|
||
for references in paths {
|
||
let mut path = Path::from_references(references.iter().copied());
|
||
for span in 0..references.len() - 1 {
|
||
path.0.set_attribute(ATTR_ID, span, segment_id.next_id());
|
||
}
|
||
path_list.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear));
|
||
}
|
||
let placement = DAffine2::from_translation(DVec2::new(24., 32.)) * DAffine2::from_scale(DVec2::splat(8.));
|
||
let base = Item::new_from_element(vector).with_attribute(ATTR_PATHS, path_list).with_attribute(ATTR_TRANSFORM, placement);
|
||
|
||
// It clips a group of red left of x = 60 and blue right of it, glass of no fill over the rectangle and that border, and larger glass over all of it
|
||
let image = |color: GraphicColor, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let glass = |min: DVec2, size: DVec2| {
|
||
let mut glass = image(GraphicColor::WHITE, min, size).with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||
let blur = EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
stamp_effect(&mut glass, Effect::new(&blur));
|
||
glass
|
||
};
|
||
let mut clipped = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::new(60., 128.)));
|
||
clipped.push(image(GraphicColor::BLUE, DVec2::new(60., 0.), DVec2::new(68., 128.)));
|
||
clipped.push(glass(DVec2::new(40., 32.), DVec2::new(32., 16.)));
|
||
clipped.push(glass(DVec2::new(16., 16.), DVec2::new(96., 96.)));
|
||
let group = Item::new_from_element(Graphic::RasterCPUList(clipped)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
let graphic = Graphic::GraphicList(
|
||
[
|
||
Item::new_from_element(Graphic::VectorList(List::new_from_item(base))),
|
||
Item::new_from_element(Graphic::Graphic(Box::new(group))),
|
||
]
|
||
.into_iter()
|
||
.collect(),
|
||
);
|
||
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
graphic.render_svg(&mut svg, &export);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: UVec2::splat(128),
|
||
..Default::default()
|
||
};
|
||
let (image_placement, image_size, image_pixels) = {
|
||
let _turn = take_turn();
|
||
let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint);
|
||
let [(image_placement, texture)] = &rendered[..] else {
|
||
panic!("expected one image, got {}", rendered.len())
|
||
};
|
||
(image_placement.clone(), UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap())
|
||
};
|
||
let image_pixel = |shape_point: (f64, f64)| {
|
||
let point = placement.transform_point2(DVec2::new(shape_point.0, shape_point.1));
|
||
let user = image_placement.user_to_document.inverse().transform_point2(point);
|
||
let texel = (image_placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2();
|
||
let start = ((texel.y * image_size.x + texel.x) * 4) as usize;
|
||
<[u8; 4]>::try_from(&image_pixels[start..start + 4]).unwrap()
|
||
};
|
||
|
||
// The image of what lies beneath the upper pane covers the rectangle, both lobes, and the triangles' contours, and nothing past them
|
||
for shape_point in [(3., 1.), (5., 0.5), (3., 8.), (1., 5.)] {
|
||
assert_eq!(image_pixel(shape_point)[3], 255, "covered at {shape_point:?}: {:?}", image_pixel(shape_point));
|
||
}
|
||
for shape_point in [(8., 3.), (9., 1.), (-1., 5.)] {
|
||
assert_eq!(image_pixel(shape_point)[3], 0, "past every shape at {shape_point:?}: {:?}", image_pixel(shape_point));
|
||
}
|
||
|
||
// The lower pane still read what lies beneath it there, blurring the border between red and blue
|
||
let [red, _, blue, _] = image_pixel((4.5, 1.));
|
||
assert!(red > 60 && blue > 60, "the border blurs within the lower pane: {:?}", image_pixel((4.5, 1.)));
|
||
}
|
||
|
||
/// The alphas at x = 39, 40, and 41 of the image an SVG blurs of what lies beneath the uppermost of four panes of glass beside a stripe from x = 40 to 40.5,
|
||
/// in a group of red the `bases` clip, or `None` without a GPU. The three panes beneath each read what lies beneath them as the image renders.
|
||
fn alphas_across_a_thin_clip_beneath_glass(bases: core_types::list::List<graphic_types::Vector>) -> Option<[u8; 3]> {
|
||
use core_types::list::{Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
let executor = executor()?;
|
||
|
||
let image = |color: GraphicColor, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let mut clipped = List::new_from_item(image(GraphicColor::RED, DVec2::ZERO, DVec2::splat(128.)));
|
||
for _ in 0..4 {
|
||
let mut glass = image(GraphicColor::WHITE, DVec2::new(44., 24.), DVec2::new(16., 80.)).with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||
let blur = EffectOperation::BackgroundBlur {
|
||
radius: 2.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
stamp_effect(&mut glass, Effect::new(&blur));
|
||
clipped.push(glass);
|
||
}
|
||
let group = Item::new_from_element(Graphic::RasterCPUList(clipped)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
let graphic = Graphic::GraphicList(
|
||
[Item::new_from_element(Graphic::VectorList(bases)), Item::new_from_element(Graphic::Graphic(Box::new(group)))]
|
||
.into_iter()
|
||
.collect(),
|
||
);
|
||
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
graphic.render_svg(&mut svg, &export);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: UVec2::splat(128),
|
||
..Default::default()
|
||
};
|
||
let _turn = take_turn();
|
||
let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint);
|
||
let [.., (placement, texture)] = &rendered[..] else { panic!("expected an image") };
|
||
assert_eq!(rendered.len(), 3, "each pane above the lowest blurs an image of what lies beneath it");
|
||
let (image_size, image_pixels) = (UVec2::new(texture.width(), texture.height()), executor.read_texture_pixels(texture).unwrap());
|
||
let alpha = |x: u32| {
|
||
let user = placement.user_to_document.inverse().transform_point2(DVec2::new(x as f64 + 0.5, 64.5));
|
||
let texel = (placement.transform.inverse().transform_point2(user) * image_size.as_dvec2()).floor().as_uvec2();
|
||
image_pixels[((texel.y * image_size.x + texel.x) * 4 + 3) as usize]
|
||
};
|
||
Some([alpha(39), alpha(40), alpha(41)])
|
||
}
|
||
|
||
/// A stripe half a pixel wide, from x = 40 to 40.5.
|
||
fn thin_stripe() -> core_types::list::Item<graphic_types::Vector> {
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
graphic_types::Vector::item_from_bezpath(&Rect::new(40., 16., 40.5, 112.).to_path(0.1))
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_blur_images_of_what_lies_beneath_glass_keeping_a_thin_clip_partly_covered_through_every_read() {
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
// The stripe with a square elsewhere, which unite into one outline
|
||
let square = graphic_types::Vector::item_from_bezpath(&Rect::new(80., 40., 100., 60.).to_path(0.1));
|
||
let Some(alphas) = alphas_across_a_thin_clip_beneath_glass([thin_stripe(), square].into_iter().collect()) else {
|
||
return;
|
||
};
|
||
|
||
// The stripe covers half its pixel however many times the panes beneath read what lies beneath them
|
||
let [left, middle, right] = alphas;
|
||
assert!(left == 0 && middle.abs_diff(128) <= 2 && right == 0, "{alphas:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_blur_images_of_what_lies_beneath_glass_cut_by_coincident_thin_clipping_shapes_as_by_one() {
|
||
let Some(alphas) = alphas_across_a_thin_clip_beneath_glass([thin_stripe(), thin_stripe()].into_iter().collect()) else {
|
||
return;
|
||
};
|
||
|
||
// Two coincident stripes cover half the pixel, as one does, rather than adding up to all of it
|
||
let [left, middle, right] = alphas;
|
||
assert!(left == 0 && middle.abs_diff(128) <= 2 && right == 0, "{alphas:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn svg_blend_ifs_in_the_viewport_read_what_lies_beneath_as_displayed_and_as_later_blend_ifs_read_it() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let Some(executor) = executor() else { return };
|
||
|
||
// A white image the viewport draws through a canvas, then a black square and a red one over it, each hidden by Blend If where light tones lie beneath
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.underlying.gray.range_end = 40.;
|
||
ranges.underlying.gray.falloff_end = 60.;
|
||
let square = |color: GraphicColor| {
|
||
let mut square = Vector::item_from_bezpath(&Rect::new(32., 32., 96., 96.).to_path(0.1));
|
||
square.set_attribute(
|
||
core_types::list::ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))),
|
||
);
|
||
stamp_effect(&mut square, Effect::new(&EffectOperation::BlendIf(Box::new(ranges))));
|
||
Item::new_from_element(Graphic::VectorList(List::new_from_item(square)))
|
||
};
|
||
let white = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, GraphicColor::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(128.)));
|
||
let white = Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(white)));
|
||
let graphic = |items: Vec<Item<Graphic>>| Graphic::GraphicList(items.into_iter().collect());
|
||
|
||
let mut svg = SvgRender::new();
|
||
graphic(vec![white.clone(), square(GraphicColor::BLACK), square(GraphicColor::RED)]).render_svg(&mut svg, &RenderParams::default());
|
||
let size = UVec2::splat(128);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: size,
|
||
..Default::default()
|
||
};
|
||
let read = {
|
||
let _turn = take_turn();
|
||
let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint);
|
||
assert_eq!(rendered.len(), 2, "each square's mask reads an image of what lies beneath it");
|
||
rendered
|
||
.iter()
|
||
.map(|(placement, texture)| {
|
||
let pixels = executor.read_texture_pixels(texture).unwrap();
|
||
let user = placement.user_to_document.inverse().transform_point2(DVec2::splat(64.5));
|
||
let texel = (placement.transform.inverse().transform_point2(user) * DVec2::new(texture.width() as f64, texture.height() as f64)).floor();
|
||
let start = ((texel.y as u32 * texture.width() + texel.x as u32) * 4) as usize;
|
||
<[u8; 4]>::try_from(&pixels[start..start + 4]).unwrap()
|
||
})
|
||
.collect::<Vec<_>>()
|
||
};
|
||
|
||
// The GPU's own render, where the black square is hidden over white
|
||
let displayed = graphic(vec![white, square(GraphicColor::BLACK)]);
|
||
let Some(pixels) = render(size, |scene| displayed.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// The black square's mask reads the white the canvas displays, rather than a stand-in for it, and the red square's reads the black one hidden over it, as displayed
|
||
assert_eq!(read[0], [255, 255, 255, 255], "the black square reads white beneath it");
|
||
assert_eq!(pixel(&pixels, size, 64, 64), [255, 255, 255, 255], "the black square is hidden over white");
|
||
assert!(read[1].iter().zip(pixel(&pixels, size, 64, 64)).all(|(&a, b)| a.abs_diff(b) <= 2), "the red square reads {:?}", read[1]);
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_in_a_clip_read_what_lies_beneath_them_only_inside_an_offscreen_render() {
|
||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Effects, Graphic, MaskMode, linked_to_content, stamp_effect};
|
||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||
|
||
let image = |color: GraphicColor, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let blur = |radius: f64| EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
|
||
// A white image, then white glass overhanging its right edge, softened by a blur that keeps its background blur in a clip, or the same without the background blur
|
||
let images = |with_background_blur: bool| {
|
||
let mut overhanging = image(GraphicColor::WHITE, DVec2::new(24., 16.), DVec2::new(20., 32.));
|
||
if with_background_blur {
|
||
let background_blur = EffectOperation::BackgroundBlur {
|
||
radius: 4.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
stamp_effect(&mut overhanging, Effect::new(&background_blur));
|
||
}
|
||
stamp_effect(&mut overhanging, Effect::new(&blur(4.)));
|
||
|
||
let mut images = List::new_from_item(image(GraphicColor::WHITE, DVec2::splat(8.), DVec2::new(24., 48.)));
|
||
images.push(overhanging);
|
||
Graphic::RasterCPUList(images)
|
||
};
|
||
|
||
// The images as the clipping base itself, then nested in a render of their own inside it: of a group with an effect kept in the clip, of a faded group, and of a mask's graphic
|
||
let bases = |with_background_blur: bool| {
|
||
let masked_placement = DAffine2::from_scale(DVec2::splat(64.));
|
||
let mut masked = image(GraphicColor::WHITE, DVec2::ZERO, DVec2::splat(64.));
|
||
let mask = EffectOperation::Mask {
|
||
mask: linked_to_content(images(with_background_blur), masked_placement),
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
stamp_effect(&mut masked, Effect::new(&mask));
|
||
let faded = Item::new_from_element(images(with_background_blur)).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||
|
||
[
|
||
("directly", Item::new_from_element(images(with_background_blur))),
|
||
(
|
||
"in a group with a blur",
|
||
Item::new_from_element(images(with_background_blur)).with_attribute(ATTR_EFFECTS, Effects::from_operations([blur(1.)])),
|
||
),
|
||
("in a faded group", Item::new_from_element(Graphic::GraphicList(List::new_from_item(faded)))),
|
||
("in a mask's graphic", Item::new_from_element(Graphic::RasterCPU(Box::new(masked)))),
|
||
]
|
||
};
|
||
|
||
// The base is hidden by its opacity, which its clip doesn't take, so a red square clipped to it shows only as much as the clip covers
|
||
let clipped_scene = |base: Item<Graphic>| {
|
||
let red = image(GraphicColor::RED, DVec2::ZERO, DVec2::splat(64.)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
let clipped = Item::new_from_element(Graphic::RasterCPU(Box::new(red)));
|
||
Graphic::GraphicList([base.with_attribute(ATTR_OPACITY, 0_f64), clipped].into_iter().collect())
|
||
};
|
||
|
||
let size = UVec2::splat(64);
|
||
for ((case, base), (_, base_without_background_blur)) in bases(true).into_iter().zip(bases(false)) {
|
||
let nested = case != "directly";
|
||
|
||
// In SVG, the glass copies what lies beneath it where the base is drawn, and in the clip only where it's nested
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
clipped_scene(base.clone()).render_svg(&mut svg, &export);
|
||
let copies = format!("{}{}", svg.svg_defs, svg.svg.to_svg_string()).matches(r##"<use href="#backdrop-"##).count();
|
||
assert_eq!(copies, 1 + nested as usize, "with the glass {case}, SVG copies what lies beneath it {copies} times");
|
||
|
||
// On the GPU, a copy adds to the clip just past the image's right edge, where the blur softens the glass's top edge
|
||
let clip_coverage = |base: Item<Graphic>| {
|
||
let graphic = clipped_scene(base);
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())).map(|pixels| pixel(&pixels, size, 32, 16)[3])
|
||
};
|
||
let (Some(with_background_blur), Some(without_background_blur)) = (clip_coverage(base), clip_coverage(base_without_background_blur)) else {
|
||
continue;
|
||
};
|
||
let message = format!("with the glass {case}, the GPU's clip covers {with_background_blur} with its background blur and {without_background_blur} without it");
|
||
match nested {
|
||
true => assert!(with_background_blur >= without_background_blur + 10, "{message}"),
|
||
false => assert!(with_background_blur.abs_diff(without_background_blur) <= 1, "{message}"),
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_read_past_the_edges_of_the_render() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: 8.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
}]);
|
||
|
||
// Stripes beneath a square crossing the right edge of the narrower render, which reads the stripes past that edge
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
for stripe in 0..16 {
|
||
let color = if stripe % 2 == 0 { Color::from_rgb8(255, 0, 0) } else { Color::from_rgb8(0, 0, 255) };
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, color, None, &Rect::new(stripe as f64 * 8., 0., stripe as f64 * 8. + 8., 64.));
|
||
}
|
||
let square = Rect::new(16., 16., 112., 48.);
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||
});
|
||
};
|
||
let (narrow, wide) = (UVec2::new(64, 64), UVec2::new(128, 64));
|
||
let (Some(narrow_pixels), Some(wide_pixels)) = (render(narrow, draw), render(wide, draw)) else {
|
||
return;
|
||
};
|
||
|
||
// The narrower render's edge matches the wider render's same pixels
|
||
for x in 56..64 {
|
||
let (narrow_pixel, wide_pixel) = (pixel(&narrow_pixels, narrow, x, 32), pixel(&wide_pixels, wide, x, 32));
|
||
assert!(narrow_pixel.iter().zip(wide_pixel).all(|(&a, b)| a.abs_diff(b) <= 2), "at {x}: {narrow_pixel:?} against {wide_pixel:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_reading_past_the_edges_of_the_render_carry_out_their_effects_once() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: 8.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
}]);
|
||
let glass = Rect::new(64., 48., 160., 80.);
|
||
|
||
// How many times a render of `size` draws the glass, and the effect passes it draws
|
||
let effects_drawn = |size: UVec2| {
|
||
let executor = executor()?;
|
||
let _turn = take_turn();
|
||
let take_drawn_passes = || std::mem::take(&mut executor.inner.document_canvas.lock().unwrap_or_else(std::sync::PoisonError::into_inner).effect_textures.drawn_passes);
|
||
take_drawn_passes();
|
||
|
||
let mut glass_drawn = 0;
|
||
let mut draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 112., 128.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(112., 0., 256., 128.));
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
glass_drawn += 1;
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass)
|
||
});
|
||
};
|
||
executor.render_vello(size, DAffine2::IDENTITY, &mut draw).unwrap_or_else(|error| panic!("Render failed: {error}"));
|
||
Some((glass_drawn, take_drawn_passes()))
|
||
};
|
||
|
||
// Glass crossing the right edge of the narrower render, and lying with its whole reach inside the wider one
|
||
let (Some(narrow), Some(wide)) = (effects_drawn(UVec2::new(128, 128)), effects_drawn(UVec2::new(256, 128))) else {
|
||
return;
|
||
};
|
||
|
||
// The narrower render carries out the blur once, in a render grown to read past its edge, as the wider one does at its own size
|
||
assert_eq!(wide.0, 1);
|
||
assert!(!wide.1.is_empty());
|
||
assert_eq!(narrow, wide);
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_beside_effects_reading_their_whole_frame_read_only_their_own_reach_past_the_render() {
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
// Glass reaching far left of the render, with a twirl that reads across the whole of an ellipse within its frame
|
||
let glass = Rect::new(-300., 0., 64., 64.);
|
||
let frame = DAffine2::from_translation(DVec2::new(-300., 0.)) * DAffine2::from_scale(DVec2::new(364., 64.));
|
||
let effects = Effects::from_operations([
|
||
EffectOperation::BackgroundBlur {
|
||
radius: 2.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
},
|
||
EffectOperation::Twirl {
|
||
angle: 90.,
|
||
transform: frame * DAffine2::from_translation(DVec2::splat(0.5)),
|
||
},
|
||
]);
|
||
|
||
let mut widths = Vec::new();
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
widths.push(scene.width());
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 0, 0), None, &Rect::new(-400., 0., 64., 64.));
|
||
scene.draw_effects(
|
||
&effects,
|
||
0.,
|
||
1.,
|
||
BlendMode::Normal,
|
||
true,
|
||
Some(glass),
|
||
DAffine2::IDENTITY,
|
||
Some((frame, 0.)),
|
||
&mut |_, _| {},
|
||
&mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass),
|
||
);
|
||
};
|
||
if render(UVec2::new(64, 64), draw).is_none() {
|
||
return;
|
||
}
|
||
|
||
// The blur reads three times its radius past the render, so a render grown to read what lies there needs no more
|
||
assert!(widths.iter().all(|&width| width <= 64 + 2 * 6), "{widths:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_out_of_reach_of_the_render_leave_it_at_its_own_size() {
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let background_blur = |box_blur| EffectOperation::BackgroundBlur { radius: 2., box_blur, gamma: false };
|
||
let shadow = drop_shadow(core_types::Color::BLACK, DVec2::new(-100., 0.), 0., 0.);
|
||
|
||
// Glass farther past the right edge than its blur reaches, kept in the region by a turned frame's bounding box or by a shadow reaching farther
|
||
let cases = [
|
||
("turned", DAffine2::from_angle(45_f64.to_radians()), vec![background_blur(true)], Rect::new(170., 59., 180., 69.)),
|
||
("beside a shadow", DAffine2::IDENTITY, vec![background_blur(false), shadow], Rect::new(308., 16., 408., 48.)),
|
||
];
|
||
|
||
for (name, effect_space, operations, glass) in cases {
|
||
let effects = Effects::from_operations(operations);
|
||
let mut widths = Vec::new();
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
widths.push(scene.width());
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 512., 128.));
|
||
scene.draw_effects(&effects, 0., 1., BlendMode::Normal, true, Some(glass), effect_space, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass)
|
||
});
|
||
};
|
||
if render(UVec2::new(128, 128), draw).is_none() {
|
||
return;
|
||
}
|
||
|
||
// No pixel in view reads what lies beneath the glass, so the scene is drawn once, at its own size
|
||
assert_eq!(widths, [128], "{name}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_over_other_background_blurs_read_through_them_past_the_edges_of_the_render() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: 8.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
}]);
|
||
|
||
// Red to the left of x = 88 and blue to the right, beneath three panes of glass crossing the right edge of the narrower render.
|
||
// Each pane reads the blurs of the panes beneath it, which read past its own reach in turn.
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(-200., 0., 88., 64.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(88., 0., 400., 64.));
|
||
let glass = Rect::new(16., 16., 240., 48.);
|
||
for _ in 0..3 {
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass)
|
||
});
|
||
}
|
||
};
|
||
let (narrow, wide) = (UVec2::new(64, 64), UVec2::new(256, 64));
|
||
let (Some(narrow_pixels), Some(wide_pixels)) = (render(narrow, draw), render(wide, draw)) else {
|
||
return;
|
||
};
|
||
|
||
// The narrower render's edge matches the wider render's same pixels, where the blue reaches through the panes
|
||
assert!(pixel(&wide_pixels, wide, 63, 32)[2] > 10, "{:?}", pixel(&wide_pixels, wide, 63, 32));
|
||
for x in 56..64 {
|
||
let (narrow_pixel, wide_pixel) = (pixel(&narrow_pixels, narrow, x, 32), pixel(&wide_pixels, wide, x, 32));
|
||
assert!(narrow_pixel.iter().zip(wide_pixel).all(|(&a, b)| a.abs_diff(b) <= 2), "at {x}: {narrow_pixel:?} against {wide_pixel:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn background_blurs_reading_farther_past_the_render_than_a_texture_holds_render_it_at_its_own_size() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
// A radius reaching so far past the render that twice its reach overflows the pixels a size can count
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: 715_827_883.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
}]);
|
||
|
||
let mut widths = Vec::new();
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
widths.push(scene.width());
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 64., 64.));
|
||
let glass = Rect::new(32., 16., 96., 48.);
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass)
|
||
});
|
||
};
|
||
let size = UVec2::new(64, 64);
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
|
||
// The scene is drawn once, at its own size, and what lies outside the glass is drawn as it is
|
||
assert_eq!(widths, [64]);
|
||
assert_eq!(pixel(&pixels, size, 16, 32), [255, 0, 0, 255]);
|
||
}
|
||
|
||
#[test]
|
||
fn renders_grow_by_their_apron_only_while_they_fit_a_texture() {
|
||
let size = UVec2::new(64, 32);
|
||
assert_eq!(super::grown_render_size(size, 0, 16_384), None);
|
||
assert_eq!(super::grown_render_size(size, 8, 16_384), Some(UVec2::new(80, 48)));
|
||
assert_eq!(super::grown_render_size(size, 8160, 16_384), Some(UVec2::new(16_384, 16_352)));
|
||
assert_eq!(super::grown_render_size(size, 8161, 16_384), None);
|
||
|
||
// Aprons too wide to count twice, or to add to the size, don't fit either
|
||
assert_eq!(super::grown_render_size(size, 2_147_483_649, 16_384), None);
|
||
assert_eq!(super::grown_render_size(size, u32::MAX / 2, 16_384), None);
|
||
}
|
||
|
||
#[test]
|
||
fn background_box_blurs_turn_their_square_with_their_effect_space() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let glass = Rect::new(16., 16., 112., 112.);
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: 6.,
|
||
box_blur: true,
|
||
gamma: false,
|
||
}]);
|
||
|
||
// Red to the left of x = 64 and blue to the right, beneath glass of no fill with its effect space turned, and no other box blur beside it
|
||
let render_turned = |degrees: f64| {
|
||
render(size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 64., 128.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(64., 0., 128., 128.));
|
||
let effect_space = DAffine2::from_angle(degrees.to_radians());
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), effect_space, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass)
|
||
});
|
||
})
|
||
};
|
||
let (Some(upright), Some(turned)) = (render_turned(0.), render_turned(45.)) else { return };
|
||
|
||
// Seven pixels from the border, an upright square's half width of 6 stops short of it, while a square turned 45° reaches across it with its corner
|
||
assert_eq!(pixel(&upright, size, 57, 64), [255, 0, 0, 255]);
|
||
let [red, _, blue, alpha] = pixel(&turned, size, 57, 64);
|
||
assert!(red > 200 && blue > 20 && alpha == 255, "{:?}", pixel(&turned, size, 57, 64));
|
||
}
|
||
|
||
#[test]
|
||
fn background_box_blurs_reach_only_their_half_width_at_any_radius() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(256, 32);
|
||
let glass = Rect::new(0., 0., 256., 32.);
|
||
|
||
// Red to the left of x = 128 and blue to the right, beneath glass covering the render, blurred directly and, past 24 pixels, by running sums
|
||
for radius in [6_u32, 40] {
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: radius as f64,
|
||
box_blur: true,
|
||
gamma: false,
|
||
}]);
|
||
let Some(pixels) = render(size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(0., 0., 128., 32.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(128., 0., 256., 32.));
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass)
|
||
});
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// Two pixels past its half width from the border, the box reads only red, and two pixels within it, some blue
|
||
assert_eq!(pixel(&pixels, size, 128 - radius - 2, 16), [255, 0, 0, 255], "radius {radius}");
|
||
assert!(pixel(&pixels, size, 128 - radius + 2, 16)[2] > 0, "radius {radius}: {:?}", pixel(&pixels, size, 128 - radius + 2, 16));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn background_box_blurs_turned_by_their_effect_space_read_their_turned_square_past_the_edges_of_the_render() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let blur = Effects::from_operations([EffectOperation::BackgroundBlur {
|
||
radius: 40.,
|
||
box_blur: true,
|
||
gamma: false,
|
||
}]);
|
||
let effect_space = DAffine2::from_angle(45_f64.to_radians());
|
||
|
||
// Red to the left of x = 174 and blue to the right, beneath glass crossing the right edge of the narrower render.
|
||
// Its box turned 45° reaches the blue from that edge with a corner about 57 pixels out, farther than the 41 it reaches unturned.
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &Rect::new(-200., -200., 174., 400.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &Rect::new(174., -200., 600., 400.));
|
||
let glass = Rect::new(0., 0., 256., 128.);
|
||
scene.draw_effects(&blur, 0., 1., BlendMode::Normal, true, Some(glass), effect_space, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &glass)
|
||
});
|
||
};
|
||
let (narrow, wide) = (UVec2::new(128, 128), UVec2::new(384, 128));
|
||
let (Some(narrow_pixels), Some(wide_pixels)) = (render(narrow, draw), render(wide, draw)) else {
|
||
return;
|
||
};
|
||
|
||
// The narrower render's edge matches the wider render's same pixels, where the blue reaches into the turned square's corner
|
||
assert!(pixel(&wide_pixels, wide, 127, 64)[2] > 10, "{:?}", pixel(&wide_pixels, wide, 127, 64));
|
||
for x in 120..128 {
|
||
let (narrow_pixel, wide_pixel) = (pixel(&narrow_pixels, narrow, x, 64), pixel(&wide_pixels, wide, x, 64));
|
||
assert!(narrow_pixel.iter().zip(wide_pixel).all(|(&a, b)| a.abs_diff(b) <= 2), "at {x}: {narrow_pixel:?} against {wide_pixel:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn effects_blend_by_their_modes_onto_what_lies_beneath() {
|
||
use core_types::Color as GraphicColor;
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let (blue, green) = (GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 1.), GraphicColor::from_rgbaf32_unchecked(0., 1., 0., 1.));
|
||
let red = Color::from_rgb8(255, 0, 0);
|
||
let close = |actual: [u8; 4], expected: [u8; 4]| actual.iter().zip(expected).all(|(&actual, expected)| actual.abs_diff(expected) <= 2);
|
||
|
||
// A blue shadow multiplying a red backdrop leaves black where it falls past the content, which still covers the backdrop
|
||
let mut shadow = drop_shadow(blue, DVec2::splat(10.), 0., 0.);
|
||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut shadow {
|
||
*blend_mode = BlendMode::Multiply;
|
||
}
|
||
let render = |effects: Vec<EffectOperation>, opacity: f32, blend_mode: BlendMode| render_square_over_backdrop(effects, 1., opacity, blend_mode, Some(red), Color::WHITE, 30., 80., size);
|
||
let Some(pixels) = render(vec![shadow.clone()], 1., BlendMode::Normal) else { return };
|
||
assert!(
|
||
close(pixel(&pixels, size, 85, 85), [0, 0, 0, 255]),
|
||
"the shadow multiplies the backdrop: {:?}",
|
||
pixel(&pixels, size, 85, 85)
|
||
);
|
||
assert_eq!(pixel(&pixels, size, 50, 50), [255, 255, 255, 255], "the content covers it");
|
||
assert_eq!(pixel(&pixels, size, 20, 20), [255, 0, 0, 255], "the backdrop shows elsewhere");
|
||
|
||
// The item's opacity fades the shadow before it blends, and its blend mode acts on the content alone
|
||
let Some(pixels) = render(vec![shadow.clone()], 0.5, BlendMode::Normal) else { return };
|
||
assert!(
|
||
close(pixel(&pixels, size, 85, 85), [128, 0, 0, 255]),
|
||
"a faded multiply halves the red: {:?}",
|
||
pixel(&pixels, size, 85, 85)
|
||
);
|
||
let Some(pixels) = render(vec![shadow], 1., BlendMode::Multiply) else { return };
|
||
assert_eq!(pixel(&pixels, size, 50, 50), [255, 0, 0, 255], "white content multiplying leaves the red backdrop");
|
||
assert!(close(pixel(&pixels, size, 85, 85), [0, 0, 0, 255]), "the shadow keeps its own mode: {:?}", pixel(&pixels, size, 85, 85));
|
||
|
||
// An inner shadow multiplying within the content tints it, and at no fill tints the backdrop seen through it
|
||
let inner_shadow = EffectOperation::InnerShadow {
|
||
color: green,
|
||
blend_mode: BlendMode::Multiply,
|
||
angle: 180.,
|
||
distance: 10.,
|
||
choke: 0.,
|
||
size: 0.,
|
||
contour: Default::default(),
|
||
};
|
||
let Some(pixels) = render(vec![inner_shadow.clone()], 1., BlendMode::Normal) else { return };
|
||
assert!(close(pixel(&pixels, size, 33, 55), [0, 255, 0, 255]), "green multiplies white: {:?}", pixel(&pixels, size, 33, 55));
|
||
let Some(pixels) = render(vec![inner_shadow.clone()], 1., BlendMode::Multiply) else { return };
|
||
assert!(
|
||
close(pixel(&pixels, size, 33, 55), [0, 0, 0, 255]),
|
||
"over multiplying content, green multiplies the red it leaves: {:?}",
|
||
pixel(&pixels, size, 33, 55)
|
||
);
|
||
let Some(pixels) = render_square_over_backdrop(vec![inner_shadow], 0., 1., BlendMode::Normal, Some(red), Color::WHITE, 30., 80., size) else {
|
||
return;
|
||
};
|
||
assert!(close(pixel(&pixels, size, 33, 55), [0, 0, 0, 255]), "green multiplies red: {:?}", pixel(&pixels, size, 33, 55));
|
||
assert_eq!(pixel(&pixels, size, 55, 55), [255, 0, 0, 255], "the faded content shows the backdrop");
|
||
}
|
||
|
||
#[test]
|
||
fn translucent_content_knocks_out_a_blended_shadow_through_its_fill_and_opacity() {
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let backdrop = Color::from_rgb8(51, 153, 255);
|
||
let content = Color::from_rgba8(255, 128, 0, 128);
|
||
let mut shadow = drop_shadow(core_types::Color::RED, DVec2::splat(10.), 0., 0.);
|
||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut shadow {
|
||
*blend_mode = BlendMode::Multiply;
|
||
}
|
||
let Some(pixels) = render_square_over_backdrop(vec![shadow], 0.5, 0.5, BlendMode::Normal, Some(backdrop), content, 30., 80., size) else {
|
||
return;
|
||
};
|
||
let close = |actual: [u8; 4], expected: [f32; 3]| actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 2.5);
|
||
let [red, green, blue] = [0.2, 0.6, 1.];
|
||
|
||
// Past the content, the red shadow cast from its half alpha, at half opacity, multiplies away a quarter of the backdrop's green and blue
|
||
let alone = pixel(&pixels, size, 85, 85);
|
||
assert!(close(alone, [red, green * 0.75, blue * 0.75]), "{alone:?}");
|
||
|
||
// Beneath the content, with half alpha faded by the half fill and half opacity, the shadow shows through 1 - alpha of the 1 - alpha × fill × opacity it shows through
|
||
let shown = 0.5 * 0.5 * (1. - 0.5) / (1. - 0.5 * 0.5 * 0.5);
|
||
let shaded = [red, green * (1. - shown), blue * (1. - shown)];
|
||
let covered = 0.5 * 0.5 * 0.5;
|
||
let expected = [1., 128. / 255., 0.].map(|channel| channel * covered);
|
||
let expected: [f32; 3] = std::array::from_fn(|channel| shaded[channel] * (1. - covered) + expected[channel]);
|
||
let beneath = pixel(&pixels, size, 75, 75);
|
||
assert!(close(beneath, expected), "{beneath:?} against {expected:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn a_trailing_mask_fades_a_glow_that_still_screens_what_lies_beneath() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{EffectOperation, Graphic, MaskMode};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let (backdrop, content, glow_color, strength) = ([0.2, 0.6, 0.9], [0.9, 0.5, 0.2], [1., 1., 0.75], 0.75);
|
||
|
||
// A glow grown by its whole size surrounds the content evenly at its color's strength
|
||
let glow = EffectOperation::OuterGlow {
|
||
color: GraphicColor::from_gamma_srgb_channels(glow_color[0], glow_color[1], glow_color[2], strength).into(),
|
||
blend_mode: BlendMode::Screen,
|
||
technique: Default::default(),
|
||
spread: 100.,
|
||
size: 5.,
|
||
range: 50.,
|
||
contour: Default::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
};
|
||
|
||
// At 60% density, a mask that's black over the square's left half and absent past the square shows 40% there, and all of the right half
|
||
let halves = (0..50).map(|column| if column < 25 { GraphicColor::BLACK } else { GraphicColor::WHITE }).collect();
|
||
let halves = Image { width: 50, height: 1, data: halves };
|
||
let across_square = DAffine2::from_translation(glam::DVec2::splat(30.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
let mask = EffectOperation::Mask {
|
||
mask: Graphic::from(Item::new_from_element(Raster::new_cpu(halves)).with_attribute(core_types::ATTR_TRANSFORM, across_square)),
|
||
mode: MaskMode::Luminance,
|
||
density: 60.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
let shown = 0.4;
|
||
|
||
let Some(pixels) = render_square_over_backdrop(vec![glow, mask], 1., 1., BlendMode::Normal, Some(opaque(backdrop)), opaque(content), 30., 80., size) else {
|
||
return;
|
||
};
|
||
let close = |actual: [u8; 4], expected: [f32; 3]| actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 3.);
|
||
|
||
// Past the content, the faded glow screens the backdrop, which drawing it normally would leave 17 levels less blue
|
||
let screened: [f32; 3] = std::array::from_fn(|channel| backdrop[channel] + glow_color[channel] - backdrop[channel] * glow_color[channel]);
|
||
let glowing = mix_channels(backdrop, screened, strength * shown);
|
||
for (x, y) in [(27, 55), (82, 55), (55, 27)] {
|
||
let actual = pixel(&pixels, size, x, y);
|
||
assert!(close(actual, glowing), "the glow at ({x}, {y}): {actual:?} against {:?}", glowing.map(|channel| channel * 255.));
|
||
}
|
||
|
||
// The faded content shows the backdrop through it, rather than the glow it knocks out
|
||
let (faded, whole) = (pixel(&pixels, size, 40, 55), pixel(&pixels, size, 70, 55));
|
||
assert!(close(faded, mix_channels(backdrop, content, shown)), "the faded content: {faded:?}");
|
||
assert!(close(whole, content), "the content shown whole: {whole:?}");
|
||
}
|
||
|
||
/// A pixel's gamma-encoded channels each mixed from `from` to `to` by `amount`.
|
||
fn mix_channels(from: [f32; 3], to: [f32; 3], amount: f32) -> [f32; 3] {
|
||
std::array::from_fn(|channel| from[channel] + (to[channel] - from[channel]) * amount)
|
||
}
|
||
|
||
#[test]
|
||
fn interior_pieces_blend_within_the_contents_share_of_a_half_covered_pixel() {
|
||
use graphic_types::{Adjustment, EffectOperation};
|
||
use raster_kernels::layer_blending::blend_pixel;
|
||
|
||
let size = UVec2::new(64, 64);
|
||
let (backdrop, content, paint, strength) = ([0.2, 0.6, 0.9], [0.9, 0.5, 0.2], [0.3, 0.8, 0.4], 0.75);
|
||
let alpha = 128. / 255.;
|
||
let to_color = |[red, green, blue]: [f32; 3], alpha: f32| Color::from_rgba8((red * 255.).round() as u8, (green * 255.).round() as u8, (blue * 255.).round() as u8, (alpha * 255.).round() as u8);
|
||
|
||
// For PSD interop, the piece blends at full coverage onto the content mixed with the backdrop by the fill, and the content's alpha sets only its share, which the opacity then fades
|
||
let expected = |blend_mode, fill, opacity| {
|
||
let base = mix_channels(backdrop, content, fill);
|
||
let [red, green, blue, _] = blend_pixel(
|
||
paint.map(|channel| channel * strength).into_iter().chain([strength]).collect::<Vec<_>>().try_into().unwrap(),
|
||
[base[0], base[1], base[2], 1.],
|
||
blend_mode,
|
||
);
|
||
mix_channels(backdrop, mix_channels(backdrop, [red, green, blue], alpha), opacity)
|
||
};
|
||
|
||
// Exact at a full fill in any mode, and below it for a mode straight along the backdrop
|
||
let cases = [
|
||
(BlendMode::Multiply, 1., 1.),
|
||
(BlendMode::Screen, 1., 1.),
|
||
(BlendMode::Color, 1., 1.),
|
||
(BlendMode::ColorDodge, 1., 1.),
|
||
(BlendMode::Multiply, 1., 0.6),
|
||
(BlendMode::Multiply, 0.5, 1.),
|
||
(BlendMode::Screen, 0.5, 1.),
|
||
(BlendMode::HardLight, 0.5, 0.6),
|
||
];
|
||
for (blend_mode, fill, opacity) in cases {
|
||
let overlay = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||
color: core_types::Color::from_gamma_srgb_channels(paint[0], paint[1], paint[2], 1.),
|
||
blend_mode,
|
||
opacity: strength as f64 * 100.,
|
||
});
|
||
let Some(pixels) = render_square_over_backdrop(vec![overlay], fill, opacity, BlendMode::Normal, Some(to_color(backdrop, 1.)), to_color(content, alpha), 16., 48., size) else {
|
||
return;
|
||
};
|
||
|
||
let actual = pixel(&pixels, size, 32, 32);
|
||
let expected = expected(blend_mode, fill, opacity);
|
||
let close = actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 3.);
|
||
assert!(
|
||
close,
|
||
"{blend_mode:?} at fill {fill} and opacity {opacity}: {actual:?} against {:?}",
|
||
expected.map(|channel| channel * 255.)
|
||
);
|
||
}
|
||
}
|
||
|
||
/// A solid paint overlay of gamma-encoded `paint` at `strength`.
|
||
fn color_overlay(paint: [f32; 3], blend_mode: BlendMode, strength: f32) -> graphic_types::EffectOperation {
|
||
graphic_types::EffectOperation::Adjustment(graphic_types::Adjustment::ColorOverlay {
|
||
color: core_types::Color::from_gamma_srgb_channels(paint[0], paint[1], paint[2], 1.),
|
||
blend_mode,
|
||
opacity: strength as f64 * 100.,
|
||
})
|
||
}
|
||
|
||
/// An opaque color of gamma-encoded `channels`.
|
||
fn opaque(channels: [f32; 3]) -> Color {
|
||
let [red, green, blue] = channels.map(|channel| (channel * 255.).round() as u8);
|
||
Color::from_rgb8(red, green, blue)
|
||
}
|
||
|
||
/// For PSD interop, what fully covering content shows: its color mixed by the `fill` with what lies `beneath` it, with each of the `pieces` blending onto it in turn.
|
||
fn interior_over(beneath: [f32; 3], content: [f32; 3], fill: f32, pieces: &[(BlendMode, [f32; 3], f32)]) -> [f32; 3] {
|
||
use raster_kernels::layer_blending::blend_pixel;
|
||
|
||
pieces.iter().fold(mix_channels(beneath, content, fill), |base, &(blend_mode, paint, strength)| {
|
||
let paint = [paint[0] * strength, paint[1] * strength, paint[2] * strength, strength];
|
||
let [red, green, blue, _] = blend_pixel(paint, [base[0], base[1], base[2], 1.], blend_mode);
|
||
[red, green, blue]
|
||
})
|
||
}
|
||
|
||
#[test]
|
||
fn interior_pieces_after_one_over_the_content_stay_over_it() {
|
||
let size = UVec2::new(64, 64);
|
||
let (backdrop, content, light, dark) = ([0.2, 0.3, 0.9], [1., 0.5, 0.], [1., 1., 0.75], [0.1, 0.6, 0.3]);
|
||
|
||
// Across a fully covered pixel at half fill, a piece in a mode that bends stays beneath the pieces after it
|
||
for (first, second) in [
|
||
(BlendMode::Overlay, BlendMode::Normal),
|
||
(BlendMode::Difference, BlendMode::Normal),
|
||
(BlendMode::Overlay, BlendMode::Multiply),
|
||
(BlendMode::Lighten, BlendMode::Normal),
|
||
] {
|
||
let effects = vec![color_overlay(light, first, 0.75), color_overlay(dark, second, 0.75)];
|
||
let Some(pixels) = render_square_over_backdrop(effects, 0.5, 1., BlendMode::Normal, Some(opaque(backdrop)), opaque(content), 16., 48., size) else {
|
||
return;
|
||
};
|
||
|
||
let expected = interior_over(backdrop, content, 0.5, &[(first, light, 0.75), (second, dark, 0.75)]);
|
||
let actual = pixel(&pixels, size, 32, 32);
|
||
let close = actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 3.);
|
||
assert!(close, "{first:?} then {second:?}: {actual:?} against {:?}", expected.map(|channel| channel * 255.));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn the_part_through_the_fill_shows_over_what_lies_beneath_the_content_in_its_layer() {
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
|
||
let size = UVec2::new(64, 64);
|
||
let (backdrop, content, glow) = ([0.2, 0.3, 0.9], [1., 0.5, 0.], [1., 1., 0.75]);
|
||
let background_blur = EffectOperation::BackgroundBlur {
|
||
radius: 4.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let mut shadow = drop_shadow(core_types::Color::BLACK.with_alpha(0.75), DVec2::ZERO, 0., 0.);
|
||
if let EffectOperation::DropShadow { knockout, .. } = &mut shadow {
|
||
*knockout = false;
|
||
}
|
||
|
||
// Glass at 30% fill over the blurred backdrop (uniform here), and content over a shadow it doesn't knock out, each with a screen glow over the content
|
||
for (beneath, shown_beneath) in [(background_blur, backdrop), (shadow, mix_channels(backdrop, [0.; 3], 0.75))] {
|
||
let effects = vec![beneath.clone(), color_overlay(glow, BlendMode::Screen, 0.75)];
|
||
let Some(pixels) = render_square_over_backdrop(effects, 0.3, 1., BlendMode::Normal, Some(opaque(backdrop)), opaque(content), 16., 48., size) else {
|
||
return;
|
||
};
|
||
|
||
let expected = interior_over(shown_beneath, content, 0.3, &[(BlendMode::Screen, glow, 0.75)]);
|
||
let actual = pixel(&pixels, size, 32, 32);
|
||
let close = actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 3.);
|
||
assert!(close, "over {beneath:?}: {actual:?} against {:?}", expected.map(|channel| channel * 255.));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_knocked_out_shadow_shows_only_outside_the_contents_share_beneath_an_interior_piece() {
|
||
use glam::DVec2;
|
||
use graphic_types::{Adjustment, EffectOperation};
|
||
|
||
// Half-transparent content at no fill, painted black within its share, over a red shadow cast right beneath it
|
||
let size = UVec2::new(64, 64);
|
||
let black_overlay = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||
color: core_types::Color::BLACK,
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
});
|
||
let shadow = drop_shadow(core_types::Color::RED, DVec2::ZERO, 0., 0.);
|
||
let content = Color::from_rgba8(255, 255, 255, 128);
|
||
let Some(pixels) = render_square_over_backdrop(vec![shadow, black_overlay], 0., 1., BlendMode::Normal, Some(Color::from_rgb8(0, 0, 255)), content, 16., 48., size) else {
|
||
return;
|
||
};
|
||
|
||
// The shadow cast at half strength shows only in the half of the pixel the content leaves, under the black within the other half
|
||
let alpha = 128. / 255.;
|
||
let outside = mix_channels([0., 0., 1.], [1., 0., 0.], alpha);
|
||
let expected = mix_channels(outside, [0., 0., 0.], alpha);
|
||
let actual = pixel(&pixels, size, 32, 32);
|
||
assert!(
|
||
actual.iter().zip(expected).all(|(&actual, expected)| (actual as f32 - expected * 255.).abs() <= 3.),
|
||
"{actual:?} against {expected:?}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn nested_effects_groups_render_inside_out() {
|
||
use core_types::Color as GraphicColor;
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = Rect::new(30., 30., 80., 80.);
|
||
|
||
// A hard shadow around a group with content that is itself a blurred square
|
||
let shadow = Effects::from_operations([drop_shadow(GraphicColor::BLACK, DVec2::new(20., 0.), 0., 0.)]);
|
||
let blur = Effects::from_operations([EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 3.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
}]);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.draw_effects(
|
||
&shadow,
|
||
1.,
|
||
1.,
|
||
BlendMode::Normal,
|
||
true,
|
||
Some(square.inflate(12., 12.)),
|
||
DAffine2::IDENTITY,
|
||
None,
|
||
&mut |_, _| {},
|
||
&mut |scene| {
|
||
scene.draw_effects(&blur, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||
});
|
||
},
|
||
);
|
||
};
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
let edge = pixel(&pixels, size, 30, 55);
|
||
assert!((100..=155).contains(&edge[3]), "the blur softens the edge to half coverage, not {edge:?}");
|
||
// Ten pixels past the content's blurred edge, where the shadow is cast from ten pixels inside it
|
||
let shadow = pixel(&pixels, size, 90, 55);
|
||
assert!(shadow[3] >= 250 && shadow[0] <= 5, "the shadow is cast by the blurred group, not {shadow:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn captured_coverages_the_effects_never_reach_cover_nothing() {
|
||
use graphic_types::effects::EffectCapture;
|
||
use graphic_types::{EffectKind, EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(64, 64);
|
||
let square = Rect::new(20., 20., 40., 40.);
|
||
|
||
// The default outline lies outside the edge, so it has no band inside for its second plane to capture
|
||
let outline = Effects::from_operations([EffectOperation::default_for(EffectKind::Outline)]);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.capture_next_effects(EffectCapture { index: 0, plane: 1 });
|
||
scene.draw_effects(&outline, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||
});
|
||
};
|
||
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
assert!(pixels.iter().all(|pixel| pixel[3] == 0), "the capture holds the finished image instead of nothing");
|
||
}
|
||
|
||
#[test]
|
||
fn captured_box_blurs_hold_their_results_for_svg_however_slight() {
|
||
use graphic_types::effects::EffectCapture;
|
||
use graphic_types::{EffectOperation, Effects, Graphic};
|
||
use rendering::Render;
|
||
|
||
let size = UVec2::new(64, 64);
|
||
let square = Rect::new(20., 20., 40., 40.);
|
||
let white = Graphic::from(core_types::Color::WHITE);
|
||
let mut draw_map = |_: usize, scene: &mut VelloSceneBuilder| white.render_to_vello(scene, DAffine2::IDENTITY, &rendering::RenderParams::default().for_pattern());
|
||
let mut render_through = |operation: EffectOperation, capture: Option<EffectCapture>| {
|
||
let effects = Effects::from_operations([operation]);
|
||
render(size, |scene| {
|
||
if let Some(capture) = capture {
|
||
scene.capture_next_effects(capture);
|
||
}
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut draw_map, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||
});
|
||
})
|
||
};
|
||
|
||
// The map SVG takes in place of a box blur, plain or with a radius mask, is the blurred content itself
|
||
let masked = |radius| EffectOperation::Blur {
|
||
radius_mask: white.clone(),
|
||
radius,
|
||
box_blur: true,
|
||
gamma: false,
|
||
};
|
||
for operation in [
|
||
EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 3.5,
|
||
box_blur: true,
|
||
gamma: false,
|
||
},
|
||
masked(3.5),
|
||
] {
|
||
let Some(shown) = render_through(operation.clone(), None) else { return };
|
||
let Some(captured) = render_through(operation.clone(), Some(EffectCapture { index: 0, plane: 0 })) else {
|
||
return;
|
||
};
|
||
assert!(shown.iter().any(|pixel| (1..255).contains(&pixel[3])), "{operation:?} blurs nothing");
|
||
for (shown, captured) in shown.iter().zip(&captured) {
|
||
assert!(
|
||
shown.iter().zip(captured).all(|(shown, captured)| shown.abs_diff(*captured) <= 1),
|
||
"{operation:?} captures {captured:?} where it shows {shown:?}"
|
||
);
|
||
}
|
||
}
|
||
|
||
// A blur too slight to run at this scale, plain or with a radius mask, still captures the content, rather than nothing
|
||
let slight = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 0.005,
|
||
box_blur: true,
|
||
gamma: false,
|
||
};
|
||
for operation in [slight, masked(0.005)] {
|
||
let Some(captured) = render_through(operation.clone(), Some(EffectCapture { index: 0, plane: 0 })) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&captured, size, 30, 30)[3], 255, "{operation:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::blending::BlendMode;
|
||
use core_types::list::ATTR_GRADIENT_FORM;
|
||
use core_types::list::Item;
|
||
use core_types::transfer_curve::TransferCurve;
|
||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientForm, GradientStop};
|
||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||
use graphic_types::{BevelDirection, BevelStyle, BevelTechnique, Effect, EffectOperation, GlowSource, GlowTechnique, Graphic, MaskMode, NoiseDistribution, stamp_effect};
|
||
use raster_kernels::evaluate_raster_effects;
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let (min, max) = (50, 100);
|
||
let shadow_color = GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75);
|
||
let blur = |radius, box_blur, gamma| EffectOperation::Blur {
|
||
radius_mask: Graphic::default(),
|
||
radius,
|
||
box_blur,
|
||
gamma,
|
||
};
|
||
let bevel = |style, technique, direction, size, soften| EffectOperation::BevelAndEmboss {
|
||
style,
|
||
technique,
|
||
depth: 150.,
|
||
direction,
|
||
size,
|
||
soften,
|
||
angle: 120.,
|
||
altitude: 30.,
|
||
highlight_color: GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 0.75),
|
||
highlight_blend_mode: BlendMode::Screen,
|
||
shadow_color,
|
||
shadow_blend_mode: BlendMode::Multiply,
|
||
gloss_contour: TransferCurve::default(),
|
||
gloss_antialiased: false,
|
||
slope_contour: TransferCurve::default(),
|
||
slope_antialiased: false,
|
||
slope_range: 100.,
|
||
texture: Graphic::default(),
|
||
texture_depth: 100.,
|
||
};
|
||
// A bevel with its gloss contour, slope contour and its range, and texture and its depth
|
||
let with_options = |bevel: EffectOperation, options: (TransferCurve, TransferCurve, f64, Graphic, f64)| {
|
||
let mut bevel = bevel;
|
||
if let EffectOperation::BevelAndEmboss {
|
||
gloss_contour,
|
||
slope_contour,
|
||
slope_range,
|
||
texture,
|
||
texture_depth,
|
||
..
|
||
} = &mut bevel
|
||
{
|
||
(*gloss_contour, *slope_contour, *slope_range, *texture, *texture_depth) = options;
|
||
}
|
||
bevel
|
||
};
|
||
let antialiased = |bevel: EffectOperation| {
|
||
let mut bevel = bevel;
|
||
if let EffectOperation::BevelAndEmboss {
|
||
gloss_antialiased, slope_antialiased, ..
|
||
} = &mut bevel
|
||
{
|
||
(*gloss_antialiased, *slope_antialiased) = (true, true);
|
||
}
|
||
bevel
|
||
};
|
||
let identity = LevelsRecord {
|
||
shadows: 0.,
|
||
midtones: 1.,
|
||
highlights: 100.,
|
||
output_minimums: 0.,
|
||
output_maximums: 100.,
|
||
};
|
||
|
||
let gradient_glow = |color, technique, spread, size, range, contour| EffectOperation::OuterGlow {
|
||
color,
|
||
blend_mode: BlendMode::Screen,
|
||
technique,
|
||
spread,
|
||
size,
|
||
range,
|
||
contour,
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
};
|
||
let glow = |technique, spread, size, range, contour| gradient_glow(shadow_color.into(), technique, spread, size, range, contour);
|
||
let stop = |position, color| GradientStop { position, midpoint: 0.5, color };
|
||
// A glow roughened by `noise` and, for a gradient, scattered along it by `jitter`
|
||
let grained = |glow: EffectOperation, noise_amount: f64, jitter_amount: f64| {
|
||
let mut glow = glow;
|
||
if let EffectOperation::OuterGlow { noise, jitter, .. } | EffectOperation::InnerGlow { noise, jitter, .. } = &mut glow {
|
||
(*noise, *jitter) = (noise_amount, jitter_amount);
|
||
}
|
||
glow
|
||
};
|
||
let fading = Graphic::from(Gradient::new([
|
||
stop(0., GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 1.)),
|
||
stop(0.4, GraphicColor::from_rgbaf32_unchecked(0.9, 0.2, 0.1, 0.8)),
|
||
stop(1., GraphicColor::from_rgbaf32_unchecked(0.2, 0., 0.6, 0.)),
|
||
]));
|
||
let inner_gradient = Graphic::from(Gradient::new([
|
||
stop(0., GraphicColor::from_rgbaf32_unchecked(0.9, 0.9, 0.2, 0.9)),
|
||
stop(1., GraphicColor::from_rgbaf32_unchecked(0.1, 0.5, 0.9, 0.3)),
|
||
]));
|
||
let opaque = Graphic::from(Gradient::new([
|
||
stop(0., GraphicColor::from_rgbaf32_unchecked(0.1, 0.8, 0.3, 1.)),
|
||
stop(1., GraphicColor::from_rgbaf32_unchecked(0.2, 0.1, 0.9, 1.)),
|
||
]));
|
||
let bow = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.25, 0.75), DVec2::ONE]);
|
||
let outline_by = |blend_mode, paint, weight, align, contour_gradient| EffectOperation::Outline {
|
||
paint,
|
||
blend_mode,
|
||
weight,
|
||
align,
|
||
contour_gradient,
|
||
};
|
||
let outline = |paint, weight, align, contour_gradient| outline_by(BlendMode::Normal, paint, weight, align, contour_gradient);
|
||
let hard_stop = Graphic::from(Gradient::new([
|
||
stop(0., GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.9, 1.)),
|
||
stop(0.5, GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.9, 1.)),
|
||
stop(0.5, GraphicColor::from_rgbaf32_unchecked(1., 0.8, 0.1, 1.)),
|
||
stop(1., GraphicColor::from_rgbaf32_unchecked(1., 0.8, 0.1, 1.)),
|
||
]));
|
||
|
||
let cases = [
|
||
vec![blur(3., false, false)],
|
||
vec![blur(20., false, true)],
|
||
vec![blur(5.5, true, false)],
|
||
vec![drop_shadow(shadow_color, DVec2::new(6.5, -3.), 8., 25.)],
|
||
vec![drop_shadow(shadow_color, DVec2::new(2., 3.), 40., 0.)],
|
||
vec![EffectOperation::InnerShadow {
|
||
color: shadow_color,
|
||
blend_mode: BlendMode::Multiply,
|
||
angle: 135.,
|
||
distance: 5.,
|
||
choke: 50.,
|
||
size: 6.,
|
||
contour: TransferCurve::default(),
|
||
}],
|
||
vec![glow(GlowTechnique::Softer, 30., 9., 50., TransferCurve::default()), blur(2., false, false)],
|
||
vec![glow(GlowTechnique::Precise, 0., 12., 75., bow.clone())],
|
||
vec![glow(GlowTechnique::Precise, 50., 16., 100., TransferCurve::default())],
|
||
vec![glow(GlowTechnique::Precise, 80., 10., 100., TransferCurve::default())],
|
||
// Grain fixed to the content roughens a glow's opacity, and scatters a gradient glow's colors along it
|
||
vec![grained(glow(GlowTechnique::Precise, 100., 12., 100., TransferCurve::default()), 60., 0.)],
|
||
vec![grained(glow(GlowTechnique::Softer, 0., 10., 50., TransferCurve::default()), 100., 0.)],
|
||
vec![grained(gradient_glow(fading.clone(), GlowTechnique::Precise, 0., 14., 75., TransferCurve::default()), 40., 50.)],
|
||
vec![grained(
|
||
EffectOperation::InnerGlow {
|
||
color: shadow_color.into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
source: GlowSource::Edge,
|
||
choke: 0.,
|
||
size: 12.,
|
||
range: 100.,
|
||
contour: TransferCurve::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
},
|
||
50.,
|
||
0.,
|
||
)],
|
||
vec![grained(
|
||
EffectOperation::InnerGlow {
|
||
color: inner_gradient.clone(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Softer,
|
||
source: GlowSource::Edge,
|
||
choke: 0.,
|
||
size: 12.,
|
||
range: 100.,
|
||
contour: TransferCurve::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
},
|
||
30.,
|
||
60.,
|
||
)],
|
||
// Jitter alone, and noisy inner glows reshaped by a range and a contour, from the edges and the center, with other seeds
|
||
vec![grained(gradient_glow(opaque.clone(), GlowTechnique::Softer, 20., 12., 100., TransferCurve::default()), 0., 80.)],
|
||
vec![EffectOperation::InnerGlow {
|
||
color: shadow_color.into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
source: GlowSource::Edge,
|
||
choke: 10.,
|
||
size: 12.,
|
||
range: 50.,
|
||
contour: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.25, 0.75), DVec2::ONE]),
|
||
noise: 70.,
|
||
jitter: 0.,
|
||
seed: 3,
|
||
}],
|
||
vec![EffectOperation::InnerGlow {
|
||
color: shadow_color.into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
source: GlowSource::Center,
|
||
choke: 10.,
|
||
size: 12.,
|
||
range: 60.,
|
||
contour: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.25, 0.75), DVec2::ONE]),
|
||
noise: 50.,
|
||
jitter: 0.,
|
||
seed: 5,
|
||
}],
|
||
vec![glow(GlowTechnique::Softer, 0., 6., 50., bow.clone())],
|
||
vec![gradient_glow(fading.clone(), GlowTechnique::Precise, 0., 14., 75., TransferCurve::default())],
|
||
vec![gradient_glow(opaque.clone(), GlowTechnique::Softer, 25., 12., 50., bow.clone())],
|
||
vec![EffectOperation::InnerGlow {
|
||
color: shadow_color.into(),
|
||
blend_mode: BlendMode::Overlay,
|
||
technique: GlowTechnique::Softer,
|
||
source: GlowSource::Edge,
|
||
choke: 25.,
|
||
size: 7.,
|
||
range: 50.,
|
||
contour: TransferCurve::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
}],
|
||
vec![EffectOperation::InnerGlow {
|
||
color: shadow_color.into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
source: GlowSource::Center,
|
||
choke: 0.,
|
||
size: 10.,
|
||
range: 75.,
|
||
contour: TransferCurve::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
}],
|
||
vec![EffectOperation::Satin {
|
||
color: shadow_color,
|
||
blend_mode: BlendMode::Multiply,
|
||
angle: 25.,
|
||
distance: 7.,
|
||
size: 6.,
|
||
invert: true,
|
||
contour: TransferCurve::default(),
|
||
}],
|
||
vec![EffectOperation::Satin {
|
||
color: shadow_color,
|
||
blend_mode: BlendMode::Hue,
|
||
angle: -110.,
|
||
distance: 9.,
|
||
size: 3.,
|
||
invert: false,
|
||
contour: bow,
|
||
}],
|
||
// Softened casts each reshaped by an arch before they're compared, then inverted
|
||
vec![EffectOperation::Satin {
|
||
color: shadow_color,
|
||
blend_mode: BlendMode::Normal,
|
||
angle: 60.,
|
||
distance: 5.,
|
||
size: 8.,
|
||
invert: true,
|
||
contour: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.5, 1.), DVec2::X]),
|
||
}],
|
||
vec![outline(shadow_color.into(), 6., StrokeAlign::Outside, false)],
|
||
vec![outline_by(BlendMode::Difference, shadow_color.into(), 5., StrokeAlign::Inside, false)],
|
||
vec![outline(shadow_color.into(), 9., StrokeAlign::Center, false)],
|
||
// Contour gradients run across the outline, whatever its alignment
|
||
vec![outline(fading.clone(), 10., StrokeAlign::Center, true)],
|
||
vec![outline(fading.clone(), 7., StrokeAlign::Inside, true)],
|
||
vec![outline(opaque.clone(), 12., StrokeAlign::Outside, true)],
|
||
// A hard stop at the middle of an odd outline lands right on its middle ring
|
||
vec![outline(hard_stop, 3., StrokeAlign::Outside, true)],
|
||
vec![EffectOperation::InnerGlow {
|
||
color: inner_gradient,
|
||
blend_mode: BlendMode::SoftLight,
|
||
technique: GlowTechnique::Precise,
|
||
source: GlowSource::Center,
|
||
choke: 20.,
|
||
size: 9.,
|
||
range: 50.,
|
||
contour: TransferCurve::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
}],
|
||
vec![bevel(BevelStyle::InnerBevel, BevelTechnique::Smooth, BevelDirection::Up, 8., 0.)],
|
||
vec![bevel(BevelStyle::OuterBevel, BevelTechnique::ChiselHard, BevelDirection::Down, 6., 2.)],
|
||
vec![bevel(BevelStyle::Emboss, BevelTechnique::ChiselSoft, BevelDirection::Up, 10., 0.)],
|
||
vec![bevel(BevelStyle::PillowEmboss, BevelTechnique::Smooth, BevelDirection::Up, 12., 1.)],
|
||
// Bends alpha, so the fill must fade the content before it on both
|
||
vec![EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite: identity,
|
||
red: identity,
|
||
green: identity,
|
||
blue: identity,
|
||
alpha: LevelsRecord { midtones: 2.2, ..identity },
|
||
})))],
|
||
];
|
||
|
||
// Paint overlays over a colored backdrop
|
||
let backdrop = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||
color: GraphicColor::from_rgbaf32_unchecked(0.3, 0.6, 0.2, 1.),
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
});
|
||
let gradient = |form: GradientForm, transform: DAffine2| {
|
||
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
|
||
position,
|
||
midpoint: 0.5,
|
||
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
|
||
});
|
||
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
|
||
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
|
||
};
|
||
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
|
||
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
|
||
|
||
// A checkerboard spanning the render from `start` to `end` with a pixel for each of the render's, so sampling it needs no interpolation
|
||
let checkerboard = |start: u32, end: u32| {
|
||
let side = end - start;
|
||
let checker = Image {
|
||
width: side,
|
||
height: side,
|
||
data: (0..side * side)
|
||
.map(|index| match (index % side / 5 + index / side / 5) % 2 {
|
||
0 => GraphicColor::RED,
|
||
_ => GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 0.5),
|
||
})
|
||
.collect(),
|
||
};
|
||
let placement = DAffine2::from_translation(DVec2::splat(start as f64)) * DAffine2::from_scale(DVec2::splat(side as f64));
|
||
Graphic::from(Item::new_from_element(Raster::new_cpu(checker)).with_attribute(ATTR_TRANSFORM, placement))
|
||
};
|
||
let checker = checkerboard(min, max);
|
||
|
||
let overlay = |paint: &Graphic, blend_mode, opacity| {
|
||
vec![
|
||
backdrop.clone(),
|
||
EffectOperation::PaintOverlay {
|
||
paint: paint.clone(),
|
||
blend_mode,
|
||
opacity,
|
||
},
|
||
]
|
||
};
|
||
// Hard Mix's threshold and the hue of the gradient's grays turn the slightest rounding into large differences, so they take the checkerboard's exact colors instead
|
||
let ill_conditioned = [BlendMode::HardMix, BlendMode::Hue];
|
||
let mut paint_cases: Vec<_> = (BlendMode::list().into_iter().flatten())
|
||
.filter(|blend_mode| !ill_conditioned.contains(blend_mode))
|
||
.map(|&blend_mode| overlay(&linear, blend_mode, 100.))
|
||
.collect();
|
||
paint_cases.extend(ill_conditioned.map(|blend_mode| overlay(&checker, blend_mode, 100.)));
|
||
paint_cases.extend([
|
||
overlay(&linear, BlendMode::Normal, 40.),
|
||
overlay(&radial, BlendMode::Multiply, 100.),
|
||
overlay(&checker, BlendMode::Screen, 100.),
|
||
]);
|
||
// Outlines drawn with paints placed on their own, the image covering the outline as well as the content
|
||
paint_cases.extend([
|
||
vec![outline(linear.clone(), 6., StrokeAlign::Outside, false)],
|
||
vec![outline(radial.clone(), 8., StrokeAlign::Center, false)],
|
||
vec![outline(checkerboard(min - 10, max + 10), 9., StrokeAlign::Center, false)],
|
||
]);
|
||
// Bevels with gloss contours, contours, and textures
|
||
let cone = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.5, 1.), DVec2::X]);
|
||
let sag = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.5, 0.25), DVec2::ONE]);
|
||
let straight = TransferCurve::default;
|
||
paint_cases.extend([
|
||
vec![with_options(
|
||
bevel(BevelStyle::InnerBevel, BevelTechnique::ChiselHard, BevelDirection::Up, 10., 0.),
|
||
(cone.clone(), straight(), 100., Graphic::default(), 100.),
|
||
)],
|
||
vec![with_options(
|
||
bevel(BevelStyle::InnerBevel, BevelTechnique::Smooth, BevelDirection::Up, 10., 0.),
|
||
(straight(), cone.clone(), 50., Graphic::default(), 100.),
|
||
)],
|
||
vec![antialiased(with_options(
|
||
bevel(BevelStyle::InnerBevel, BevelTechnique::ChiselHard, BevelDirection::Up, 12., 0.),
|
||
(cone.clone(), cone.clone(), 50., Graphic::default(), 100.),
|
||
))],
|
||
vec![with_options(
|
||
bevel(BevelStyle::Emboss, BevelTechnique::ChiselSoft, BevelDirection::Down, 12., 1.),
|
||
(sag.clone(), sag, 100., Graphic::default(), 100.),
|
||
)],
|
||
vec![with_options(
|
||
bevel(BevelStyle::OuterBevel, BevelTechnique::ChiselHard, BevelDirection::Up, 8., 0.),
|
||
(straight(), cone, 50., Graphic::default(), 100.),
|
||
)],
|
||
vec![with_options(
|
||
bevel(BevelStyle::InnerBevel, BevelTechnique::Smooth, BevelDirection::Up, 6., 0.),
|
||
(straight(), straight(), 100., checker.clone(), 150.),
|
||
)],
|
||
vec![with_options(
|
||
bevel(BevelStyle::PillowEmboss, BevelTechnique::ChiselHard, BevelDirection::Up, 10., 0.),
|
||
(straight(), straight(), 100., radial.clone(), -100.),
|
||
)],
|
||
// A texture reaching past the content, with the shading beneath the content fading out across the slopes' foot
|
||
vec![with_options(
|
||
bevel(BevelStyle::OuterBevel, BevelTechnique::Smooth, BevelDirection::Up, 10., 0.),
|
||
(straight(), straight(), 100., linear.clone(), 100.),
|
||
)],
|
||
// A wide straight contour across a quarter of the slope
|
||
vec![with_options(
|
||
bevel(BevelStyle::InnerBevel, BevelTechnique::ChiselHard, BevelDirection::Up, 20., 0.),
|
||
(straight(), straight(), 25., Graphic::default(), 100.),
|
||
)],
|
||
]);
|
||
|
||
// Masks by an image with a pixel for each of the square's, with varying grays and alphas, and by gradients, before and after a shadow
|
||
let square_placement = DAffine2::from_translation(DVec2::splat(min as f64)) * DAffine2::from_scale(DVec2::splat((max - min) as f64));
|
||
let mask_image = Image {
|
||
width: 50,
|
||
height: 50,
|
||
data: (0..2500)
|
||
.map(|index| {
|
||
let (x, y) = ((index % 50) as f32 / 49., (index / 50) as f32);
|
||
GraphicColor::from_gamma_srgb_channels(x, 0.5 * x, 1. - x, if y < 25. { 1. } else { 0.6 })
|
||
})
|
||
.collect(),
|
||
};
|
||
let mask_image = Graphic::from(Item::new_from_element(Raster::new_cpu(mask_image)).with_attribute(ATTR_TRANSFORM, square_placement));
|
||
|
||
// A 5 by 5 image of black and white stretched over the square, so sampling it interpolates between its pixels
|
||
let resampled = Image {
|
||
width: 5,
|
||
height: 5,
|
||
data: (0..25).map(|index| if (index % 5 + index / 5) % 2 == 0 { GraphicColor::BLACK } else { GraphicColor::WHITE }).collect(),
|
||
};
|
||
let resampled = Graphic::from(Item::new_from_element(Raster::new_cpu(resampled)).with_attribute(ATTR_TRANSFORM, square_placement));
|
||
|
||
// Opaque checks of black and white with a pixel for each of the square's
|
||
let checks = Image {
|
||
width: 50,
|
||
height: 50,
|
||
data: (0..2500)
|
||
.map(|index| if (index % 50 / 5 + index / 250) % 2 == 0 { GraphicColor::BLACK } else { GraphicColor::WHITE })
|
||
.collect(),
|
||
};
|
||
let checks = Graphic::from(Item::new_from_element(Raster::new_cpu(checks)).with_attribute(ATTR_TRANSFORM, square_placement));
|
||
|
||
let mask = |mask: &Graphic, mode, density, feather, invert| EffectOperation::Mask {
|
||
mask: mask.clone(),
|
||
mode,
|
||
density,
|
||
feather,
|
||
invert,
|
||
};
|
||
let mask_shadow = drop_shadow(shadow_color, DVec2::new(6.5, -3.), 8., 25.);
|
||
let screen_glow = || glow(GlowTechnique::Softer, 30., 9., 50., TransferCurve::default());
|
||
let interior_glow = |blend_mode| EffectOperation::InnerGlow {
|
||
color: shadow_color.into(),
|
||
blend_mode,
|
||
technique: GlowTechnique::Softer,
|
||
source: GlowSource::Edge,
|
||
choke: 25.,
|
||
size: 7.,
|
||
range: 50.,
|
||
contour: TransferCurve::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
};
|
||
let masked_radius_blur = |radius_mask: &Graphic, radius, box_blur, gamma| EffectOperation::Blur {
|
||
radius_mask: radius_mask.clone(),
|
||
radius,
|
||
box_blur,
|
||
gamma,
|
||
};
|
||
let painted = |paint: &Graphic| EffectOperation::PaintOverlay {
|
||
paint: paint.clone(),
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
};
|
||
let make_opaque = |strength| EffectOperation::Adjustment(Adjustment::MakeOpaque { strength });
|
||
let mask_cases = [
|
||
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false)],
|
||
vec![mask(&mask_image, MaskMode::LuminanceSvg, 100., 0., false)],
|
||
vec![mask(&linear, MaskMode::LuminanceSvg, 80., 3., true)],
|
||
vec![mask(&mask_image, MaskMode::Alpha, 70., 3., true)],
|
||
vec![mask(&linear, MaskMode::Luminance, 100., 6., false)],
|
||
vec![mask(&radial, MaskMode::Alpha, 100., 0., false)],
|
||
vec![mask(&mask_image, MaskMode::Luminance, 100., 2., false), mask_shadow.clone()],
|
||
vec![mask_shadow.clone(), mask(&linear, MaskMode::Luminance, 80., 0., true)],
|
||
vec![blur(2., false, false), mask(&radial, MaskMode::Luminance, 100., 1.5, false), mask_shadow.clone()],
|
||
vec![mask(&mask_image, MaskMode::Luminance, 60., 0., false), mask(&linear, MaskMode::Alpha, 100., 2., true)],
|
||
vec![mask(&resampled, MaskMode::Luminance, 100., 0., false)],
|
||
// Trailing masks fade layers that keep their modes: glows screening beneath the content, and interior pieces blending through its fill
|
||
vec![screen_glow(), mask(&linear, MaskMode::Luminance, 60., 2., false)],
|
||
vec![
|
||
mask_shadow.clone(),
|
||
screen_glow(),
|
||
mask(&mask_image, MaskMode::Alpha, 70., 3., true),
|
||
mask(&radial, MaskMode::Luminance, 50., 0., false),
|
||
],
|
||
vec![interior_glow(BlendMode::Multiply), mask(&radial, MaskMode::Luminance, 100., 1.5, false)],
|
||
vec![interior_glow(BlendMode::Overlay), mask(&linear, MaskMode::Alpha, 80., 0., true)],
|
||
vec![EffectOperation::Feather { distance: 3. }],
|
||
vec![EffectOperation::Feather { distance: 14. }],
|
||
vec![mask_shadow.clone(), EffectOperation::Feather { distance: 8. }],
|
||
vec![EffectOperation::Feather { distance: 6. }, blur(2., false, false)],
|
||
// Masks first give the feather curved, translucent, and holed outlines
|
||
vec![mask(&radial, MaskMode::Alpha, 100., 0., false), EffectOperation::Feather { distance: 6. }],
|
||
vec![mask(&radial, MaskMode::Luminance, 100., 0., true), EffectOperation::Feather { distance: 5. }],
|
||
vec![masked_radius_blur(&linear, 10., false, false)],
|
||
vec![masked_radius_blur(&mask_image, 6., false, true)],
|
||
vec![masked_radius_blur(&radial, 16., false, false), blur(1., false, false)],
|
||
vec![masked_radius_blur(&linear, 40., false, false)],
|
||
vec![masked_radius_blur(&linear, 10., true, false)],
|
||
vec![masked_radius_blur(&radial, 24., true, true)],
|
||
// Hard edges between colors and alphas, which the levels interpolate across in their power space unless in gamma
|
||
vec![
|
||
painted(&checks),
|
||
masked_radius_blur(&Graphic::from(GraphicColor::from_gamma_srgb_channels(0.4, 0.4, 0.4, 1.)), 12., false, false),
|
||
],
|
||
vec![painted(&checks), masked_radius_blur(&radial, 20., false, false)],
|
||
vec![painted(&checks), masked_radius_blur(&linear, 12., false, true)],
|
||
vec![painted(&checker), masked_radius_blur(&linear, 12., false, false)],
|
||
vec![painted(&checker), masked_radius_blur(&mask_image, 8., true, false)],
|
||
// Boxes of each pixel's own fractional width across hard edges, in gamma
|
||
vec![painted(&checks), masked_radius_blur(&resampled, 15.5, true, true)],
|
||
// Masked content's translucent alpha lifted toward opaque by each strength, with the empty space around it left empty
|
||
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false), make_opaque(0.)],
|
||
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false), make_opaque(50.)],
|
||
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false), make_opaque(100.)],
|
||
// No strength still carries out the adjustments after it
|
||
vec![
|
||
mask(&mask_image, MaskMode::Luminance, 100., 0., false),
|
||
make_opaque(0.),
|
||
EffectOperation::Adjustment(Adjustment::Invert),
|
||
],
|
||
];
|
||
|
||
// Content in a color of its own, so every mode has colors to blend
|
||
let content = [217, 140, 89];
|
||
let gpu_content = Color::from_rgb8(content[0], content[1], content[2]);
|
||
let [red, green, blue] = content.map(|channel| channel as f32 / 255.);
|
||
let cpu_content = GraphicColor::from_gamma_srgb_channels(red, green, blue, 1.);
|
||
|
||
// Filters of the checkerboard's colors, whose sharp edges the kernels pick out
|
||
let checkered = |filter: EffectOperation| [overlay(&checker, BlendMode::Normal, 100.), vec![filter]].concat();
|
||
// Kernels of rows as wide as they are tall, unless their width is given
|
||
let kernel_of_width = |kernel: Vec<f64>, columns: usize, scale, offset| EffectOperation::ConvolutionKernel {
|
||
kernel: kernel.into_iter().map(Item::new_from_element).collect(),
|
||
columns: columns as u32,
|
||
scale,
|
||
offset,
|
||
apply_to_alpha: false,
|
||
};
|
||
let convolution_kernel = |kernel: Vec<f64>, scale, offset| kernel_of_width(kernel.clone(), kernel.len().isqrt(), scale, offset);
|
||
let applied_to_alpha = |kernel: Vec<f64>, scale| EffectOperation::ConvolutionKernel {
|
||
columns: kernel.len().isqrt() as u32,
|
||
kernel: kernel.into_iter().map(Item::new_from_element).collect(),
|
||
scale,
|
||
offset: 0.,
|
||
apply_to_alpha: true,
|
||
};
|
||
let sharpen_kernel = vec![0., -1., 0., -1., 8., -1., 0., -1., 0.];
|
||
let sparse = (0..81).map(|index| [(0, 2.), (40, 4.), (44, -1.), (80, 1.)].into_iter().find(|&(at, _)| at == index).map_or(0., |(_, weight)| weight));
|
||
paint_cases.extend([
|
||
checkered(convolution_kernel(vec![1.; 9], 9., 0.)),
|
||
checkered(convolution_kernel(vec![0., -1., 0., -1., 5., -1., 0., -1., 0.], 1., 0.)),
|
||
checkered(convolution_kernel([vec![0.; 10], vec![-1., -1., 1., 1., 1.], vec![0.; 10]].concat(), 2., 128.)),
|
||
checkered(convolution_kernel(sparse.collect(), 6., 20.)),
|
||
checkered(convolution_kernel(vec![1.; 49], 40., -10.)),
|
||
// Large sums of large weights, which must stay precise through the whole sum
|
||
checkered(convolution_kernel((0..81).map(|index| if index == 40 { 81. } else { -1. }).collect(), 1., 0.)),
|
||
checkered(convolution_kernel(
|
||
(0..49)
|
||
.map(|index| {
|
||
if index == 24 {
|
||
500.
|
||
} else if index % 7 == 0 {
|
||
-40.
|
||
} else {
|
||
0.
|
||
}
|
||
})
|
||
.collect(),
|
||
220.,
|
||
0.,
|
||
)),
|
||
// More taps than one pass holds, carried over between passes, and colors continued from farther than one pass of shifts reaches
|
||
checkered(convolution_kernel(
|
||
(0..121)
|
||
.map(|index| {
|
||
if index == 60 {
|
||
61.
|
||
} else if index % 2 == 0 {
|
||
-1.
|
||
} else {
|
||
0.5
|
||
}
|
||
})
|
||
.collect(),
|
||
31.,
|
||
0.,
|
||
)),
|
||
checkered(convolution_kernel((0..169).map(|index| if index % 13 == 6 || index / 13 == 6 { 1. } else { 0. }).collect(), 25., 0.)),
|
||
// Even and uneven kernels, centered after the middle of an even count
|
||
checkered(convolution_kernel((0..16).map(|index| index as f64 - 7.).collect(), 8., 64.)),
|
||
checkered(kernel_of_width(vec![-1., 0., 2., 0., -1.], 5, 1., 40.)),
|
||
checkered(kernel_of_width(vec![1., 2., 1.], 1, 4., 0.)),
|
||
checkered(kernel_of_width(vec![1., -1., 2., -2., 3., -3.], 2, 1., 128.)),
|
||
// Applied to the alpha too, the coverage sharpens, softens, and spreads past the content with the colors
|
||
checkered(applied_to_alpha(sharpen_kernel.clone(), 4.)),
|
||
vec![applied_to_alpha(sharpen_kernel.clone(), 4.)],
|
||
vec![applied_to_alpha(vec![1.; 25], 25.)],
|
||
vec![blur(3., false, false), applied_to_alpha(sharpen_kernel, 4.)],
|
||
]);
|
||
let emboss = |angle, height, amount| EffectOperation::Emboss { angle, height, amount };
|
||
paint_cases.extend([
|
||
checkered(emboss(135., 3., 100.)),
|
||
checkered(emboss(-20., 6.5, 300.)),
|
||
checkered(EffectOperation::FindEdges),
|
||
checkered(minimum_maximum(2., MinimumMaximumMode::Minimum)),
|
||
checkered(minimum_maximum(1.5, MinimumMaximumMode::Maximum)),
|
||
checkered(EffectOperation::Adjustment(Adjustment::Solarize)),
|
||
// The square's silhouette shows in relief and as an edge against what it's matted over, and its coverage moves the opposite way to its colors
|
||
vec![emboss(60., 2., 150.)],
|
||
vec![EffectOperation::FindEdges],
|
||
vec![minimum_maximum(40., MinimumMaximumMode::Minimum)],
|
||
vec![minimum_maximum(3.5, MinimumMaximumMode::Maximum)],
|
||
// Neighborhoods widened over several passes, out past the transparency around the square, and mixed between radii either side of a power of two
|
||
vec![minimum_maximum(40., MinimumMaximumMode::Maximum)],
|
||
vec![minimum_maximum(100.5, MinimumMaximumMode::Minimum)],
|
||
vec![minimum_maximum(100.5, MinimumMaximumMode::Maximum)],
|
||
checkered(minimum_maximum(15.5, MinimumMaximumMode::Minimum)),
|
||
checkered(minimum_maximum(15.5, MinimumMaximumMode::Maximum)),
|
||
// Soft content, whose faint fringes keep their colors, and a zero radius beside another effect, which changes nothing
|
||
vec![blur(3., false, false), minimum_maximum(2., MinimumMaximumMode::Minimum)],
|
||
vec![blur(3., false, false), minimum_maximum(1.5, MinimumMaximumMode::Maximum)],
|
||
vec![blur(2., false, false), minimum_maximum(0., MinimumMaximumMode::Maximum)],
|
||
]);
|
||
let unsharp = |amount, radius, threshold| EffectOperation::Sharpen {
|
||
amount,
|
||
radius,
|
||
threshold,
|
||
edges_only: false,
|
||
};
|
||
let edges_only = |amount, threshold| EffectOperation::Sharpen {
|
||
amount,
|
||
radius: 0.,
|
||
threshold,
|
||
edges_only: true,
|
||
};
|
||
paint_cases.extend([
|
||
checkered(unsharp(150., 2., 0.)),
|
||
checkered(unsharp(400., 1.2, 20.)),
|
||
checkered(EffectOperation::HighPass { radius: 3. }),
|
||
checkered(edges_only(100., 0.)),
|
||
checkered(edges_only(250., 15.)),
|
||
// The coverage sharpens too, and the colors around the edges average only what's visible
|
||
vec![unsharp(300., 4., 0.)],
|
||
vec![EffectOperation::HighPass { radius: 12. }],
|
||
vec![edges_only(100., 0.)],
|
||
// Soft content, whose faint fringes ease into being compared against their own colors and whose gentle slopes Edges Only leaves, and a zero radius, which changes nothing
|
||
vec![blur(3., false, false), unsharp(200., 2., 0.)],
|
||
vec![blur(3., false, false), EffectOperation::HighPass { radius: 4. }],
|
||
vec![blur(2., false, false), edges_only(200., 0.)],
|
||
vec![blur(2., false, false), unsharp(150., 0., 0.)],
|
||
]);
|
||
let noise = |amount, distribution, monochromatic| EffectOperation::AddNoise {
|
||
amount,
|
||
distribution,
|
||
monochromatic,
|
||
seed: 5,
|
||
};
|
||
paint_cases.extend([
|
||
checkered(noise(30., NoiseDistribution::Uniform, false)),
|
||
checkered(noise(20., NoiseDistribution::Gaussian, true)),
|
||
checkered(EffectOperation::Dissolve { opacity: 60., seed: 2 }),
|
||
// Past full brightness, and with the fill fading the coverage that Dissolve thresholds
|
||
vec![noise(400., NoiseDistribution::Gaussian, false)],
|
||
vec![EffectOperation::Dissolve { opacity: 100., seed: 9 }],
|
||
]);
|
||
|
||
for effects in cases.into_iter().chain(paint_cases).chain(mask_cases) {
|
||
for fill in [1., 0.5] {
|
||
let Some(gpu) = render_square_over_backdrop(effects.clone(), fill, 1., BlendMode::Normal, None, gpu_content, min as f64, max as f64, size) else {
|
||
return;
|
||
};
|
||
|
||
// The same square as a raster covering the render one pixel to one pixel
|
||
let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT);
|
||
for y in min..max {
|
||
for x in min..max {
|
||
image.data[(y * size.x + x) as usize] = cpu_content;
|
||
}
|
||
}
|
||
// Graphics following the content lie in the raster's own space, so they're linked to its placement to match the square drawn without one
|
||
let placement = DAffine2::from_scale(size.as_dvec2());
|
||
// A gradient paint keeps its kind, which an outline's drawing depends on, by taking the raster's space into its own transform
|
||
let paint_in_raster_space = |paint: Graphic| match paint {
|
||
Graphic::Gradient(mut item) => {
|
||
let transform = placement.inverse() * item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||
Graphic::Gradient(item)
|
||
}
|
||
paint => graphic_types::linked_to_content(paint, placement),
|
||
};
|
||
let linked: Vec<EffectOperation> = effects
|
||
.iter()
|
||
.cloned()
|
||
.map(|mut operation| {
|
||
match &mut operation {
|
||
EffectOperation::Mask { mask, .. } => *mask = graphic_types::linked_to_content(std::mem::take(mask), placement),
|
||
EffectOperation::Blur { radius_mask, .. } => *radius_mask = graphic_types::linked_to_content(std::mem::take(radius_mask), placement),
|
||
EffectOperation::PaintOverlay { paint, .. } | EffectOperation::Outline { paint, .. } => *paint = paint_in_raster_space(std::mem::take(paint)),
|
||
EffectOperation::BevelAndEmboss { texture, .. } => *texture = paint_in_raster_space(std::mem::take(texture)),
|
||
_ => {}
|
||
}
|
||
operation
|
||
})
|
||
.collect();
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image))
|
||
.with_attribute(ATTR_TRANSFORM, placement)
|
||
.with_attribute(ATTR_OPACITY_FILL, fill as f64);
|
||
linked.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
let evaluated = evaluate_raster_effects(item);
|
||
|
||
// Reads the evaluated image at the center of each render pixel through its grown placement
|
||
let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||
let raster = evaluated.element();
|
||
let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse();
|
||
|
||
let mut worst = 0;
|
||
for y in 0..size.y {
|
||
for x in 0..size.x {
|
||
let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor();
|
||
let cpu = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize];
|
||
let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels();
|
||
let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.);
|
||
|
||
// Compared premultiplied, so a nearly transparent pixel's color can't dominate
|
||
let gpu = pixel(&gpu, size, x, y);
|
||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||
for channel in 0..4 {
|
||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||
worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32);
|
||
}
|
||
}
|
||
}
|
||
// A rendered paint rounds to eight bits, which an outline shows unmixed and modes that divide or land near black (where gamma is steepest) amplify
|
||
use BlendMode::*;
|
||
let tolerance = match effects.last() {
|
||
Some(EffectOperation::PaintOverlay { blend_mode: VividLight, .. }) => 16,
|
||
Some(EffectOperation::PaintOverlay {
|
||
blend_mode: ColorBurn | LinearBurn | ColorDodge | HardLight | LinearLight | PinLight | Difference,
|
||
..
|
||
}) => 8,
|
||
Some(operation @ EffectOperation::Outline { .. }) if operation.drawn_paints().next().is_some() => 3,
|
||
// A noisy outer glow fades by its raw strength over 0.12, which amplifies eightfold the rounding of that strength where it falls steeply, across a full spread's last pixel
|
||
Some(EffectOperation::OuterGlow { noise, spread, .. }) if *noise > 0. && *spread >= 100. => 8,
|
||
// A texture's paint rounds to eight bits, which the two renderers can land a level apart, moving the surface by its depth times its span over 255
|
||
Some(EffectOperation::BevelAndEmboss { texture, .. }) if !matches!(texture, Graphic::None(_)) => 6,
|
||
// A slope contour steeper than a straight line amplifies the rounding of the GPU's half-float heights
|
||
Some(EffectOperation::BevelAndEmboss { slope_contour, .. }) if !slope_contour.is_identity() => 4,
|
||
// A rendered map's code apart shifts the interpolation between wide levels of a blur varied by its radius mask, or its box's width
|
||
Some(operation @ EffectOperation::Blur { .. }) if operation.varies_blur_radius() => 3,
|
||
_ => 2,
|
||
};
|
||
assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_neighborhood_extremes_match_the_cpu_kernels() {
|
||
use graphic_types::Effects;
|
||
use half::f16;
|
||
|
||
// Gradients across and down that a window off by a texel shifts, beside random colors, opaque out to the edges but for a translucent band and a hole
|
||
let (width, height) = (450, 40);
|
||
let texels: Vec<[f16; 4]> = (0..width * height)
|
||
.map(|index| {
|
||
let (x, y) = (index % width, index / width);
|
||
let alpha = match (x, y) {
|
||
(300..306, 10..14) => 0.,
|
||
(0..24, _) => 0.5,
|
||
_ => 1.,
|
||
};
|
||
let random = (index as u32).wrapping_mul(2_654_435_761) >> 24;
|
||
let straight = [x as f32 / (width - 1) as f32, y as f32 / (height - 1) as f32, random as f32 / 255.];
|
||
let [red, green, blue] = straight.map(|channel| channel * alpha);
|
||
[red, green, blue, alpha].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let plane = raster_kernels::effect_kernels::Plane {
|
||
width,
|
||
height,
|
||
data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(),
|
||
};
|
||
|
||
// Radii one pass reads, those doubled several times (some near powers of two), and those reaching across the texture's height or both its sides
|
||
let mut strays = Vec::new();
|
||
for radius in [1., 2.5, 8., 9., 15.5, 31.5, 40., 64.5, 100.5, 400., 1000.] {
|
||
for maximum in [false, true] {
|
||
let mode = if maximum { MinimumMaximumMode::Maximum } else { MinimumMaximumMode::Minimum };
|
||
let operation = minimum_maximum(radius, mode);
|
||
let Some(gpu) = gpu_effect_texels(&Effects::from_operations([operation.clone()]), &texels, width, &[]) else {
|
||
return;
|
||
};
|
||
let cpu = raster_kernels::filter_kernels::neighborhood_extreme(&plane, radius, maximum, glam::DMat2::IDENTITY);
|
||
|
||
// In 8-bit levels, well below the 0.57 that one texel shifts the gradient across
|
||
let levels = (gpu.iter().zip(&cpu.data))
|
||
.flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.))
|
||
.fold(0_f32, f32::max);
|
||
if levels > 0.25 {
|
||
strays.push(format!("{operation:?} strays from the CPU's kernel by {levels} levels"));
|
||
}
|
||
}
|
||
}
|
||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||
}
|
||
|
||
/// Colors across the RGB cube, among them black, white, grays, and saturated and near-black colors, each opaque, with some also translucent or fully transparent.
|
||
fn adjustment_test_colors() -> Vec<core_types::Color> {
|
||
const LEVELS: [f32; 12] = [0., 1. / 255., 4. / 255., 0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 254. / 255., 1.];
|
||
let count = LEVELS.len();
|
||
|
||
let mut colors = Vec::new();
|
||
for index in 0..count * count * count {
|
||
let [r, g, b] = [index / (count * count), index / count % count, index % count].map(|level| LEVELS[level]);
|
||
colors.push(core_types::Color::from_gamma_srgb_channels(r, g, b, 1.));
|
||
|
||
for (spacing, alpha) in [(5, 0.5), (7, 0.15), (97, 0.)] {
|
||
if index % spacing == 0 {
|
||
colors.push(core_types::Color::from_gamma_srgb_channels(r, g, b, alpha));
|
||
}
|
||
}
|
||
}
|
||
colors
|
||
}
|
||
|
||
/// What the GPU's adjustment passes carrying out `run` at `fill` leave of each of `texels`, which like the result hold premultiplied gamma-encoded channels
|
||
/// as the half floats of the working format.
|
||
fn gpu_adjusted_texels(run: &[graphic_types::Adjustment], texels: &[[half::f16; 4]], fill: f32) -> Option<Vec<[f32; 4]>> {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
use half::f16;
|
||
use wgpu::util::DeviceExt;
|
||
|
||
let executor = executor()?;
|
||
let effect_passes = &executor.inner.vello_renderer.effect_passes;
|
||
if !effect_passes.renders_working_formats {
|
||
return None;
|
||
}
|
||
let device = &executor.context().device;
|
||
let _turn = take_turn();
|
||
|
||
// One texel for each pixel
|
||
let width = 64;
|
||
let height = texels.len().div_ceil(width);
|
||
let mut padded = texels.to_vec();
|
||
padded.resize(width * height, [f16::ZERO; 4]);
|
||
let descriptor = wgpu::TextureDescriptor {
|
||
label: Some("adjustment_test_colors"),
|
||
size: wgpu::Extent3d {
|
||
width: width as u32,
|
||
height: height as u32,
|
||
depth_or_array_layers: 1,
|
||
},
|
||
mip_level_count: 1,
|
||
sample_count: 1,
|
||
dimension: wgpu::TextureDimension::D2,
|
||
format: wgpu::TextureFormat::Rgba16Float,
|
||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||
view_formats: &[],
|
||
};
|
||
|
||
let queue = executor.context().queue.lock();
|
||
let content = device.create_texture_with_data(&queue, &descriptor, wgpu::util::TextureDataOrder::LayerMajor, bytemuck::cast_slice(&padded));
|
||
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
|
||
let mut textures = crate::vello_effects::EffectTextures::default();
|
||
let layers = graphic_types::effect_layers::EffectLayers::plan(&effects, core_types::blending::BlendMode::Normal, fill, false);
|
||
let results = effect_passes.apply(executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||
let (adjusted, _) = results.into_iter().next().expect("the adjustments draw one layer");
|
||
drop(queue);
|
||
|
||
let bytes = executor.read_texture_pixels(&adjusted).expect("Failed to read back the adjusted colors");
|
||
let half_floats: Vec<f32> = bytes.as_chunks::<2>().0.iter().map(|&bytes| f16::from_le_bytes(bytes).to_f32()).collect();
|
||
Some(half_floats.as_chunks::<4>().0[..texels.len()].to_vec())
|
||
}
|
||
|
||
/// How far, in 8-bit levels of the straight gamma-encoded channels and alpha (scaled down for values past 1 by their size, as half floats round them),
|
||
/// the GPU's adjustment passes carrying out `run` on `colors` at `fill` stray from the CPU's kernels, with the pixel that strays the most.
|
||
/// The colors reach the GPU as the half floats of its working format, so the CPU adjusts them as the GPU reads them.
|
||
fn gpu_adjustment_deviation(run: &[graphic_types::Adjustment], colors: &[core_types::Color], fill: f32) -> Option<(f32, String)> {
|
||
use half::f16;
|
||
|
||
// One color for each pixel, premultiplied with gamma-encoded channels as the effect passes hold them
|
||
let texels: Vec<[f16; 4]> = (colors.iter())
|
||
.map(|color| {
|
||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||
[red * alpha, green * alpha, blue * alpha, alpha].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let gpu = gpu_adjusted_texels(run, &texels, fill)?;
|
||
|
||
// The texels as the adjustments read them (which a fill fades first, into half floats again), adjusted one after another as the CPU carries out effects
|
||
let inputs: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(|channel| f16::from_f32(channel.to_f32() * fill).to_f32())).collect();
|
||
let mut cpu = inputs.clone();
|
||
run.iter().for_each(|adjustment| raster_kernels::raster_effects::adjust_premultiplied(&mut cpu, adjustment));
|
||
|
||
let straight = |[red, green, blue, alpha]: [f32; 4]| if alpha > 0. { [red / alpha, green / alpha, blue / alpha, alpha] } else { [0.; 4] };
|
||
let mut worst = (0_f32, String::new());
|
||
for (index, (input, cpu)) in inputs.iter().zip(&cpu).enumerate() {
|
||
let (input, gpu, cpu) = (straight(*input), straight(gpu[index]), straight(*cpu));
|
||
|
||
// Without alpha a pixel shows no color to compare, and a NaN on only one side strays without bound
|
||
let channels = if gpu[3] > 0. && cpu[3] > 0. { 0..4 } else { 3..4 };
|
||
for channel in channels {
|
||
let deviation = match (gpu[channel].is_nan(), cpu[channel].is_nan()) {
|
||
(false, false) => (gpu[channel] - cpu[channel]).abs() * 255. / cpu[channel].abs().max(1.),
|
||
(true, true) => 0.,
|
||
_ => f32::INFINITY,
|
||
};
|
||
if deviation > worst.0 {
|
||
worst = (deviation, format!("{input:?} as {gpu:?} rather than {cpu:?}"));
|
||
}
|
||
}
|
||
}
|
||
Some(worst)
|
||
}
|
||
|
||
/// Checks that each named run of adjustments strays from the CPU's kernels on the GPU by at most the rounding of the half floats its passes write, printing how far each strays.
|
||
fn assert_gpu_adjustments_match_the_cpu_kernels(runs: Vec<(impl std::fmt::Display, Vec<graphic_types::Adjustment>)>) {
|
||
assert_gpu_adjustments_stray_at_most(0.3, runs, &[1.]);
|
||
}
|
||
|
||
/// Checks that each named run strays from the CPU's kernels by at most `limit` levels at each of `fills`, which should be powers of two so fading by them rounds nothing.
|
||
fn assert_gpu_adjustments_stray_at_most(limit: f32, runs: Vec<(impl std::fmt::Display, Vec<graphic_types::Adjustment>)>, fills: &[f32]) {
|
||
let colors = adjustment_test_colors();
|
||
|
||
let mut strays = Vec::new();
|
||
for (name, run) in runs {
|
||
// A Color Overlay draws as a pass of its own, splitting the run of adjustments around it into passes of their own too
|
||
let is_overlay = |adjustment: &graphic_types::Adjustment| matches!(adjustment, graphic_types::Adjustment::ColorOverlay { .. });
|
||
let passes = run.split(is_overlay).filter(|adjustments| !adjustments.is_empty()).count() + run.iter().filter(|adjustment| is_overlay(adjustment)).count();
|
||
|
||
// It paints within the content unfaded by the fill, unlike the kernels adjusting the faded content, so a run with one is compared at a full fill
|
||
let has_overlay = run.iter().any(is_overlay);
|
||
for &fill in fills.iter().filter(|&&fill| fill >= 1. || !has_overlay) {
|
||
let Some((levels, worst_pixel)) = gpu_adjustment_deviation(&run, &colors, fill) else { return };
|
||
println!("{name} at a fill of {fill}: {levels:.3} levels");
|
||
|
||
if levels > limit * passes.max(1) as f32 {
|
||
strays.push(format!("{name} at a fill of {fill} strays from the CPU's kernels by {levels} levels, adjusting {worst_pixel}"));
|
||
}
|
||
}
|
||
}
|
||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_tone_adjustments_match_the_cpu_kernels() {
|
||
use core_types::transfer_curve::TransferCurve;
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::*;
|
||
|
||
let record = |shadows, midtones, highlights, output_minimums, output_maximums| LevelsRecord {
|
||
shadows,
|
||
midtones,
|
||
highlights,
|
||
output_minimums,
|
||
output_maximums,
|
||
};
|
||
let identity = record(0., 1., 100., 0., 100.);
|
||
let levels = |composite, red, green, blue, alpha| Adjustment::Levels(Box::new(LevelsSettings { composite, red, green, blue, alpha }));
|
||
|
||
let curve = |points: &[(f64, f64)]| TransferCurve::new(points.iter().map(|&(x, y)| DVec2::new(x, y)).collect());
|
||
let curves = |composite, red, green, blue, alpha| Adjustment::Curves(Box::new(CurvesSettings { composite, red, green, blue, alpha }));
|
||
let straight = TransferCurve::default;
|
||
|
||
let brightness_contrast = |brightness, contrast, use_classic| Adjustment::BrightnessContrast {
|
||
brightness,
|
||
contrast,
|
||
use_classic,
|
||
classic_pivot: 127.,
|
||
};
|
||
let exposure = |exposure, offset, gamma_correction| Adjustment::Exposure { exposure, offset, gamma_correction };
|
||
|
||
let runs = [
|
||
("Levels", levels(record(10., 1.4, 90., 0., 100.), identity, record(5., 0.8, 100., 0., 100.), identity, identity)),
|
||
(
|
||
"Levels with midtones at their bounds",
|
||
levels(record(0., 9.99, 100., 0., 100.), record(0., 0.01, 100., 0., 100.), identity, record(20., 0.1, 80., 10., 90.), identity),
|
||
),
|
||
(
|
||
"Levels with gammas merged into one",
|
||
levels(record(0., 2.5, 100., 5., 95.), record(30., 3.2, 100., 0., 100.), record(0., 0.3, 60., 0., 100.), identity, identity),
|
||
),
|
||
(
|
||
"Levels with inverted output and a bent alpha",
|
||
levels(record(40., 1., 41., 90., 10.), identity, identity, identity, record(10., 2.2, 90., 0., 80.)),
|
||
),
|
||
(
|
||
"Curves",
|
||
curves(
|
||
curve(&[(0., 0.), (0.25, 0.4), (0.75, 0.7), (1., 1.)]),
|
||
straight(),
|
||
curve(&[(0., 0.1), (1., 0.9)]),
|
||
straight(),
|
||
straight(),
|
||
),
|
||
),
|
||
(
|
||
"Curves with steep segments",
|
||
curves(
|
||
curve(&[(0., 0.), (0.45, 0.02), (0.5, 0.98), (1., 1.)]),
|
||
curve(&[(0.2, 0.9), (0.21, 0.1)]),
|
||
curve(&[(0.5, 0.5)]),
|
||
TransferCurve::new(Vec::new()),
|
||
curve(&[(0., 1.), (1., 0.)]),
|
||
),
|
||
),
|
||
("Brightness/Contrast", brightness_contrast(40., 30., false)),
|
||
("Brightness/Contrast darkening", brightness_contrast(-60., -40., false)),
|
||
("Brightness/Contrast beyond 100", brightness_contrast(150., 100., false)),
|
||
("Brightness/Contrast beyond -100", brightness_contrast(-150., -50., false)),
|
||
("Brightness/Contrast classic", brightness_contrast(50., 50., true)),
|
||
("Brightness/Contrast classic squeezed", brightness_contrast(-30., -100., true)),
|
||
("Brightness/Contrast classic at full contrast", brightness_contrast(20., 100., true)),
|
||
("Exposure", exposure(1.5, 0.05, 1.2)),
|
||
("Exposure darkening", exposure(-2., -0.1, 0.5)),
|
||
("Exposure at its extremes", exposure(8., 0., 9.99)),
|
||
("Exposure with the least gamma", exposure(0., 0.3, 0.01)),
|
||
("Gamma Correction", Adjustment::GammaCorrection { gamma: 2.2, inverse: false }),
|
||
("Gamma Correction inverse", Adjustment::GammaCorrection { gamma: 0.4, inverse: true }),
|
||
("Gamma Correction at its extremes", Adjustment::GammaCorrection { gamma: 0.01, inverse: false }),
|
||
("Posterize to 2 levels", Adjustment::Posterize { levels: 2 }),
|
||
("Posterize to 7 levels", Adjustment::Posterize { levels: 7 }),
|
||
("Posterize to 255 levels", Adjustment::Posterize { levels: 255 }),
|
||
(
|
||
"Threshold",
|
||
Adjustment::Threshold {
|
||
min_luminance: 37.3,
|
||
max_luminance: 88.1,
|
||
},
|
||
),
|
||
(
|
||
"Threshold across everything",
|
||
Adjustment::Threshold {
|
||
min_luminance: 0.,
|
||
max_luminance: 100.,
|
||
},
|
||
),
|
||
(
|
||
"Threshold of the shadows",
|
||
Adjustment::Threshold {
|
||
min_luminance: 12.3,
|
||
max_luminance: 47.9,
|
||
},
|
||
),
|
||
("Invert", Adjustment::Invert),
|
||
("Solarize", Adjustment::Solarize),
|
||
("Make Opaque", Adjustment::MakeOpaque { strength: 100. }),
|
||
("Make Opaque at half strength", Adjustment::MakeOpaque { strength: 50. }),
|
||
];
|
||
assert_gpu_adjustments_match_the_cpu_kernels(runs.into_iter().map(|(name, adjustment)| (name, vec![adjustment])).collect());
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_color_adjustments_match_the_cpu_kernels() {
|
||
use core_types::Color;
|
||
use core_types::blending::BlendMode;
|
||
use graphic_types::adjustment::*;
|
||
|
||
let desaturate = |method| Adjustment::Desaturate { method };
|
||
|
||
let black_and_white = |weights: [f64; 6], use_tint| {
|
||
let [reds, yellows, greens, cyans, blues, magentas] = weights;
|
||
Adjustment::BlackAndWhite(BlackAndWhiteSettings {
|
||
use_tint,
|
||
tint: Color::from_gamma_srgb_channels(0.88, 0.83, 0.7, 1.),
|
||
reds,
|
||
yellows,
|
||
greens,
|
||
cyans,
|
||
blues,
|
||
magentas,
|
||
})
|
||
};
|
||
|
||
let sliders = |hue, saturation, lightness| HueSaturationSliders { hue, saturation, lightness };
|
||
let range = |sliders, [falloff_start, range_start, range_end, falloff_end]: [f64; 4]| HueRangeSettings {
|
||
sliders,
|
||
falloff_start,
|
||
range_start,
|
||
range_end,
|
||
falloff_end,
|
||
};
|
||
let zero = sliders(0., 0., 0.);
|
||
let hue_saturation = |master, colorize, ranges: [HueSaturationSliders; 6]| {
|
||
let [reds, yellows, greens, cyans, blues, magentas] = ranges;
|
||
Adjustment::HueSaturation(Box::new(HueSaturationSettings {
|
||
master,
|
||
colorize,
|
||
colorize_sliders: sliders(200., 60., -30.),
|
||
reds: range(reds, [315., 345., 15., 45.]),
|
||
yellows: range(yellows, [15., 45., 75., 105.]),
|
||
greens: range(greens, [75., 105., 135., 165.]),
|
||
cyans: range(cyans, [135., 165., 195., 225.]),
|
||
blues: range(blues, [195., 225., 255., 285.]),
|
||
magentas: range(magentas, [255., 285., 315., 345.]),
|
||
}))
|
||
};
|
||
|
||
let row = |red, green, blue, constant| ChannelMixerRow { red, green, blue, constant };
|
||
let channel_mixer = |monochrome, red, green, blue| {
|
||
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||
monochrome,
|
||
monochrome_mix: row(40., 40., 20., 5.),
|
||
red,
|
||
green,
|
||
blue,
|
||
}))
|
||
};
|
||
|
||
let inks = |cyan, magenta, yellow, black| SelectiveColorInks { cyan, magenta, yellow, black };
|
||
let selective_color = |mode, groups: [SelectiveColorInks; 9]| {
|
||
let [reds, yellows, greens, cyans, blues, magentas, whites, neutrals, blacks] = groups;
|
||
Adjustment::SelectiveColor(Box::new(SelectiveColorSettings {
|
||
mode,
|
||
reds,
|
||
yellows,
|
||
greens,
|
||
cyans,
|
||
blues,
|
||
magentas,
|
||
whites,
|
||
neutrals,
|
||
blacks,
|
||
}))
|
||
};
|
||
let some_inks = [
|
||
inks(-20., 15., 30., 0.),
|
||
inks(0., 0., 0., 0.),
|
||
inks(35., -10., 0., 20.),
|
||
inks(-40., 25., 10., -15.),
|
||
inks(10., 10., -30., 5.),
|
||
inks(0., -50., 45., 0.),
|
||
inks(-25., 0., 0., 30.),
|
||
inks(15., -15., 20., -10.),
|
||
inks(0., 20., -20., 40.),
|
||
];
|
||
let extreme_inks = [100., -100., 100., -100., 100., -100., 100., -100., 100.].map(|percent| inks(percent, -percent, percent, -percent));
|
||
|
||
let shifts = |cyan_red, magenta_green, yellow_blue| ColorBalanceShifts { cyan_red, magenta_green, yellow_blue };
|
||
let color_balance = |shadows, midtones, highlights, preserve_luminosity| {
|
||
Adjustment::ColorBalance(ColorBalanceSettings {
|
||
shadows,
|
||
midtones,
|
||
highlights,
|
||
preserve_luminosity,
|
||
})
|
||
};
|
||
|
||
let photo_filter = |color, density, preserve_luminosity| Adjustment::PhotoFilter { color, density, preserve_luminosity };
|
||
let warming = Color::from_gamma_srgb_channels(0.925, 0.541, 0., 1.);
|
||
let cooling = Color::from_gamma_srgb_channels(0., 0.42, 1., 1.);
|
||
|
||
let runs = [
|
||
("Desaturate by Rec. 709 luminance", desaturate(DesaturateMethod::LuminanceRec709)),
|
||
("Desaturate by Rec. 709 luma", desaturate(DesaturateMethod::LumaRec709)),
|
||
("Desaturate by Rec. 601 luma", desaturate(DesaturateMethod::LumaRec601)),
|
||
("Desaturate by OkLab lightness", desaturate(DesaturateMethod::LightnessOkLab)),
|
||
("Desaturate by the channels' average", desaturate(DesaturateMethod::ChannelsAverage)),
|
||
("Desaturate by the channels' minimum", desaturate(DesaturateMethod::ChannelsMinimum)),
|
||
("Desaturate by the channels' maximum", desaturate(DesaturateMethod::ChannelsMaximum)),
|
||
("Desaturate by HSL lightness", desaturate(DesaturateMethod::LightnessHsl)),
|
||
("Black & White", black_and_white([40., 60., 40., 60., 20., 80.], false)),
|
||
("Black & White tinted at extreme weights", black_and_white([300., -200., 150., -50., 250., -100.], true)),
|
||
("Hue/Saturation", hue_saturation(sliders(25., 30., 5.), false, [sliders(-15., 40., 0.), zero, zero, zero, zero, zero])),
|
||
(
|
||
"Hue/Saturation by range at extremes",
|
||
hue_saturation(
|
||
sliders(-120., -20., 0.),
|
||
false,
|
||
[zero, sliders(30., -100., 50.), sliders(0., 100., 0.), zero, sliders(60., 0., -100.), sliders(-90., 60., 100.)],
|
||
),
|
||
),
|
||
("Hue/Saturation fully saturating", hue_saturation(sliders(0., 100., -40.), false, [zero; 6])),
|
||
// A range's full lightness leaves grays, which the full saturation of another slider has no color in to raise
|
||
(
|
||
"Hue/Saturation with a range's lightness and the master's saturation at their ends",
|
||
hue_saturation(sliders(0., 100., 0.), false, [sliders(0., 0., -100.), zero, sliders(0., 0., 100.), zero, zero, zero]),
|
||
),
|
||
(
|
||
"Hue/Saturation with a range's lightness and its own saturation at their ends",
|
||
hue_saturation(zero, false, [sliders(0., 100., 100.), zero, zero, sliders(0., 100., -100.), zero, zero]),
|
||
),
|
||
(
|
||
"Hue/Saturation with the master's lightness and saturation at their ends",
|
||
hue_saturation(sliders(0., 100., 100.), false, [zero; 6]),
|
||
),
|
||
("Hue/Saturation fully desaturating and lightening", hue_saturation(sliders(180., -100., 100.), false, [zero; 6])),
|
||
("Hue/Saturation colorizing", hue_saturation(zero, true, [zero; 6])),
|
||
("Vibrance", Adjustment::Vibrance { vibrance: 60., saturation: 20. }),
|
||
("Vibrance draining", Adjustment::Vibrance { vibrance: -80., saturation: -50. }),
|
||
("Vibrance at its most", Adjustment::Vibrance { vibrance: 100., saturation: 100. }),
|
||
("Vibrance at its least", Adjustment::Vibrance { vibrance: -100., saturation: -100. }),
|
||
("Channel Mixer", channel_mixer(false, row(80., 20., 0., 0.), row(10., 70., 20., 0.), row(0., 30., 90., -10.))),
|
||
(
|
||
"Channel Mixer at extremes",
|
||
channel_mixer(false, row(200., -200., 50., 100.), row(-150., 200., -50., -100.), row(33.3, 33.3, 33.3, 0.)),
|
||
),
|
||
("Channel Mixer in monochrome", channel_mixer(true, row(100., 0., 0., 0.), row(0., 100., 0., 0.), row(0., 0., 100., 0.))),
|
||
("Selective Color", selective_color(RelativeAbsolute::Relative, some_inks)),
|
||
("Selective Color absolute", selective_color(RelativeAbsolute::Absolute, some_inks)),
|
||
("Selective Color at extremes", selective_color(RelativeAbsolute::Relative, extreme_inks)),
|
||
("Selective Color absolute at extremes", selective_color(RelativeAbsolute::Absolute, extreme_inks)),
|
||
("Color Balance", color_balance(shifts(30., -20., 10.), shifts(-40., 25., 60.), shifts(15., -35., -10.), true)),
|
||
(
|
||
"Color Balance without preserving luminosity",
|
||
color_balance(shifts(30., -20., 10.), shifts(-40., 25., 60.), shifts(15., -35., -10.), false),
|
||
),
|
||
(
|
||
"Color Balance at extremes",
|
||
color_balance(shifts(100., -100., 100.), shifts(-100., 100., -100.), shifts(100., 100., -100.), false),
|
||
),
|
||
("Photo Filter", photo_filter(warming, 25., true)),
|
||
("Photo Filter at full density", photo_filter(cooling, 100., false)),
|
||
("Photo Filter at full density preserving luminosity", photo_filter(cooling, 100., true)),
|
||
];
|
||
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
|
||
|
||
// Every blend mode, overlaying an opaque color and a translucent one, each with channels summing to what no test color's do, which Darker Color and Lighter Color compare
|
||
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
|
||
for (color, opacity) in [
|
||
(Color::from_gamma_srgb_channels(0.9, 0.453, 0.2, 1.), 70.),
|
||
(Color::from_gamma_srgb_channels(0.1, 0.6, 0.853, 0.4), 100.),
|
||
] {
|
||
let overlay = Adjustment::ColorOverlay {
|
||
color,
|
||
blend_mode: *blend_mode,
|
||
opacity,
|
||
};
|
||
runs.push((format!("Color Overlay with {blend_mode} at {opacity}% opacity"), vec![overlay]));
|
||
}
|
||
}
|
||
|
||
assert_gpu_adjustments_match_the_cpu_kernels(runs);
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_gradient_maps_match_the_cpu_kernels() {
|
||
use core_types::Color;
|
||
use core_types::list::{ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, Item};
|
||
use graphic_types::Adjustment;
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, GradientStop};
|
||
|
||
let stop = |position, midpoint, [red, green, blue]: [f32; 3]| GradientStop {
|
||
position,
|
||
midpoint,
|
||
color: Color::from_gamma_srgb_channels(red, green, blue, 1.),
|
||
};
|
||
let stops = vec![stop(0., 0.3, [0.05, 0., 0.3]), stop(0.35, 0.5, [0.9, 0.2, 0.1]), stop(1., 0.75, [1., 0.95, 0.4])];
|
||
let gradient_map = |stops: &Vec<GradientStop>, space, interpolation, hue_direction, spread, cyclic, reverse| Adjustment::GradientMap {
|
||
gradient: Item::new_from_element(Gradient::new(stops.iter().copied()))
|
||
.with_attribute(ATTR_GRADIENT_SPACE, space)
|
||
.with_attribute(ATTR_GRADIENT_INTERPOLATION, interpolation)
|
||
.with_attribute(ATTR_GRADIENT_HUE_DIRECTION, hue_direction)
|
||
.with_attribute(ATTR_GRADIENT_SPREAD, spread)
|
||
.with_attribute(ATTR_GRADIENT_CYCLIC, cyclic),
|
||
reverse,
|
||
};
|
||
let spaces = [
|
||
GradientSpace::OkLab,
|
||
GradientSpace::Lab,
|
||
GradientSpace::OkLCh,
|
||
GradientSpace::LCh,
|
||
GradientSpace::RgbLinear,
|
||
GradientSpace::RgbGamma,
|
||
GradientSpace::Hsv,
|
||
GradientSpace::Hsl,
|
||
];
|
||
|
||
let mut runs = Vec::new();
|
||
for space in spaces {
|
||
for interpolation in [GradientInterpolation::Linear, GradientInterpolation::Smooth] {
|
||
let name = format!("Gradient Map {interpolation:?} in {space:?}");
|
||
runs.push((name, gradient_map(&stops, space, interpolation, GradientHueDirection::Shorter, GradientSpread::Pad, false, false)));
|
||
}
|
||
}
|
||
for hue_direction in [GradientHueDirection::Longer, GradientHueDirection::Increasing, GradientHueDirection::Decreasing] {
|
||
for (space, interpolation) in [(GradientSpace::OkLCh, GradientInterpolation::Linear), (GradientSpace::Hsl, GradientInterpolation::Smooth)] {
|
||
let name = format!("Gradient Map {interpolation:?} in {space:?} the {hue_direction:?} way");
|
||
runs.push((name, gradient_map(&stops, space, interpolation, hue_direction, GradientSpread::Pad, false, false)));
|
||
}
|
||
}
|
||
|
||
// Hard steps where no color's position lands exactly, which float rounding could tip either way, then stops past the ends, a single stop, and none
|
||
let steps = vec![stop(0.05, 0.5, [0.05, 0., 0.3]), stop(0.3721, 0.5, [0.9, 0.2, 0.1]), stop(0.9, 0.5, [1., 0.95, 0.4])];
|
||
let wrapping = vec![stop(0.08, 0.3, [0.05, 0., 0.3]), stop(0.35, 0.5, [0.9, 0.2, 0.1]), stop(0.83, 0.65, [1., 0.95, 0.4])];
|
||
let hard_edge = vec![
|
||
stop(0., 0.5, [0.1, 0.1, 0.1]),
|
||
stop(0.4137, 0.5, [0.9, 0.2, 0.1]),
|
||
stop(0.4137, 0.5, [0.1, 0.3, 0.9]),
|
||
stop(1., 0.5, [0.9, 0.9, 0.9]),
|
||
];
|
||
let outside = vec![stop(-0.2, 0.6, [0., 0.4, 0.2]), stop(0.5, 0.5, [0.7, 0.7, 0.1]), stop(1.3, 0.5, [0.2, 0., 0.9])];
|
||
let single = vec![stop(0.4, 0.5, [0.3, 0.6, 0.9])];
|
||
|
||
// Stops exactly where the test colors' black, grays, and white land, which each take the color of the stop they land on
|
||
let at_grays = vec![
|
||
stop(0., 0.5, [0.1, 0.1, 0.1]),
|
||
stop(0.2, 0.5, [0.9, 0.2, 0.1]),
|
||
stop(0.5, 0.5, [0.1, 0.3, 0.9]),
|
||
stop(0.8, 0.5, [0.2, 0.8, 0.3]),
|
||
stop(1., 0.5, [0.9, 0.9, 0.9]),
|
||
];
|
||
|
||
let linear = (GradientSpace::OkLab, GradientInterpolation::Linear, GradientHueDirection::Shorter);
|
||
let stepped = (GradientSpace::OkLab, GradientInterpolation::Stepped, GradientHueDirection::Shorter);
|
||
for (name, stops, (space, interpolation, hue_direction), spread, cyclic, reverse) in [
|
||
("stepped", &steps, stepped, GradientSpread::Pad, false, false),
|
||
("stepped and cyclic", &steps, stepped, GradientSpread::Pad, true, false),
|
||
("stepped at the grays", &at_grays, stepped, GradientSpread::Pad, false, false),
|
||
("stepped at the grays in reverse", &at_grays, stepped, GradientSpread::Pad, false, true),
|
||
("stepped at the grays, cyclic, and repeating", &at_grays, stepped, GradientSpread::Repeat, true, false),
|
||
("repeating up to white", &at_grays, linear, GradientSpread::Repeat, false, false),
|
||
("repeating down to black in reverse", &at_grays, linear, GradientSpread::Repeat, false, true),
|
||
("clear past its ends", &at_grays, linear, GradientSpread::Clear, false, false),
|
||
("with a hard edge", &hard_edge, linear, GradientSpread::Pad, false, false),
|
||
("reversed", &stops, linear, GradientSpread::Pad, false, true),
|
||
("cyclic and repeating", &wrapping, linear, GradientSpread::Repeat, true, false),
|
||
(
|
||
"smooth, cyclic, and repeating",
|
||
&stops,
|
||
(GradientSpace::Lab, GradientInterpolation::Smooth, GradientHueDirection::Shorter),
|
||
GradientSpread::Repeat,
|
||
true,
|
||
true,
|
||
),
|
||
("reflected with stops past its ends", &outside, linear, GradientSpread::Reflect, false, false),
|
||
(
|
||
"smooth with stops past its ends",
|
||
&outside,
|
||
(GradientSpace::OkLCh, GradientInterpolation::Smooth, GradientHueDirection::Shorter),
|
||
GradientSpread::Pad,
|
||
false,
|
||
false,
|
||
),
|
||
("of a single stop", &single, linear, GradientSpread::Pad, false, false),
|
||
("of no stops", &Vec::new(), linear, GradientSpread::Pad, false, false),
|
||
] {
|
||
runs.push((format!("Gradient Map {name}"), gradient_map(stops, space, interpolation, hue_direction, spread, cyclic, reverse)));
|
||
}
|
||
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name, vec![adjustment])).collect();
|
||
|
||
// Positions past both ends of the ramp, from a lookup table stretching every channel out of gamut, which each spread folds back its own way
|
||
let out_of_gamut = Adjustment::ColorLookup {
|
||
lut_file: graphene_resource::Resource::new(b"LUT_1D_SIZE 2\n-0.6 -0.6 -0.6\n1.7 1.7 1.7\n".to_vec()),
|
||
};
|
||
for (spread, interpolation) in [
|
||
(GradientSpread::Reflect, GradientInterpolation::Linear),
|
||
(GradientSpread::Repeat, GradientInterpolation::Smooth),
|
||
(GradientSpread::Clear, GradientInterpolation::Stepped),
|
||
] {
|
||
let map = gradient_map(&steps, GradientSpace::OkLab, interpolation, GradientHueDirection::Shorter, spread, false, false);
|
||
runs.push((format!("Gradient Map {interpolation:?} with {spread:?} out of gamut"), vec![out_of_gamut.clone(), map]));
|
||
}
|
||
|
||
assert_gpu_adjustments_match_the_cpu_kernels(runs);
|
||
}
|
||
|
||
/// An ICC profile of the `class` and color `space` holding one `A2B0` tag.
|
||
fn icc_profile(class: &[u8; 4], space: &[u8; 4], tag: &[u8]) -> Vec<u8> {
|
||
let mut bytes = vec![0; 128];
|
||
bytes[8] = 2;
|
||
bytes[12..16].copy_from_slice(class);
|
||
bytes[16..20].copy_from_slice(space);
|
||
bytes[20..24].copy_from_slice(space);
|
||
bytes[36..40].copy_from_slice(b"acsp");
|
||
|
||
bytes.extend_from_slice(&1_u32.to_be_bytes());
|
||
bytes.extend_from_slice(b"A2B0");
|
||
bytes.extend_from_slice(&144_u32.to_be_bytes());
|
||
bytes.extend_from_slice(&(tag.len() as u32).to_be_bytes());
|
||
bytes.extend_from_slice(tag);
|
||
bytes
|
||
}
|
||
|
||
/// A value from 0 to 1 as an ICC profile's unsigned 16-bit sample.
|
||
fn icc_sample(value: f32) -> [u8; 2] {
|
||
((value.clamp(0., 1.) * 65_535.).round() as u16).to_be_bytes()
|
||
}
|
||
|
||
/// An ICC profile's `s15Fixed16Number`.
|
||
fn icc_fixed(value: f32) -> [u8; 4] {
|
||
((value * 65_536.).round() as i32).to_be_bytes()
|
||
}
|
||
|
||
/// An abstract profile with a `lut16Type` table bending CIELAB in its legacy encoding, with output curves after it.
|
||
fn icc_abstract_profile() -> Vec<u8> {
|
||
const GRID: usize = 5;
|
||
const OUTPUT_ENTRIES: usize = 16;
|
||
|
||
let mut tag = vec![0; 52];
|
||
tag[0..4].copy_from_slice(b"mft2");
|
||
tag[8] = 3;
|
||
tag[9] = 3;
|
||
tag[10] = GRID as u8;
|
||
tag[48..50].copy_from_slice(&2_u16.to_be_bytes());
|
||
tag[50..52].copy_from_slice(&(OUTPUT_ENTRIES as u16).to_be_bytes());
|
||
|
||
// Identity input curves, a grid lightening and saturating, then output curves bending gently
|
||
for _ in 0..3 {
|
||
tag.extend([icc_sample(0.), icc_sample(1.)].concat());
|
||
}
|
||
let step = |index: usize| index as f32 / (GRID - 1) as f32;
|
||
for l in 0..GRID {
|
||
for a in 0..GRID {
|
||
for b in 0..GRID {
|
||
let (l, a, b) = (step(l), step(a), step(b));
|
||
for value in [l.powf(0.85), 0.5 + (a - 0.5) * 1.3, 0.5 + (b - 0.5) * 0.8 + 0.05 * l] {
|
||
tag.extend(icc_sample(value));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
for _ in 0..3 {
|
||
tag.extend((0..OUTPUT_ENTRIES).flat_map(|index| icc_sample((index as f32 / (OUTPUT_ENTRIES - 1) as f32).powf(0.9))));
|
||
}
|
||
|
||
icc_profile(b"abst", b"Lab ", &tag)
|
||
}
|
||
|
||
/// An abstract profile with a `lutAToBType` transform bending CIELAB in its standard encoding without a grid, by parametric curves of functions 0, 1, and 2
|
||
/// around a matrix, among them one with an `a` of 0 and one raising to a power of 0.
|
||
fn icc_standard_lab_profile() -> Vec<u8> {
|
||
let parametric = |function: u16, parameters: &[f32]| {
|
||
let mut bytes = b"para\0\0\0\0".to_vec();
|
||
bytes.extend_from_slice(&function.to_be_bytes());
|
||
bytes.extend_from_slice(&[0, 0]);
|
||
bytes.extend(parameters.iter().flat_map(|¶meter| icc_fixed(parameter)));
|
||
bytes
|
||
};
|
||
|
||
let mut tag = b"mAB \0\0\0\0\x03\x03\0\0".to_vec();
|
||
tag.extend_from_slice(&[0; 20]);
|
||
let place = |tag: &mut Vec<u8>, elements: Vec<Vec<u8>>| {
|
||
let offset = tag.len() as u32;
|
||
for element in elements {
|
||
tag.extend(element);
|
||
tag.resize(tag.len().next_multiple_of(4), 0);
|
||
}
|
||
offset
|
||
};
|
||
|
||
let b_curves = vec![parametric(1, &[1.2, 0.95, 0.02]), parametric(2, &[0.9, 1.1, -0.05, 0.03]), parametric(2, &[1.4, 0., 0.5, 0.1])];
|
||
let b_offset = place(&mut tag, b_curves);
|
||
let matrix = [1., 0.05, 0., 0., 0.9, 0.1, 0., 0., 1., 0., 0.02, -0.03];
|
||
let matrix_offset = place(&mut tag, vec![matrix.iter().flat_map(|&value| icc_fixed(value)).collect()]);
|
||
let m_offset = place(&mut tag, vec![parametric(0, &[0.8]), parametric(0, &[1.]), parametric(0, &[0.])]);
|
||
|
||
for (index, offset) in [b_offset, matrix_offset, m_offset].into_iter().enumerate() {
|
||
tag[12 + 4 * index..16 + 4 * index].copy_from_slice(&offset.to_be_bytes());
|
||
}
|
||
icc_profile(b"abst", b"Lab ", &tag)
|
||
}
|
||
|
||
/// A device link profile with a `lutAToBType` transform running sampled curves, a grid of `grid_size` points along each axis, power curves,
|
||
/// a matrix with offsets, then parametric curves.
|
||
fn icc_device_link_profile(grid_size: u8) -> Vec<u8> {
|
||
let sampled = |samples: &[f32]| {
|
||
let mut bytes = b"curv\0\0\0\0".to_vec();
|
||
bytes.extend_from_slice(&(samples.len() as u32).to_be_bytes());
|
||
bytes.extend(samples.iter().flat_map(|&sample| icc_sample(sample)));
|
||
bytes
|
||
};
|
||
let power = |gamma: f32| {
|
||
let mut bytes = b"curv\0\0\0\0".to_vec();
|
||
bytes.extend_from_slice(&1_u32.to_be_bytes());
|
||
bytes.extend_from_slice(&((gamma * 256.).round() as u16).to_be_bytes());
|
||
bytes
|
||
};
|
||
let parametric = |function: u16, parameters: &[f32]| {
|
||
let mut bytes = b"para\0\0\0\0".to_vec();
|
||
bytes.extend_from_slice(&function.to_be_bytes());
|
||
bytes.extend_from_slice(&[0, 0]);
|
||
bytes.extend(parameters.iter().flat_map(|¶meter| icc_fixed(parameter)));
|
||
bytes
|
||
};
|
||
|
||
// Each element starts on a four-byte boundary, located by its offset within the tag
|
||
let mut tag = b"mAB \0\0\0\0\x03\x03\0\0".to_vec();
|
||
tag.extend_from_slice(&[0; 20]);
|
||
let place = |tag: &mut Vec<u8>, elements: Vec<Vec<u8>>| {
|
||
let offset = tag.len() as u32;
|
||
for element in elements {
|
||
tag.extend(element);
|
||
tag.resize(tag.len().next_multiple_of(4), 0);
|
||
}
|
||
offset
|
||
};
|
||
|
||
let b_curves = vec![
|
||
parametric(3, &[2.4, 1. / 1.055, 0.055 / 1.055, 1. / 12.92, 0.04045]),
|
||
parametric(4, &[1.8, 0.9, 0.05, 0.5, 0.1, 0.02, 0.01]),
|
||
parametric(0, &[0.7]),
|
||
];
|
||
let b_offset = place(&mut tag, b_curves);
|
||
let matrix = [0.9, 0.1, 0., -0.05, 1.05, 0., 0.1, -0.1, 1., 0.02, 0., -0.01];
|
||
let matrix_offset = place(&mut tag, vec![matrix.iter().flat_map(|&value| icc_fixed(value)).collect()]);
|
||
let m_offset = place(&mut tag, vec![power(1.8), power(1.), power(0.6)]);
|
||
|
||
let mut grid = vec![grid_size; 3];
|
||
grid.resize(16, 0);
|
||
grid.extend_from_slice(&[2, 0, 0, 0]);
|
||
for r in 0..grid_size {
|
||
for g in 0..grid_size {
|
||
for b in 0..grid_size {
|
||
let [r, g, b] = [r, g, b].map(|index| index as f32 / (grid_size - 1) as f32);
|
||
for value in [r * 0.8 + g * 0.2, g * g, (b + 0.25 * r * g).min(1.)] {
|
||
grid.extend(icc_sample(value));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
let grid_offset = place(&mut tag, vec![grid]);
|
||
let a_offset = place(&mut tag, vec![sampled(&[0., 0.3, 0.55, 0.8, 1.]), sampled(&[0., 0.1, 0.4, 1.]), sampled(&[0.2, 0.9])]);
|
||
|
||
for (index, offset) in [b_offset, matrix_offset, m_offset, grid_offset, a_offset].into_iter().enumerate() {
|
||
tag[12 + 4 * index..16 + 4 * index].copy_from_slice(&offset.to_be_bytes());
|
||
}
|
||
icc_profile(b"link", b"RGB ", &tag)
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_color_lookups_match_the_cpu_kernels() {
|
||
use graphic_types::Adjustment;
|
||
|
||
let grid = |size: usize| (0..size * size * size).map(move |index| [index % size, index / size % size, index / (size * size)].map(|step| step as f32 / (size - 1) as f32));
|
||
|
||
// Three-dimensional CUBE files with red varying fastest, the largest spanning several rows of the texture holding it
|
||
let cube_of_size = |size: usize| {
|
||
let mut cube = format!("TITLE \"Bent\"\nLUT_3D_SIZE {size}\n");
|
||
for [r, g, b] in grid(size) {
|
||
cube += &format!("{} {} {}\n", r.powf(0.8) * 0.9 + 0.1 * g, g * g * 0.7 + 0.2 * b, (b + 0.3 * r * g).min(1.));
|
||
}
|
||
cube
|
||
};
|
||
let cube = cube_of_size(9);
|
||
|
||
// A one-dimensional CUBE file over a domain other than 0 to 1
|
||
let mut one_dimensional = String::from("LUT_1D_SIZE 17\nDOMAIN_MIN 0 0.1 0\nDOMAIN_MAX 1 0.9 2\n");
|
||
for index in 0..17 {
|
||
let value = index as f32 / 16.;
|
||
one_dimensional += &format!("{} {} {}\n", value.powf(1.6), value.sqrt(), 1. - value);
|
||
}
|
||
|
||
// A 3DL file with blue varying fastest, and an input line uneven enough to shape the values before its 12-bit table
|
||
let mut three_dl = (0..17).map(|index| ((index as f32 / 16.).powf(1.5) * 1023.).round().to_string()).collect::<Vec<_>>().join(" ") + "\nMesh 3 12\n";
|
||
for [b, g, r] in grid(9) {
|
||
let [r, g, b] = [1. - r * 0.6, (g + b) / 2., b * b].map(|value: f32| (value * 4095.).round());
|
||
three_dl += &format!("{r} {g} {b}\n");
|
||
}
|
||
|
||
// A CSP file with piecewise input curves, one of them an identity of no points
|
||
let mut csp = String::from("CSPLUTV100\n3D\n\n5\n0 0.2 0.5 0.8 1\n0 0.3 0.6 0.85 1\n1\n3\n0 0.5 1\n0 0.4 1\n5 5 5\n");
|
||
for [r, g, b] in grid(5) {
|
||
csp += &format!("{} {} {}\n", 1. - g, (r + b) / 2., r * g);
|
||
}
|
||
|
||
let lookup = |file: Vec<u8>| {
|
||
let lut_file = graphene_resource::Resource::new(file);
|
||
assert!(raster_kernels::color_lookup_table::parse_cached(&lut_file).is_ok(), "A test's table isn't readable");
|
||
Adjustment::ColorLookup { lut_file }
|
||
};
|
||
let cube = lookup(cube.into_bytes());
|
||
let device_link = lookup(icc_device_link_profile(3));
|
||
let standard_lab = lookup(icc_standard_lab_profile());
|
||
|
||
// Channels outside 0 to 1 coming into the tables, and a negative one raised to an integer power after one
|
||
let out_of_gamut = lookup(b"LUT_1D_SIZE 2\n-0.6 -0.6 -0.6\n1.7 1.7 1.7\n".to_vec());
|
||
let negative_red = lookup(b"LUT_1D_SIZE 2\n-1 0.5 0.5\n-1 0.5 0.5\n".to_vec());
|
||
|
||
let mut runs = vec![
|
||
("Color Lookup of a CUBE file", vec![cube.clone()]),
|
||
("Color Lookup of a 33-point CUBE file", vec![lookup(cube_of_size(33).into_bytes())]),
|
||
("Color Lookup of a one-dimensional CUBE file with a domain", vec![lookup(one_dimensional.into_bytes())]),
|
||
("Color Lookup of a 3DL file with a shaper", vec![lookup(three_dl.into_bytes())]),
|
||
("Color Lookup of a CSP file", vec![lookup(csp.into_bytes())]),
|
||
("Color Lookup of an abstract ICC profile", vec![lookup(icc_abstract_profile())]),
|
||
("Color Lookup of an abstract ICC profile in standard Lab without a grid", vec![standard_lab.clone()]),
|
||
("Color Lookup of a device link ICC profile", vec![device_link.clone()]),
|
||
// A grid of more texels than 16 bits count, which the stages after it lie past
|
||
("Color Lookup of a device link ICC profile with a 65-point grid", vec![lookup(icc_device_link_profile(65))]),
|
||
("Color Lookup of one CUBE file twice over", vec![cube.clone(), cube.clone()]),
|
||
("Color Lookups of a CUBE file out of gamut", vec![out_of_gamut.clone(), cube]),
|
||
("Color Lookups of a device link ICC profile out of gamut", vec![out_of_gamut.clone(), device_link]),
|
||
("Color Lookups of a standard Lab ICC profile out of gamut", vec![out_of_gamut, standard_lab]),
|
||
(
|
||
"Color Lookup to negative red, then Gamma Correction",
|
||
vec![negative_red, Adjustment::GammaCorrection { gamma: 0.5, inverse: false }],
|
||
),
|
||
];
|
||
|
||
// A table with steps after it, which share the texture of the steps while the table has its own
|
||
let record = |shadows, midtones, highlights, output_minimums, output_maximums| graphic_types::adjustment::LevelsRecord {
|
||
shadows,
|
||
midtones,
|
||
highlights,
|
||
output_minimums,
|
||
output_maximums,
|
||
};
|
||
let identity = record(0., 1., 100., 0., 100.);
|
||
let levels = Adjustment::Levels(Box::new(graphic_types::adjustment::LevelsSettings {
|
||
composite: record(8., 1.3, 93., 2., 97.),
|
||
red: identity,
|
||
green: identity,
|
||
blue: identity,
|
||
alpha: identity,
|
||
}));
|
||
let curves = Adjustment::Curves(Box::new(graphic_types::adjustment::CurvesSettings {
|
||
composite: core_types::transfer_curve::TransferCurve::new(vec![glam::DVec2::ZERO, glam::DVec2::new(0.4, 0.3), glam::DVec2::ONE]),
|
||
..Default::default()
|
||
}));
|
||
runs.push(("Color Lookup of a 17-point CUBE file, Levels, then Curves", vec![lookup(cube_of_size(17).into_bytes()), levels, curves]));
|
||
|
||
assert_gpu_adjustments_match_the_cpu_kernels(runs);
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_runs_of_several_adjustments_match_the_cpu_kernels() {
|
||
use core_types::Color;
|
||
use core_types::blending::BlendMode;
|
||
use core_types::list::Item;
|
||
use core_types::transfer_curve::TransferCurve;
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::*;
|
||
use graphic_types::vector_types::Gradient;
|
||
|
||
let record = |shadows, midtones, highlights| LevelsRecord {
|
||
shadows,
|
||
midtones,
|
||
highlights,
|
||
output_minimums: 0.,
|
||
output_maximums: 100.,
|
||
};
|
||
let identity = record(0., 1., 100.);
|
||
let levels = Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite: record(10., 1.4, 90.),
|
||
red: identity,
|
||
green: record(5., 0.8, 100.),
|
||
blue: identity,
|
||
alpha: LevelsRecord { output_maximums: 60., ..identity },
|
||
}));
|
||
let curves = Adjustment::Curves(Box::new(CurvesSettings {
|
||
composite: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.3, 0.45), DVec2::ONE]),
|
||
..Default::default()
|
||
}));
|
||
let gradient_map = Adjustment::GradientMap {
|
||
gradient: Item::new_from_element(Gradient::from(vec![Color::from_rgbaf32_unchecked(0.1, 0., 0.4, 1.), Color::from_rgbaf32_unchecked(1., 0.8, 0.2, 1.)])),
|
||
reverse: false,
|
||
};
|
||
let overlay = Adjustment::ColorOverlay {
|
||
color: Color::from_gamma_srgb_channels(0.2, 0.5, 0.9, 1.),
|
||
blend_mode: BlendMode::SoftLight,
|
||
opacity: 60.,
|
||
};
|
||
let exposure = Adjustment::Exposure {
|
||
exposure: 0.5,
|
||
offset: 0.,
|
||
gamma_correction: 1.2,
|
||
};
|
||
let vibrance = Adjustment::Vibrance { vibrance: 60., saturation: 20. };
|
||
let posterize = Adjustment::Posterize { levels: 5 };
|
||
let channel_mixer = Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||
monochrome: false,
|
||
monochrome_mix: Default::default(),
|
||
red: ChannelMixerRow {
|
||
red: 70.,
|
||
green: 30.,
|
||
..Default::default()
|
||
},
|
||
green: ChannelMixerRow { green: 100., ..Default::default() },
|
||
blue: ChannelMixerRow {
|
||
blue: 80.,
|
||
constant: 10.,
|
||
..Default::default()
|
||
},
|
||
}));
|
||
let threshold = Adjustment::Threshold {
|
||
min_luminance: 37.3,
|
||
max_luminance: 88.1,
|
||
};
|
||
let unreadable_lookup = Adjustment::ColorLookup {
|
||
lut_file: graphene_resource::Resource::new(b"not a table".to_vec()),
|
||
};
|
||
|
||
// White passes through Color Balance as white, which a Threshold up to 100% keeps and a Color Burn of black leaves alone
|
||
let color_balance = Adjustment::ColorBalance(ColorBalanceSettings {
|
||
midtones: ColorBalanceShifts {
|
||
cyan_red: 10.,
|
||
magenta_green: -20.,
|
||
yellow_blue: 5.,
|
||
},
|
||
preserve_luminosity: true,
|
||
..Default::default()
|
||
});
|
||
let threshold_to_white = Adjustment::Threshold {
|
||
min_luminance: 50.,
|
||
max_luminance: 100.,
|
||
};
|
||
let color_burn = Adjustment::ColorOverlay {
|
||
color: Color::BLACK,
|
||
blend_mode: BlendMode::ColorBurn,
|
||
opacity: 100.,
|
||
};
|
||
|
||
// An alpha curve emptying the faintest pixels, which nothing after it fills back in
|
||
let emptying_curves = Adjustment::Curves(Box::new(CurvesSettings {
|
||
alpha: TransferCurve::new(vec![DVec2::new(0.4, 0.), DVec2::ONE]),
|
||
..Default::default()
|
||
}));
|
||
|
||
// A Color Lookup leaving colors as they are, in a pass of its own
|
||
let identity_lookup = Adjustment::ColorLookup {
|
||
lut_file: graphene_resource::Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec()),
|
||
};
|
||
|
||
let runs = vec![
|
||
(
|
||
"Levels, Curves, Color Overlay, then Gradient Map",
|
||
vec![levels.clone(), curves.clone(), overlay.clone(), gradient_map.clone()],
|
||
),
|
||
("Exposure, Vibrance, Invert, then Posterize", vec![exposure.clone(), vibrance.clone(), Adjustment::Invert, posterize]),
|
||
(
|
||
"Levels fading alpha, Make Opaque, Channel Mixer, then Threshold",
|
||
vec![levels.clone(), Adjustment::MakeOpaque { strength: 100. }, channel_mixer.clone(), threshold],
|
||
),
|
||
("Vibrance, an unreadable Color Lookup, then Curves", vec![vibrance.clone(), unreadable_lookup.clone(), curves.clone()]),
|
||
("an unreadable Color Lookup alone", vec![unreadable_lookup]),
|
||
("Gradient Map, Color Overlay, then Exposure", vec![gradient_map.clone(), overlay.clone(), exposure.clone()]),
|
||
("Color Balance, then Threshold up to white", vec![color_balance.clone(), threshold_to_white.clone()]),
|
||
(
|
||
"Color Balance at its defaults, then Threshold up to white",
|
||
vec![Adjustment::ColorBalance(Default::default()), threshold_to_white],
|
||
),
|
||
("Color Balance, then a Color Burn of black", vec![color_balance, color_burn]),
|
||
(
|
||
"Curves emptying faint pixels, then Make Opaque",
|
||
vec![emptying_curves.clone(), Adjustment::MakeOpaque { strength: 100. }, Adjustment::Invert],
|
||
),
|
||
// The pass emptying a pixel ends before the Color Lookup's own pass, and the one after it with Make Opaque still leaves the pixel empty
|
||
(
|
||
"Curves emptying faint pixels, then a Color Lookup and Make Opaque",
|
||
vec![emptying_curves, identity_lookup, Adjustment::MakeOpaque { strength: 100. }],
|
||
),
|
||
];
|
||
assert_gpu_adjustments_stray_at_most(0.3, runs, &[1., 0.5]);
|
||
|
||
// Passes on either side of each Gradient Map, each reading the result of the one before unrounded
|
||
let chained = vec![gradient_map.clone(), curves, channel_mixer, gradient_map, vibrance];
|
||
assert_gpu_adjustments_stray_at_most(0.3, vec![("Gradient Map, Curves, Channel Mixer, Gradient Map, then Vibrance", chained)], &[1., 0.5]);
|
||
}
|
||
|
||
#[test]
|
||
fn passes_of_a_split_run_hand_on_their_results_unrounded() {
|
||
use core_types::transfer_curve::TransferCurve;
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::*;
|
||
|
||
// A Color Lookup leaving colors as they are, in a pass of its own that splits the run around it
|
||
let split = Adjustment::ColorLookup {
|
||
lut_file: graphene_resource::Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec()),
|
||
};
|
||
let record = |shadows, highlights, output_maximums| LevelsRecord {
|
||
shadows,
|
||
midtones: 1.,
|
||
highlights,
|
||
output_minimums: 0.,
|
||
output_maximums,
|
||
};
|
||
let identity = record(0., 100., 100.);
|
||
let levels = |composite, alpha| {
|
||
Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite,
|
||
red: identity,
|
||
green: identity,
|
||
blue: identity,
|
||
alpha,
|
||
}))
|
||
};
|
||
|
||
// A slight bend leaving tones between those half floats hold, then a tenfold stretch of the middle tones that would show their rounding ten times over
|
||
let bend = Adjustment::GammaCorrection { gamma: 1.1, inverse: false };
|
||
let steep = vec![bend, split.clone(), levels(record(45., 55., 100.), identity)];
|
||
|
||
// A gray just over a Threshold's cutoff, where rounding it to a half float either way (as GPUs differ in) would land under it
|
||
let just_over_cutoff = Adjustment::Curves(Box::new(CurvesSettings {
|
||
composite: TransferCurve::new(vec![DVec2::new(0., 0.5002), DVec2::new(1., 0.5002)]),
|
||
..Default::default()
|
||
}));
|
||
let threshold = Adjustment::Threshold {
|
||
min_luminance: 50.01,
|
||
max_luminance: 100.,
|
||
};
|
||
let cutoff = vec![just_over_cutoff, split.clone(), threshold];
|
||
|
||
// An alpha too faint for a half float to hold, which Make Opaque then lifts
|
||
let faint = levels(identity, record(0., 100., 2e-6));
|
||
let lifted = vec![faint, split, Adjustment::MakeOpaque { strength: 100. }];
|
||
|
||
// Grays a 4096th apart, hundreds of which land within the stretch
|
||
let grays: Vec<core_types::Color> = (0..=4096)
|
||
.map(|level| level as f32 / 4096.)
|
||
.map(|gray| core_types::Color::from_gamma_srgb_channels(gray, gray, gray, 1.))
|
||
.collect();
|
||
|
||
let mut strays = Vec::new();
|
||
for (name, run) in [("a steep Levels", steep), ("a Threshold", cutoff), ("Make Opaque", lifted)] {
|
||
// Each run takes three passes, the last of them holding the step that would reveal any rounding
|
||
let references: Vec<&Adjustment> = run.iter().collect();
|
||
let steps = raster_kernels::adjustment_steps::AdjustmentSteps::encode(&references);
|
||
assert_eq!(crate::vello_adjustments::pass_steps(steps.kinds()), [0..1, 1..2, 2..3], "{name}");
|
||
|
||
let Some((levels, worst_pixel)) = gpu_adjustment_deviation(&run, &grays, 1.) else { return };
|
||
println!("{name} after two passes: {levels:.3} levels");
|
||
if levels > 0.3 {
|
||
strays.push(format!("{name} after two passes strays from the CPU's kernels by {levels} levels, adjusting {worst_pixel}"));
|
||
}
|
||
}
|
||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_adjustments_of_8_bit_content_match_the_cpu_kernels_at_the_edges_of_their_steps() {
|
||
use graphic_types::adjustment::*;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
// Every 8-bit gray as one opaque pixel, rendered as exactly that level
|
||
let size = UVec2::splat(16);
|
||
let square = Rect::new(0., 0., 16., 16.);
|
||
let draw_grays = |scene: &mut VelloSceneBuilder| {
|
||
for level in 0..=255_u8 {
|
||
let (x, y) = (f64::from(level % 16), f64::from(level / 16));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgba8(level, level, level, 255), None, &Rect::new(x, y, x + 1., y + 1.));
|
||
}
|
||
};
|
||
|
||
// Grays landing exactly on the edges between posterized levels, on the pivot of a full contrast, and at a Levels input bound
|
||
let record = |shadows, highlights| LevelsRecord {
|
||
shadows,
|
||
midtones: 1.,
|
||
highlights,
|
||
output_minimums: 0.,
|
||
output_maximums: 100.,
|
||
};
|
||
let levels = |shadows, highlights| {
|
||
Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite: record(shadows, highlights),
|
||
red: record(0., 100.),
|
||
green: record(0., 100.),
|
||
blue: record(0., 100.),
|
||
alpha: record(0., 100.),
|
||
}))
|
||
};
|
||
let mut cases: Vec<(String, Adjustment)> = [2, 3, 5, 7, 255]
|
||
.into_iter()
|
||
.map(|levels| (format!("Posterize to {levels} levels"), Adjustment::Posterize { levels }))
|
||
.collect();
|
||
for pivot in [0., 64., 100., 127., 128., 191., 255.] {
|
||
let contrast = Adjustment::BrightnessContrast {
|
||
brightness: 0.,
|
||
contrast: 100.,
|
||
use_classic: true,
|
||
classic_pivot: pivot,
|
||
};
|
||
cases.push((format!("Brightness/Contrast classic at full contrast about {pivot}"), contrast));
|
||
}
|
||
for (shadows, highlights) in [(40., 100.), (41., 100.), (0., 40.), (0., 41.)] {
|
||
cases.push((format!("Levels from {shadows}% to {highlights}%"), levels(shadows, highlights)));
|
||
}
|
||
|
||
// Thresholds bounded exactly at a gray, which lies within them
|
||
for level in [1_u8, 64, 127, 128, 200, 254, 255] {
|
||
let bound = f64::from(level) / 255. * 100.;
|
||
let threshold = |min_luminance, max_luminance| Adjustment::Threshold { min_luminance, max_luminance };
|
||
cases.push((format!("Threshold from gray {level}"), threshold(bound, 100.)));
|
||
cases.push((format!("Threshold up to gray {level}"), threshold(0., bound)));
|
||
}
|
||
|
||
let mut strays = Vec::new();
|
||
for (name, adjustment) in cases {
|
||
let effects = Effects::from_operations([EffectOperation::Adjustment(adjustment.clone())]);
|
||
let Some(pixels) = render(size, |scene| {
|
||
scene.draw_effects(
|
||
&effects,
|
||
1.,
|
||
1.,
|
||
core_types::blending::BlendMode::Normal,
|
||
true,
|
||
Some(square),
|
||
DAffine2::IDENTITY,
|
||
None,
|
||
&mut |_, _| {},
|
||
&mut |scene| draw_grays(scene),
|
||
)
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
let mut grays: Vec<core_types::Color> = (0..=255)
|
||
.map(|level| core_types::Color::from_gamma_srgb_channels(level as f32 / 255., level as f32 / 255., level as f32 / 255., 1.))
|
||
.collect();
|
||
raster_kernels::adjustments::adjust_colors(&adjustment, &mut grays);
|
||
|
||
let mut worst = (0_f32, 0);
|
||
for (level, gray) in grays.iter().enumerate() {
|
||
let gpu = pixel(&pixels, size, level as u32 % 16, level as u32 / 16)[0] as f32;
|
||
let deviation = (gpu - gray.to_gamma_srgb_channels()[0] * 255.).abs();
|
||
if deviation > worst.0 {
|
||
worst = (deviation, level);
|
||
}
|
||
}
|
||
println!("{name}: {:.3} levels", worst.0);
|
||
|
||
// The rendered level is rounded, after passing through a half float
|
||
if worst.0 > 0.7 {
|
||
strays.push(format!("{name} strays from the CPU's kernel by {} levels at gray {}", worst.0, worst.1));
|
||
}
|
||
}
|
||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||
}
|
||
|
||
#[test]
|
||
fn steep_adjustments_of_smooth_gradients_stay_smooth() {
|
||
use graphic_types::adjustment::*;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
// Levels stretching the middle fifth of the tones across all of them brings out any rounding of the content before it
|
||
let record = |shadows, highlights| LevelsRecord {
|
||
shadows,
|
||
midtones: 1.,
|
||
highlights,
|
||
output_minimums: 0.,
|
||
output_maximums: 100.,
|
||
};
|
||
let identity = record(0., 100.);
|
||
let levels = Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite: record(40., 60.),
|
||
red: identity,
|
||
green: identity,
|
||
blue: identity,
|
||
alpha: identity,
|
||
}));
|
||
let effects = Effects::from_operations([EffectOperation::Adjustment(levels)]);
|
||
|
||
let width = 1024_u32;
|
||
let size = UVec2::new(width, 8);
|
||
let bounds = Rect::new(0., 0., f64::from(width), 8.);
|
||
let gradient = peniko::Gradient::new_linear((0., 0.), (f64::from(width), 0.)).with_stops([Color::BLACK, Color::WHITE]);
|
||
|
||
// A layer just short of opaque is drawn in an intermediate texture of its own
|
||
for in_layer in [false, true] {
|
||
let Some(pixels) = render(size, |scene| {
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(bounds), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
if in_layer {
|
||
scene.push_layer(Fill::NonZero, peniko::Mix::Normal, 0.999, Affine::IDENTITY, &bounds);
|
||
}
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, &gradient, None, &bounds);
|
||
if in_layer {
|
||
scene.pop_layer();
|
||
}
|
||
});
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// The stretched tones climb about 1.25 levels a pixel, where content rounded to 8 bits would climb 5 levels every 4 pixels
|
||
let ramp: Vec<i32> = (0..width).map(|x| i32::from(pixel(&pixels, size, x, 4)[0])).filter(|&value| value > 5 && value < 250).collect();
|
||
let largest_step = ramp.windows(2).map(|pair| (pair[1] - pair[0]).abs()).max().unwrap_or(0);
|
||
let mut distinct = ramp.clone();
|
||
distinct.dedup();
|
||
assert!(
|
||
largest_step <= 2 && distinct.len() * 10 >= ramp.len() * 9,
|
||
"the gradient (in a layer: {in_layer}) bands, climbing by up to {largest_step} levels through {} distinct levels across {} pixels",
|
||
distinct.len(),
|
||
ramp.len()
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_adjustments_that_keep_white_do_not_carry_it_past_white() {
|
||
use graphic_types::adjustment::*;
|
||
use half::f16;
|
||
|
||
let identity = LevelsRecord {
|
||
shadows: 0.,
|
||
midtones: 1.,
|
||
highlights: 100.,
|
||
output_minimums: 0.,
|
||
output_maximums: 100.,
|
||
};
|
||
let levels = |midtones| {
|
||
Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite: LevelsRecord { midtones, ..identity },
|
||
red: identity,
|
||
green: identity,
|
||
blue: identity,
|
||
alpha: identity,
|
||
}))
|
||
};
|
||
let color_balance = |cyan_red| {
|
||
Adjustment::ColorBalance(ColorBalanceSettings {
|
||
midtones: ColorBalanceShifts { cyan_red, ..Default::default() },
|
||
preserve_luminosity: true,
|
||
..Default::default()
|
||
})
|
||
};
|
||
let cases = [
|
||
("Levels", levels(1.)),
|
||
("Levels with bent midtones", levels(1.2)),
|
||
("Color Balance", color_balance(0.)),
|
||
("Color Balance with shifted midtones", color_balance(10.)),
|
||
("Curves", Adjustment::Curves(Default::default())),
|
||
("Posterize", Adjustment::Posterize { levels: 4 }),
|
||
(
|
||
"Exposure",
|
||
Adjustment::Exposure {
|
||
exposure: 0.,
|
||
offset: 0.,
|
||
gamma_correction: 1.,
|
||
},
|
||
),
|
||
(
|
||
"Brightness/Contrast",
|
||
Adjustment::BrightnessContrast {
|
||
brightness: 0.,
|
||
contrast: 0.,
|
||
use_classic: false,
|
||
classic_pivot: 127.,
|
||
},
|
||
),
|
||
("Hue/Saturation", Adjustment::HueSaturation(Default::default())),
|
||
("Selective Color", Adjustment::SelectiveColor(Default::default())),
|
||
("Gamma Correction", Adjustment::GammaCorrection { gamma: 2.2, inverse: false }),
|
||
("Vibrance", Adjustment::Vibrance { vibrance: 20., saturation: 0. }),
|
||
(
|
||
"Photo Filter",
|
||
Adjustment::PhotoFilter {
|
||
color: core_types::Color::WHITE,
|
||
density: 25.,
|
||
preserve_luminosity: false,
|
||
},
|
||
),
|
||
];
|
||
|
||
// White, opaque and translucent, as premultiplied half floats
|
||
let whites = [[1.; 4], [0.5; 4]].map(|texel: [f32; 4]| texel.map(f16::from_f32));
|
||
|
||
// A half float rounds a channel left a hair past 1 back to 1, hiding it, but its inverse falls below zero where the sign shows
|
||
for (name, adjustment) in cases {
|
||
let Some(inverted) = gpu_adjusted_texels(&[adjustment, Adjustment::Invert], &whites, 1.) else {
|
||
return;
|
||
};
|
||
|
||
for [red, green, blue, _] in inverted {
|
||
for channel in [red, green, blue] {
|
||
assert!(channel.is_sign_positive() && channel < 1e-3, "{name} leaves white at {channel} once inverted");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn adjustments_leave_the_empty_space_around_content_empty() {
|
||
use core_types::transfer_curve::TransferCurve;
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::*;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::splat(128);
|
||
let bounds = Rect::new(40., 40., 88., 88.);
|
||
let identity = LevelsRecord {
|
||
shadows: 0.,
|
||
midtones: 1.,
|
||
highlights: 100.,
|
||
output_minimums: 0.,
|
||
output_maximums: 100.,
|
||
};
|
||
|
||
// Adjustments raising alpha, the last after a curve that empties everything first
|
||
let raised_alpha = Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite: identity,
|
||
red: identity,
|
||
green: identity,
|
||
blue: identity,
|
||
alpha: LevelsRecord { output_minimums: 50., ..identity },
|
||
}));
|
||
let emptied = Adjustment::Curves(Box::new(CurvesSettings {
|
||
alpha: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.)]),
|
||
..Default::default()
|
||
}));
|
||
let make_opaque = |strength| Adjustment::MakeOpaque { strength };
|
||
let cases = [
|
||
("Make Opaque", vec![make_opaque(100.)], 255),
|
||
("Make Opaque at half strength", vec![make_opaque(50.)], 255),
|
||
("Levels with a raised alpha output", vec![raised_alpha], 255),
|
||
("Curves emptying alpha, then Make Opaque", vec![emptied, make_opaque(100.)], 0),
|
||
];
|
||
|
||
for (name, run, alpha_within) in cases {
|
||
let effects = Effects::from_operations(run.into_iter().map(EffectOperation::Adjustment));
|
||
let Some(pixels) = render(size, |scene| {
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(bounds), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, RED, None, &circle((64., 64.), 20.))
|
||
});
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// The content keeps its own alpha as adjusted, and the corner of its bounds outside it (like everything past them) holds nothing
|
||
assert_eq!(pixel(&pixels, size, 64, 64)[3], alpha_within, "{name} within the content");
|
||
assert_eq!(pixel(&pixels, size, 42, 42), [0; 4], "{name} within the content's bounds");
|
||
assert_eq!(pixel(&pixels, size, 4, 4), [0; 4], "{name} past the content's bounds");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn grained_glows_match_the_cpu_zoomed_in_and_out() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use core_types::transfer_curve::TransferCurve;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||
use graphic_types::{EffectOperation, Effects, GlowSource, GlowTechnique, Graphic};
|
||
use raster_kernels::evaluate_raster_effects;
|
||
|
||
let (min, max) = (24., 56.);
|
||
let stop = |position, color| GradientStop { position, midpoint: 0.5, color };
|
||
let fading = Graphic::from(Gradient::new([
|
||
stop(0., GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 1.)),
|
||
stop(1., GraphicColor::from_rgbaf32_unchecked(0.2, 0., 0.6, 0.3)),
|
||
]));
|
||
let transparent = Graphic::from(Gradient::new([
|
||
stop(0., GraphicColor::from_rgbaf32_unchecked(0.9, 0.1, 0.3, 0.)),
|
||
stop(1., GraphicColor::from_rgbaf32_unchecked(0.1, 0.6, 0.9, 0.)),
|
||
]));
|
||
let glows = [
|
||
EffectOperation::OuterGlow {
|
||
color: GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75).into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
spread: 30.,
|
||
size: 8.,
|
||
range: 100.,
|
||
contour: TransferCurve::default(),
|
||
noise: 60.,
|
||
jitter: 0.,
|
||
seed: 2,
|
||
},
|
||
EffectOperation::InnerGlow {
|
||
color: fading,
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
source: GlowSource::Edge,
|
||
choke: 0.,
|
||
size: 8.,
|
||
range: 100.,
|
||
contour: TransferCurve::default(),
|
||
noise: 40.,
|
||
jitter: 50.,
|
||
seed: 0,
|
||
},
|
||
// Shown only by its noise, with its colors jittered
|
||
EffectOperation::OuterGlow {
|
||
color: transparent,
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
spread: 50.,
|
||
size: 8.,
|
||
range: 100.,
|
||
contour: TransferCurve::default(),
|
||
noise: 100.,
|
||
jitter: 40.,
|
||
seed: 5,
|
||
},
|
||
// Noise too slight to change anything in 32-bit floats
|
||
EffectOperation::OuterGlow {
|
||
color: GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75).into(),
|
||
blend_mode: BlendMode::Normal,
|
||
technique: GlowTechnique::Precise,
|
||
spread: 100.,
|
||
size: 8.,
|
||
range: 100.,
|
||
contour: TransferCurve::default(),
|
||
noise: 0.000001,
|
||
jitter: 0.,
|
||
seed: 2,
|
||
},
|
||
];
|
||
|
||
let zooms = [
|
||
// Twice and half as many pixels as document pixels, with the render's corner at negative document pixels so the grain's cells there are negative too
|
||
(2., DVec2::new(10., 6.), 160),
|
||
(0.5, DVec2::new(4., 2.), 48),
|
||
// An eighth as many, where each pixel spans more grain than it samples
|
||
(0.125, DVec2::new(3., 2.), 16),
|
||
// The render cutting off the content's upper left, so it starts partway into the grain
|
||
(2., DVec2::new(-70., -60.), 160),
|
||
];
|
||
for (scale, offset, side) in zooms {
|
||
for glow in glows.clone() {
|
||
let effects = Effects::from_operations([glow.clone()]);
|
||
let size = UVec2::splat(side);
|
||
let square = Rect::new(min, min, max, max);
|
||
// The grain lies in the effect space, which has its origin at the content's, the square's corner
|
||
let effect_space = DAffine2::from_translation(DVec2::splat(min));
|
||
let Some(gpu) = render(size, |scene| {
|
||
scene.draw_placed(Affine::translate((offset.x, offset.y)) * Affine::scale(scale), |scene| {
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), effect_space, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||
});
|
||
});
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// The same square as a raster at the same pixels per document pixel
|
||
let pixels = ((max - min) * scale) as u32;
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(pixels, pixels, GraphicColor::WHITE)))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(min)) * DAffine2::from_scale(DVec2::splat(max - min)));
|
||
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(&glow));
|
||
let evaluated = evaluate_raster_effects(item);
|
||
let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||
let raster = evaluated.element();
|
||
let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse();
|
||
|
||
let mut worst = 0;
|
||
for y in 0..size.y {
|
||
for x in 0..size.x {
|
||
let document = (DVec2::new(x as f64 + 0.5, y as f64 + 0.5) - offset) / scale;
|
||
let point = document_to_pixels.transform_point2(document).floor();
|
||
let inside = point.x >= 0. && point.y >= 0. && point.x < raster.width as f64 && point.y < raster.height as f64;
|
||
let cpu = match inside {
|
||
true => {
|
||
let [red, green, blue, alpha] = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize].to_gamma_srgb_channels();
|
||
[red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.)
|
||
}
|
||
false => [0.; 4],
|
||
};
|
||
|
||
let gpu = pixel(&gpu, size, x, y);
|
||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||
for channel in 0..4 {
|
||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||
worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32);
|
||
}
|
||
}
|
||
}
|
||
assert!(worst <= 2, "{effects:?} at {scale} pixels per document pixel differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn soft_chisels_on_translucent_content_match_the_cpu() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, stamp_effect};
|
||
use raster_kernels::evaluate_raster_effects;
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let (min, max) = (50, 110);
|
||
// Partial coverage gives every pixel inside a head start short of the whole slope, so seeds of differing values meet
|
||
let alpha = 140. / 255.;
|
||
|
||
for (style, bevel_size) in [(BevelStyle::InnerBevel, 10.), (BevelStyle::Emboss, 12.), (BevelStyle::OuterBevel, 8.), (BevelStyle::InnerBevel, 40.)] {
|
||
let mut bevel = EffectOperation::default_for(EffectKind::BevelAndEmboss);
|
||
if let EffectOperation::BevelAndEmboss {
|
||
style: bevel_style,
|
||
technique,
|
||
size: bevel_width,
|
||
highlight_color,
|
||
shadow_color,
|
||
..
|
||
} = &mut bevel
|
||
{
|
||
(*bevel_style, *technique, *bevel_width) = (style, BevelTechnique::ChiselSoft, bevel_size);
|
||
(*highlight_color, *shadow_color) = (GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 0.75), GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75));
|
||
}
|
||
let effects = Effects::from_operations([bevel.clone()]);
|
||
|
||
let square = Rect::new(min as f64, min as f64, max as f64, max as f64);
|
||
let Some(gpu) = render(size, |scene| {
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE.with_alpha(alpha), None, &square)
|
||
});
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// The same square as a raster covering the render one pixel to one pixel
|
||
let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT);
|
||
for y in min..max {
|
||
for x in min..max {
|
||
image.data[(y * size.x + x) as usize] = GraphicColor::WHITE.with_alpha(alpha);
|
||
}
|
||
}
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2()));
|
||
stamp_effect(&mut item, Effect::new(&bevel));
|
||
let evaluated = evaluate_raster_effects(item);
|
||
let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||
let raster = evaluated.element();
|
||
let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse();
|
||
|
||
let mut worst = 0;
|
||
for y in 0..size.y {
|
||
for x in 0..size.x {
|
||
let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor();
|
||
let [red, green, blue, cpu_alpha] = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize].to_gamma_srgb_channels();
|
||
let cpu = [red * cpu_alpha, green * cpu_alpha, blue * cpu_alpha, cpu_alpha].map(|channel| channel * 255.);
|
||
|
||
let gpu = pixel(&gpu, size, x, y);
|
||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||
for channel in 0..4 {
|
||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||
worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32);
|
||
}
|
||
}
|
||
}
|
||
assert!(worst <= 2, "a soft {style:?} of {bevel_size} on translucent content differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn adjustments_on_image_textures_and_through_effects_groups_match_the_cpu_kernels() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use graphic_types::adjustment::*;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::Gradient;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
// Opaque colors spread across the RGB cube, one per pixel, on whole 8-bit levels as the content's 8-bit render holds them
|
||
let size = UVec2::new(64, 64);
|
||
let channel = |value: u32| ((value % 64) * 4) as f32 / 255.;
|
||
let colors: Vec<GraphicColor> = (0..size.x * size.y)
|
||
.map(|index| GraphicColor::from_gamma_srgb_channels(channel(index % 64), channel(index / 64), channel(index * 7 + index / 64 * 13), 1.))
|
||
.collect();
|
||
let raster = Raster::new_cpu(Image {
|
||
width: size.x,
|
||
height: size.y,
|
||
data: colors.clone(),
|
||
});
|
||
|
||
let record = |shadows, midtones, highlights| LevelsRecord {
|
||
shadows,
|
||
midtones,
|
||
highlights,
|
||
output_minimums: 0.,
|
||
output_maximums: 100.,
|
||
};
|
||
let identity = record(0., 1., 100.);
|
||
let levels = Adjustment::Levels(Box::new(LevelsSettings {
|
||
composite: record(10., 1.4, 90.),
|
||
red: identity,
|
||
green: record(5., 0.8, 100.),
|
||
blue: identity,
|
||
alpha: identity,
|
||
}));
|
||
let hue_saturation = Adjustment::HueSaturation(Box::new(HueSaturationSettings {
|
||
master: HueSaturationSliders {
|
||
hue: 25.,
|
||
saturation: 30.,
|
||
lightness: 5.,
|
||
},
|
||
..Default::default()
|
||
}));
|
||
let gradient_map = Adjustment::GradientMap {
|
||
gradient: Item::new_from_element(Gradient::from(vec![
|
||
GraphicColor::from_rgbaf32_unchecked(0.1, 0., 0.4, 1.),
|
||
GraphicColor::from_rgbaf32_unchecked(1., 0.8, 0.2, 1.),
|
||
])),
|
||
reverse: false,
|
||
};
|
||
let exposure = Adjustment::Exposure {
|
||
exposure: 0.5,
|
||
offset: 0.,
|
||
gamma_correction: 1.2,
|
||
};
|
||
let vibrance = |vibrance, saturation| Adjustment::Vibrance { vibrance, saturation };
|
||
|
||
// Runs of one kind and of several, each in one pass however many kinds it mixes, but for the last, which its Gradient Map splits into three
|
||
let runs = [
|
||
vec![levels.clone(), exposure, Adjustment::Invert],
|
||
vec![hue_saturation, Adjustment::Desaturate { method: DesaturateMethod::LumaRec601 }],
|
||
vec![gradient_map.clone()],
|
||
vec![vibrance(60., 20.)],
|
||
vec![vibrance(40., 0.), Adjustment::Invert],
|
||
vec![Adjustment::Invert, vibrance(-30., 10.), Adjustment::Invert],
|
||
vec![levels, gradient_map, vibrance(30., 10.)],
|
||
];
|
||
|
||
for run in runs {
|
||
let mut expected = colors.clone();
|
||
run.iter().for_each(|adjustment| raster_kernels::adjustments::adjust_colors(adjustment, &mut expected));
|
||
|
||
// Carried out on the rendered content by an effects group, and on the image's own texture as it's drawn
|
||
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
|
||
let through_effects_group = |scene: &mut VelloSceneBuilder| {
|
||
let bounds = Rect::new(0., 0., size.x as f64, size.y as f64);
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(bounds), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.draw_raster(raster.clone(), Vec::new(), peniko::ImageSampler::new(), Affine::IDENTITY)
|
||
});
|
||
};
|
||
let on_image_texture = |scene: &mut VelloSceneBuilder| scene.draw_raster(raster.clone(), run.clone(), peniko::ImageSampler::new(), Affine::IDENTITY);
|
||
let paths = [
|
||
("through an effects group", &through_effects_group as &dyn Fn(&mut VelloSceneBuilder)),
|
||
("on the image's texture", &on_image_texture),
|
||
];
|
||
|
||
// Only the 8-bit rounding of the content and the result separates them
|
||
for (path, draw) in paths {
|
||
let Some(gpu) = render(size, draw) else { return };
|
||
|
||
let mut worst = 0;
|
||
for (index, color) in expected.iter().enumerate() {
|
||
let cpu = color.to_gamma_srgb_channels().map(|channel| (channel * 255.).round() as i32);
|
||
for channel in 0..3 {
|
||
worst = worst.max((cpu[channel] - gpu[index][channel] as i32).unsigned_abs());
|
||
}
|
||
}
|
||
let names = run.iter().map(|adjustment| adjustment.kind().to_string()).collect::<Vec<_>>().join(" + ");
|
||
assert!(worst <= 1, "{names} {path} differs from the CPU kernels by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn minified_images_average_their_pixels() {
|
||
use raster_types::{Image, Raster};
|
||
|
||
// Stripes half black and half white in every eight columns, drawn at an eighth of their size, where sampling only the two
|
||
// columns nearest each pixel's center would find black
|
||
let stripes = Image {
|
||
width: 64,
|
||
height: 64,
|
||
data: (0..64 * 64)
|
||
.map(|index| if (2..6).contains(&(index % 8)) { core_types::Color::BLACK } else { core_types::Color::WHITE })
|
||
.collect(),
|
||
};
|
||
let stripes = Raster::new_cpu(stripes);
|
||
let draw = |scene: &mut VelloSceneBuilder| scene.draw_raster(stripes.clone(), Vec::new(), peniko::ImageSampler::new(), Affine::scale(1. / 8.));
|
||
|
||
let size = UVec2::new(8, 8);
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
for (index, pixel) in pixels.iter().enumerate() {
|
||
assert!(
|
||
(115..=140).contains(&pixel[0]) && pixel[1] == pixel[0] && pixel[2] == pixel[0] && pixel[3] == 255,
|
||
"pixel {index} is {pixel:?} rather than the gray of its average"
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn minified_adjusted_images_sample_their_adjusted_mipmaps() {
|
||
use graphic_types::Adjustment;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
|
||
// Quarters of red, green, blue, and white, inverted and drawn at an eighth of their size where only the smaller levels are sampled, each staying in its quarter
|
||
let quarters = [core_types::Color::RED, core_types::Color::GREEN, core_types::Color::BLUE, core_types::Color::WHITE];
|
||
let quarter = |x: u32, y: u32, size: u32| (x * 2 / size + 2 * (y * 2 / size)) as usize;
|
||
let data = (0..64 * 64).map(|index| quarters[quarter(index % 64, index / 64, 64)]).collect();
|
||
let image = Raster::new_cpu(Image { width: 64, height: 64, data });
|
||
let draw = |scene: &mut VelloSceneBuilder| scene.draw_raster(image.clone(), vec![Adjustment::Invert], peniko::ImageSampler::new(), Affine::scale(1. / 8.));
|
||
|
||
let inverted = [[0, 255, 255, 255], [255, 0, 255, 255], [255, 255, 0, 255], [0, 0, 0, 255]];
|
||
let size = UVec2::new(8, 8);
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
for y in 0..size.y {
|
||
for x in 0..size.x {
|
||
let (actual, expected) = (pixel(&pixels, size, x, y), inverted[quarter(x, y, size.x)]);
|
||
let close = (0..4).all(|channel| actual[channel].abs_diff(expected[channel]) <= 1);
|
||
assert!(close, "pixel ({x}, {y}) is {actual:?} rather than {expected:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn rasters_upload_once_across_scenes_until_modified() {
|
||
use raster_types::{Image, Raster};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
let _turn = take_turn();
|
||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||
let raster = Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE));
|
||
|
||
// Each render draws its scene anew, as the editor does whenever the graph runs
|
||
let scene_drawing = |raster: &Raster<raster_types::CPU>| {
|
||
let mut scene = VelloSceneBuilder::new(64, 64, Affine::IDENTITY, max_texture_size);
|
||
scene.draw_raster(raster.clone(), Vec::new(), peniko::ImageSampler::new(), Affine::scale(8.));
|
||
scene
|
||
};
|
||
|
||
let mut canvas = crate::VelloCanvas::default();
|
||
for _ in 0..3 {
|
||
executor.render_vello_scene_on_canvas(&mut canvas, scene_drawing(&raster)).unwrap();
|
||
}
|
||
assert_eq!(canvas.images.textures.len(), 1, "a clone of the same pixels reuses their texture");
|
||
|
||
let mut modified = raster.clone();
|
||
modified.data_mut().data[0] = core_types::Color::BLACK;
|
||
executor.render_vello_scene_on_canvas(&mut canvas, scene_drawing(&modified)).unwrap();
|
||
assert_eq!(canvas.images.textures.len(), 2, "modified pixels get a texture of their own");
|
||
}
|
||
|
||
#[test]
|
||
fn textures_of_dropped_rasters_are_freed() {
|
||
use raster_types::{Image, Raster};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||
|
||
// Each render draws new pixels and drops the last ones, as dragging a slider on a raster node does
|
||
let mut canvas = crate::VelloCanvas::default();
|
||
for _ in 0..10 {
|
||
let mut scene = VelloSceneBuilder::new(64, 64, Affine::IDENTITY, max_texture_size);
|
||
scene.draw_raster(Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE)), Vec::new(), peniko::ImageSampler::new(), Affine::scale(8.));
|
||
executor.render_vello_scene_on_canvas(&mut canvas, scene).unwrap();
|
||
}
|
||
assert_eq!(canvas.images.textures.len(), 1, "only the texture of pixels that still exist stays");
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_take_gpu_image_radius_masks_through_the_gpus_maps() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_TRANSFORM, Color};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
use wgpu::util::DeviceExt;
|
||
|
||
let Some(executor) = executor() else { return };
|
||
let _turn = take_turn();
|
||
|
||
// A white GPU image, which SVG markup can't draw, bare and in a group
|
||
let descriptor = wgpu::TextureDescriptor {
|
||
label: Some("radius_mask_test_image"),
|
||
size: wgpu::Extent3d {
|
||
width: 2,
|
||
height: 2,
|
||
depth_or_array_layers: 1,
|
||
},
|
||
mip_level_count: 1,
|
||
sample_count: 1,
|
||
dimension: wgpu::TextureDimension::D2,
|
||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC,
|
||
view_formats: &[],
|
||
};
|
||
let texture = {
|
||
let queue = executor.context().queue.lock();
|
||
executor
|
||
.context()
|
||
.device
|
||
.create_texture_with_data(&queue, &descriptor, wgpu::util::TextureDataOrder::LayerMajor, &[255; 16])
|
||
};
|
||
let image = Graphic::from(Item::new_from_element(Raster::new_gpu(texture)));
|
||
let grouped = Graphic::Graphic(Box::new(Item::new_from_element(image.clone())));
|
||
|
||
for radius_mask in [image, grouped] {
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask,
|
||
radius: 4.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(10.)));
|
||
stamp_effect(&mut item, Effect::new(&blur));
|
||
|
||
let mut render = SvgRender::new();
|
||
List::new_from_item(item).render_svg(
|
||
&mut render,
|
||
&RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
},
|
||
);
|
||
assert_eq!(render.effect_maps.len(), 1, "{}", render.svg_defs);
|
||
assert!(!render.svg_defs.contains("luminanceToAlpha"), "{}", render.svg_defs);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_draw_content_with_effects_svg_cannot_express_as_images_the_gpu_renders() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_TRANSFORM, Color};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Adjustment, Effect, EffectOperation, stamp_effect};
|
||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
let _turn = take_turn();
|
||
|
||
// An orange square casting a shadow, with Vibrance draining its color, which no SVG filter can do after the shadow
|
||
let shadow = EffectOperation::DropShadow {
|
||
color: Color::BLACK,
|
||
blend_mode: BlendMode::Multiply,
|
||
angle: 180.,
|
||
distance: 4.,
|
||
spread: 0.,
|
||
size: 0.,
|
||
contour: Default::default(),
|
||
knockout: true,
|
||
};
|
||
let mut item =
|
||
Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::from_gamma_srgb_channels(1., 0.5, 0., 1.)))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(10.)));
|
||
stamp_effect(&mut item, Effect::new(&shadow));
|
||
stamp_effect(&mut item, Effect::new(&EffectOperation::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: -100. })));
|
||
|
||
let mut render = SvgRender::new();
|
||
List::new_from_item(item).render_svg(
|
||
&mut render,
|
||
&RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
},
|
||
);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: UVec2::splat(32),
|
||
..Default::default()
|
||
};
|
||
let rendered = executor.render_deferred_svg_images(&render.deferred_images, footprint);
|
||
|
||
// The square comes out gray, with the shadow beside it
|
||
let [(_, texture)] = &rendered[..] else { panic!("expected one image, got {}", rendered.len()) };
|
||
let pixels = executor.read_texture_pixels(texture).unwrap();
|
||
let width = texture.width() as usize;
|
||
let [red, green, blue, alpha] = pixels[(5 * width + 2) * 4..][..4] else { unreachable!() };
|
||
assert!(
|
||
red.abs_diff(green) <= 2 && green.abs_diff(blue) <= 2 && alpha == 255,
|
||
"expected gray, got {:?}",
|
||
[red, green, blue, alpha]
|
||
);
|
||
assert_eq!(pixels[(5 * width + 12) * 4..][..4], [0, 0, 0, 255], "the shadow");
|
||
|
||
// Its image replaces the markup standing in for it
|
||
let mut svg = render.svg.to_svg_string();
|
||
futures::executor::block_on(executor.resolve_deferred_svg_images(&mut svg, &mut Vec::new(), rendered));
|
||
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
|
||
}
|
||
|
||
#[test]
|
||
fn adjusted_images_remake_one_copy_as_their_adjustments_change() {
|
||
use graphic_types::Adjustment;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
|
||
let Some(executor) = executor() else { return };
|
||
let _turn = take_turn();
|
||
let new_scene = || VelloSceneBuilder::new(64, 64, Affine::IDENTITY, executor.context().device.limits().max_texture_dimension_2d);
|
||
let raster = Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE));
|
||
let exposure = |exposure| Adjustment::Exposure {
|
||
exposure,
|
||
offset: 0.,
|
||
gamma_correction: 1.,
|
||
};
|
||
let copies = |canvas: &crate::VelloCanvas| canvas.images.textures.values().map(|image_texture| image_texture.adjusted.len()).sum::<usize>();
|
||
|
||
// Dragging a slider adjusts the same pixels differently in every render
|
||
let mut canvas = crate::VelloCanvas::default();
|
||
for amount in [0.1, 0.2, 0.3] {
|
||
let mut scene = new_scene();
|
||
scene.draw_raster(raster.clone(), vec![exposure(amount)], peniko::ImageSampler::new(), Affine::scale(8.));
|
||
executor.render_vello_scene_on_canvas(&mut canvas, scene).unwrap();
|
||
}
|
||
assert_eq!(copies(&canvas), 1, "each new run takes over the copy the last render drew");
|
||
|
||
// Two layers sharing the pixels with different adjustments need a copy each
|
||
let mut scene = new_scene();
|
||
scene.draw_raster(raster.clone(), vec![exposure(0.4)], peniko::ImageSampler::new(), Affine::scale(4.));
|
||
scene.draw_raster(raster.clone(), vec![Adjustment::Invert], peniko::ImageSampler::new(), Affine::scale(8.));
|
||
executor.render_vello_scene_on_canvas(&mut canvas, scene).unwrap();
|
||
assert_eq!(copies(&canvas), 2);
|
||
}
|
||
|
||
/// The settings of a noise pattern with features a few units across.
|
||
fn noise_settings() -> graphic_types::generator::NoiseSettings {
|
||
use graphic_types::generator::*;
|
||
|
||
NoiseSettings {
|
||
seed: 11,
|
||
scale: 6.,
|
||
noise_type: NoiseType::OpenSimplex2,
|
||
domain_warp_type: DomainWarpType::None,
|
||
domain_warp_amplitude: 0.,
|
||
fractal_type: FractalType::FBm,
|
||
fractal_octaves: 3,
|
||
fractal_lacunarity: 2.,
|
||
fractal_gain: 0.5,
|
||
fractal_weighted_strength: 0.,
|
||
fractal_ping_pong_strength: 2.,
|
||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||
cellular_return_type: CellularReturnType::Nearest,
|
||
cellular_jitter: 1.,
|
||
}
|
||
}
|
||
|
||
/// A noise pattern with features a few units across.
|
||
fn noise_pattern() -> graphic_types::generator::GeneratorPattern {
|
||
graphic_types::generator::GeneratorPattern::Noise(noise_settings())
|
||
}
|
||
|
||
/// Draws `pattern` with `pixels_per_unit` pixels to a unit, from `origin` in its space, comparing 64 by 64 pixels with the generator's own samples.
|
||
/// Returns how many pixels differ by more than 2 levels and the most any differs by, or `None` without a GPU.
|
||
fn drawing_differences(pattern: &graphic_types::generator::GeneratorPattern, pixels_per_unit: f64, origin: glam::DVec2) -> Option<(usize, u8)> {
|
||
let size = UVec2::new(80, 80);
|
||
let pixels = render(size, |scene| {
|
||
scene.draw_generator(pattern, Affine::translate((8., 8.)) * Affine::scale(pixels_per_unit) * Affine::translate((-origin.x, -origin.y)))
|
||
})?;
|
||
|
||
// The pattern fills the plane, past the area compared
|
||
assert_eq!(pixel(&pixels, size, 2, 2)[3], 255);
|
||
assert_eq!(pixel(&pixels, size, 76, 76)[3], 255);
|
||
|
||
let (expected, _, _) = raster_kernels::generators::render_pattern(pattern, [origin, origin + 64. / pixels_per_unit], 64, 64)
|
||
.unwrap()
|
||
.to_flat_u8();
|
||
let differences: Vec<u8> = (0..64 * 64)
|
||
.map(|index| {
|
||
let drawn = pixel(&pixels, size, index % 64 + 8, index / 64 + 8);
|
||
let sampled = &expected[(index * 4) as usize..][..4];
|
||
(0..3).map(|channel| drawn[channel].abs_diff(sampled[channel])).max().unwrap_or(0)
|
||
})
|
||
.collect();
|
||
|
||
let mismatched = differences.iter().filter(|&&difference| difference > 2).count();
|
||
Some((mismatched, differences.into_iter().max().unwrap_or(0)))
|
||
}
|
||
|
||
#[test]
|
||
fn generators_draw_their_pattern_at_the_resolution_in_view() {
|
||
// Each unit of the pattern drawn across two pixels, so its tiles sample the pattern at every pixel's center
|
||
let Some((_, worst)) = drawing_differences(&noise_pattern(), 2., glam::DVec2::ZERO) else { return };
|
||
assert!(worst <= 2, "the drawn pattern differs from the generator's own samples by up to {worst} levels");
|
||
}
|
||
|
||
#[test]
|
||
fn every_noise_setting_renders_on_the_gpu_like_on_the_cpu() {
|
||
use core_types::choice_type::ChoiceTypeStatic;
|
||
use graphic_types::generator::*;
|
||
|
||
fn every<T: ChoiceTypeStatic + 'static>() -> impl Iterator<Item = T> {
|
||
T::list().iter().flat_map(|section| section.iter().map(|(variant, _)| *variant))
|
||
}
|
||
|
||
// Each noise type, fractal type, and domain warp, and each pairing of the cellular noise's distance function and return type
|
||
let base = || NoiseSettings {
|
||
fractal_type: FractalType::None,
|
||
..noise_settings()
|
||
};
|
||
let warps = [FractalType::None, FractalType::DomainWarpProgressive, FractalType::DomainWarpIndependent];
|
||
let variations = (every::<NoiseType>().map(|noise_type| NoiseSettings { noise_type, ..base() }))
|
||
.chain(every::<FractalType>().map(|fractal_type| NoiseSettings {
|
||
fractal_type,
|
||
fractal_weighted_strength: 0.5,
|
||
..base()
|
||
}))
|
||
.chain(every::<DomainWarpType>().flat_map(|domain_warp_type| {
|
||
warps.map(|fractal_type| NoiseSettings {
|
||
domain_warp_type,
|
||
domain_warp_amplitude: 4.,
|
||
fractal_type,
|
||
..base()
|
||
})
|
||
}))
|
||
.chain(every::<CellularDistanceFunction>().flat_map(|cellular_distance_function| {
|
||
every::<CellularReturnType>().map(move |cellular_return_type| NoiseSettings {
|
||
noise_type: NoiseType::Cellular,
|
||
cellular_distance_function,
|
||
cellular_return_type,
|
||
..base()
|
||
})
|
||
}));
|
||
|
||
// Another GPU's rounding may put a few pixels on the other side of a cell's edge
|
||
for settings in variations {
|
||
let Some((mismatched, _)) = drawing_differences(&GeneratorPattern::Noise(settings.clone()), 2., glam::DVec2::ZERO) else {
|
||
return;
|
||
};
|
||
assert!(mismatched <= 8, "{mismatched} pixels differ from the CPU's samples with {settings:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn every_mandelbrot_setting_renders_on_the_gpu_like_on_the_cpu() {
|
||
use core_types::choice_type::ChoiceTypeStatic;
|
||
use graphic_types::generator::*;
|
||
|
||
fn every<T: ChoiceTypeStatic + 'static>() -> impl Iterator<Item = T> {
|
||
T::list().iter().flat_map(|section| section.iter().map(|(variant, _)| *variant))
|
||
}
|
||
|
||
let GeneratorPattern::Mandelbrot(defaults) = GeneratorPattern::decode(Generator::Mandelbrot, &|_| None) else {
|
||
unreachable!()
|
||
};
|
||
|
||
// A power-of-two scale, so the tiles' pixels line up with the pixels compared at the power-of-two zooms below
|
||
let scale = 1024.;
|
||
|
||
// Each fractal, interior, and exterior, and every other setting away from its default
|
||
let base = || MandelbrotSettings { scale, ..defaults.clone() };
|
||
let variations = (every::<MandelbrotFractal>().map(|fractal| MandelbrotSettings { fractal, ..base() }))
|
||
.chain(every::<MandelbrotExterior>().map(|exterior| MandelbrotSettings { exterior, ..base() }))
|
||
.chain(every::<MandelbrotInterior>().map(|interior| MandelbrotSettings { interior, ..base() }))
|
||
.chain([50., 100.].map(|mandelbrot_to_julia| MandelbrotSettings { mandelbrot_to_julia, ..base() }))
|
||
.chain([3., 2.5].map(|power| MandelbrotSettings { power, ..base() }))
|
||
.chain([32, 1000].map(|iterations| MandelbrotSettings { iterations, ..base() }))
|
||
.chain([MandelbrotSettings {
|
||
mandelbrot_to_julia: 100.,
|
||
julia_slice: glam::DVec2::new(0.285, 0.01),
|
||
..base()
|
||
}])
|
||
.chain([0., 50.].map(|mandelbrot_to_julia| MandelbrotSettings {
|
||
mandelbrot_slice: glam::DVec2::new(0.3, -0.2),
|
||
mandelbrot_to_julia,
|
||
..base()
|
||
}))
|
||
.chain([MandelbrotExterior::Tendrils, MandelbrotExterior::Rays].map(|exterior| MandelbrotSettings { exterior, frequency: 2, ..base() }));
|
||
|
||
// The plane from -2 to 2 across the pixels compared, where 32-bit rounding, and the CPU and each GPU tile following reference orbits of their own, may tip points
|
||
// on the set's ragged edge into escaping at another iteration
|
||
for settings in variations {
|
||
let Some((mismatched, _)) = drawing_differences(&GeneratorPattern::Mandelbrot(settings.clone()), 64. / (4. * scale), glam::DVec2::splat(-2. * scale)) else {
|
||
return;
|
||
};
|
||
assert!(mismatched <= 120, "{mismatched} pixels differ from the CPU's samples with {settings:?}");
|
||
}
|
||
|
||
// Pixels 2^-28 of a unit of the plane across, too fine for 32-bit floats without a reference orbit, on the edge of the set's second largest bulb
|
||
let Some((_, worst)) = drawing_differences(&GeneratorPattern::Mandelbrot(base()), 2_f64.powi(28) / scale, glam::DVec2::new(-1.25 * scale, 0.)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 2, "deep zooms differ from the CPU's samples by up to {worst} levels");
|
||
}
|
||
|
||
/// Renders the tile of `pattern`, `pixels` across with its top left corner at `corner` of its space and pixels `texel` units across, into straight-alpha RGBA8 pixels, or `None` without a GPU.
|
||
fn generator_tile_pixels(pattern: &graphic_types::generator::GeneratorPattern, corner: glam::DVec2, texel: f64, pixels: u32) -> Option<Vec<[u8; 4]>> {
|
||
let executor = executor()?;
|
||
let device = &executor.context().device;
|
||
let _turn = take_turn();
|
||
|
||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||
label: Some("generator_tile_test"),
|
||
size: wgpu::Extent3d {
|
||
width: pixels,
|
||
height: pixels,
|
||
depth_or_array_layers: 1,
|
||
},
|
||
mip_level_count: 1,
|
||
sample_count: 1,
|
||
dimension: wgpu::TextureDimension::D2,
|
||
format: crate::vello_render::TEXTURE_FORMAT,
|
||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||
view_formats: &[],
|
||
});
|
||
|
||
let queue = executor.context().queue.lock();
|
||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("generator_tile_test") });
|
||
let mut held = Vec::new();
|
||
(executor.inner.vello_renderer.generator_passes).render_tile(executor, &queue, &mut encoder, &mut held, &texture, pattern, corner, texel);
|
||
queue.submit([encoder.finish()]);
|
||
drop(held);
|
||
drop(queue);
|
||
|
||
let bytes = executor.read_texture_pixels(&texture).expect("Failed to read back the tile");
|
||
Some(bytes.as_chunks::<4>().0.to_vec())
|
||
}
|
||
|
||
#[test]
|
||
fn deep_mandelbrot_tiles_follow_their_reference_orbits_like_the_cpu() {
|
||
use graphic_types::generator::*;
|
||
use raster_kernels::mandelbrot::MandelbrotSetup;
|
||
|
||
let GeneratorPattern::Mandelbrot(defaults) = GeneratorPattern::decode(Generator::Mandelbrot, &|_| None) else {
|
||
unreachable!()
|
||
};
|
||
|
||
// Pixels 2^-32 of a unit of the plane across, on the edges of the sets with powers of 2 and 2.5 at 256 iterations, and across the seam of the Tricorn's with a power of 2.5
|
||
// on the negative real axis. Rounding, especially by Direct3D's transcendental functions, may tip a few points on the edges into escaping at another iteration.
|
||
let views = [
|
||
(MandelbrotFractal::ClassicMandelbrot, 2., glam::DVec2::new(0.139_355_853_002_853_52, 0.613_550_669_256_420_2)),
|
||
(MandelbrotFractal::ClassicMandelbrot, 2.5, glam::DVec2::new(0.172_648_565_655_390_94, 0.688_459_272_724_629_5)),
|
||
(MandelbrotFractal::Tricorn, 2.5, glam::DVec2::new(-0.863_244_635_611_779_1, 0.)),
|
||
];
|
||
for (fractal, power, center) in views {
|
||
let settings = MandelbrotSettings {
|
||
fractal,
|
||
power,
|
||
scale: 1.,
|
||
..defaults.clone()
|
||
};
|
||
let (pixels, texel) = (64, 2_f64.powi(-32));
|
||
let corner = center - texel * (pixels / 2) as f64;
|
||
let Some(drawn) = generator_tile_pixels(&GeneratorPattern::Mandelbrot(settings.clone()), corner, texel, pixels) else {
|
||
return;
|
||
};
|
||
|
||
// The CPU follows the same reference orbit as the tile
|
||
let setup = MandelbrotSetup::new(&settings);
|
||
let reference = setup.reference_orbit([corner, corner + texel * pixels as f64], texel).filter(|reference| reference.values.len() >= 2);
|
||
assert!(reference.is_some(), "{fractal:?} with a power of {power} has no reference orbit");
|
||
let mismatched = (0..pixels * pixels)
|
||
.filter(|index| {
|
||
let point = corner + (glam::DVec2::new((index % pixels) as f64, (index / pixels) as f64) + 0.5) * texel;
|
||
let sampled = (setup.sample(point, reference.as_ref(), false).clamp(0., 1.) * 255.).round() as u8;
|
||
drawn[*index as usize][0].abs_diff(sampled) > 2
|
||
})
|
||
.count();
|
||
assert!(mismatched <= 128, "{mismatched} pixels differ from the CPU's samples for {fractal:?} with a power of {power}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn generator_tiles_are_reused_across_a_pan() {
|
||
let Some(executor) = executor() else { return };
|
||
let _turn = take_turn();
|
||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||
let tiles = |canvas: &crate::VelloCanvas| canvas.images.generator_tiles.len();
|
||
|
||
// A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile
|
||
let mut canvas = crate::VelloCanvas::default();
|
||
let draw = |offset: f64| {
|
||
let mut scene = VelloSceneBuilder::new(512, 512, Affine::IDENTITY, max_texture_size);
|
||
scene.draw_generator(&noise_pattern(), Affine::translate((offset, 0.)) * Affine::scale(2.));
|
||
scene
|
||
};
|
||
executor.render_vello_scene_on_canvas(&mut canvas, draw(0.)).unwrap();
|
||
let first = tiles(&canvas);
|
||
executor.render_vello_scene_on_canvas(&mut canvas, draw(0.)).unwrap();
|
||
assert_eq!(tiles(&canvas), first, "drawing the same view again renders no tiles");
|
||
|
||
executor.render_vello_scene_on_canvas(&mut canvas, draw(-100.)).unwrap();
|
||
let panned = tiles(&canvas) - first;
|
||
assert!(panned < first, "panning renders only the tiles newly in view, not all {first} again (rendered {panned})");
|
||
}
|
||
|
||
/// An effect stamped on content at `placement` the way its node stamps it, with displacement maps lined up with the content where it lies.
|
||
fn stamped_at(operation: &graphic_types::EffectOperation, placement: DAffine2) -> graphic_types::Effect {
|
||
let mut operation = operation.clone();
|
||
if let graphic_types::EffectOperation::Displace {
|
||
displacement,
|
||
x_displacement,
|
||
y_displacement,
|
||
..
|
||
} = &mut operation
|
||
{
|
||
for map in [displacement, x_displacement, y_displacement] {
|
||
*map = graphic_types::linked_to_content(std::mem::take(map), placement);
|
||
}
|
||
}
|
||
graphic_types::Effect::new(&operation)
|
||
}
|
||
|
||
/// An opaque image `width` by `height` placed by `placement`, gray at each pixel by the 8-bit level `level` gives at its column and row, which a displacement reads as its luminance.
|
||
fn gray_map(width: u32, height: u32, placement: DAffine2, level: impl Fn(f32, f32) -> f32) -> graphic_types::Graphic {
|
||
let data = (0..width * height)
|
||
.map(|index| {
|
||
let gray = level((index % width) as f32, (index / width) as f32) / 255.;
|
||
core_types::Color::from_gamma_srgb_channels(gray, gray, gray, 1.)
|
||
})
|
||
.collect();
|
||
let image = graphic_types::raster_types::Raster::new_cpu(graphic_types::raster_types::Image { width, height, data });
|
||
graphic_types::Graphic::from(core_types::list::Item::new_from_element(image).with_attribute(core_types::ATTR_TRANSFORM, placement))
|
||
}
|
||
|
||
/// A displacement in Angle mode by `map`, which lighter areas move the content along `angle` (in degrees counterclockwise from the right) by `distance`.
|
||
fn angle_displacement(map: graphic_types::Graphic, angle: f64, distance: f64, edge_mode: graphic_types::vector_types::GradientSpread) -> graphic_types::EffectOperation {
|
||
graphic_types::EffectOperation::Displace {
|
||
mode: graphic_types::DisplaceMode::Angle,
|
||
displacement: map,
|
||
angle,
|
||
distance,
|
||
x_displacement: Default::default(),
|
||
y_displacement: Default::default(),
|
||
offset: glam::DVec2::splat(10.),
|
||
edge_mode,
|
||
}
|
||
}
|
||
|
||
/// A displacement in X and Y mode, where lighter areas of `x_map` move the content right by `x_offset` and of `y_map` down by `y_offset`.
|
||
fn x_and_y_displacement(
|
||
(x_map, x_offset): (graphic_types::Graphic, f64),
|
||
(y_map, y_offset): (graphic_types::Graphic, f64),
|
||
edge_mode: graphic_types::vector_types::GradientSpread,
|
||
) -> graphic_types::EffectOperation {
|
||
graphic_types::EffectOperation::Displace {
|
||
mode: graphic_types::DisplaceMode::XAndY,
|
||
displacement: Default::default(),
|
||
angle: 135.,
|
||
distance: 10.,
|
||
x_displacement: x_map,
|
||
y_displacement: y_map,
|
||
offset: glam::DVec2::new(x_offset, y_offset),
|
||
edge_mode,
|
||
}
|
||
}
|
||
|
||
/// A 50 by 50 raster at (`offset`, `offset`), one pixel per document unit, of colors varying across it around a hole, carrying `effects` with `fill`.
|
||
/// Its colors are whole 8-bit levels, which the GPU's copy of it holds exactly.
|
||
fn patterned_raster(offset: f64, effects: &[graphic_types::EffectOperation], fill: f64) -> core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>> {
|
||
patterned_raster_sized(offset, UVec2::splat(50), effects, fill)
|
||
}
|
||
|
||
/// Like [`patterned_raster`], `size` pixels across.
|
||
fn patterned_raster_sized(
|
||
offset: f64,
|
||
size: UVec2,
|
||
effects: &[graphic_types::EffectOperation],
|
||
fill: f64,
|
||
) -> core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>> {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::stamp_effect;
|
||
|
||
let level = |channel: f32| (channel * 255.).round() / 255.;
|
||
let data = (0..size.x * size.y)
|
||
.map(|index| {
|
||
let (x, y) = ((index % size.x) as f32 + 0.5, (index / size.x) as f32 + 0.5);
|
||
let alpha = if (x - 32.).hypot(y - 20.) < 7. { 0. } else { 1. };
|
||
core_types::Color::from_gamma_srgb_channels(level(x / 50.), level(y / 50.), level(((x * 0.4).sin() * 0.5 + 0.5) * (1. - y / 100.)), alpha)
|
||
})
|
||
.collect();
|
||
let placement = DAffine2::from_translation(glam::DVec2::splat(offset)) * DAffine2::from_scale(size.as_dvec2());
|
||
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: size.x, height: size.y, data }))
|
||
.with_attribute(ATTR_TRANSFORM, placement)
|
||
.with_attribute(ATTR_OPACITY_FILL, fill);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, stamped_at(operation, placement)));
|
||
item
|
||
}
|
||
|
||
/// Whether the GPU is a software one, like Mesa's lavapipe, which Vulkan allows to round what its texture filter samples from 8-bit images to whole levels.
|
||
/// A displacement map drawn from an image then moves hard edges by up to a pixel more than the CPU, so tests skip comparing those.
|
||
fn filters_8_bit_images_to_whole_levels() -> bool {
|
||
// TODO: Remove this and its uses once the images that effects read are uploaded as float textures, which every driver filters without rounding
|
||
executor().is_some_and(|executor| executor.context().adapter.get_info().device_type == wgpu::DeviceType::Cpu)
|
||
}
|
||
|
||
/// The most that the GPU's render of `item` and its CPU evaluation differ by at any of the render's pixels, in levels of their premultiplied channels, or `None` without a GPU.
|
||
fn gpu_and_cpu_difference(item: core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>>, size: UVec2) -> Option<u32> {
|
||
gpu_and_cpu_difference_in_view(item, size, DAffine2::IDENTITY)
|
||
}
|
||
|
||
/// Like [`gpu_and_cpu_difference`], with the GPU rendering through a `view` (a zoom, say), which should keep the evaluated raster's pixels on the render's.
|
||
fn gpu_and_cpu_difference_in_view(item: core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>>, size: UVec2, view: DAffine2) -> Option<u32> {
|
||
Some(gpu_and_cpu_differences_in_view(item, size, view)?.into_iter().max().unwrap_or_default())
|
||
}
|
||
|
||
/// How much the GPU's render of `item` through a `view` and its CPU evaluation differ by at each of the render's pixels, row by row, as [`gpu_and_cpu_difference_in_view`] measures it.
|
||
fn gpu_and_cpu_differences_in_view(item: core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>>, size: UVec2, view: DAffine2) -> Option<Vec<u32>> {
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone()));
|
||
let gpu = render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
|
||
Some(cpu_differences(&gpu, size, item, view, UVec2::ZERO, size))
|
||
}
|
||
|
||
/// The GPU's renders of the `items` (as if each were drawn alone in a render `tile` pixels across), drawn side by side in one render in rows of `columns`, each cut from it. `None` without a GPU.
|
||
fn gpu_tiles(items: &[core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>>], tile: UVec2, columns: u32) -> Option<Vec<Vec<[u8; 4]>>> {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::{Item, List};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Each item moved into its tile, which its effects follow
|
||
let origin = |index: usize| UVec2::new(index as u32 % columns, index as u32 / columns) * tile;
|
||
let placed = items.iter().enumerate().map(|(index, item)| {
|
||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||
let item = item.clone().with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(origin(index).as_dvec2()) * transform);
|
||
Item::new_from_element(graphic_types::Graphic::from(item))
|
||
});
|
||
let graphic = graphic_types::Graphic::GraphicList(placed.collect::<List<_>>());
|
||
let size = UVec2::new(columns, (items.len() as u32).div_ceil(columns)) * tile;
|
||
let gpu = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
|
||
|
||
let tiles = (0..items.len()).map(|index| {
|
||
let origin = origin(index);
|
||
(0..tile.y)
|
||
.flat_map(|y| (0..tile.x).map(move |x| (x, y)))
|
||
.map(|(x, y)| pixel(&gpu, size, origin.x + x, origin.y + y))
|
||
.collect()
|
||
});
|
||
Some(tiles.collect())
|
||
}
|
||
|
||
/// Like [`gpu_and_cpu_differences_in_view`] for each of the `items` (as if each were drawn alone in a render `tile` pixels across), drawn together as [`gpu_tiles`] draws them:
|
||
/// each one's tile, and how much its CPU evaluation differs from it at each pixel there, row by row. `None` without a GPU.
|
||
fn gpu_tiles_and_cpu_differences(
|
||
items: Vec<core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>>>,
|
||
tile: UVec2,
|
||
columns: u32,
|
||
) -> Option<Vec<(Vec<[u8; 4]>, Vec<u32>)>> {
|
||
let tiles = gpu_tiles(&items, tile, columns)?;
|
||
let differences = items
|
||
.into_iter()
|
||
.zip(&tiles)
|
||
.map(|(item, pixels)| cpu_differences(pixels, tile, item, DAffine2::IDENTITY, UVec2::ZERO, tile));
|
||
Some(tiles.iter().cloned().zip(differences).collect())
|
||
}
|
||
|
||
/// How much the CPU evaluation of `item` through a `view` differs from the `gpu` render of it, `size` pixels across, at each pixel of the part `extent` across from `origin`, row by row,
|
||
/// in levels of their premultiplied channels.
|
||
fn cpu_differences(
|
||
gpu: &[[u8; 4]],
|
||
size: UVec2,
|
||
item: core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>>,
|
||
view: DAffine2,
|
||
origin: UVec2,
|
||
extent: UVec2,
|
||
) -> Vec<u32> {
|
||
use core_types::ATTR_TRANSFORM;
|
||
|
||
let evaluated = raster_kernels::evaluate_raster_effects(item);
|
||
let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||
let raster = evaluated.element();
|
||
let document_to_pixels = DAffine2::from_scale(glam::DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse() * view.inverse();
|
||
|
||
let mut differences = Vec::with_capacity((extent.x * extent.y) as usize);
|
||
for y in origin.y..origin.y + extent.y {
|
||
for x in origin.x..origin.x + extent.x {
|
||
let point = document_to_pixels.transform_point2(glam::DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor();
|
||
let inside = point.x >= 0. && point.y >= 0. && point.x < raster.width as f64 && point.y < raster.height as f64;
|
||
let cpu = if inside {
|
||
raster.data[(point.y as u32 * raster.width + point.x as u32) as usize]
|
||
} else {
|
||
core_types::Color::TRANSPARENT
|
||
};
|
||
let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels();
|
||
let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.);
|
||
|
||
let gpu = pixel(gpu, size, x, y);
|
||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||
let difference = (0..4).map(|channel| {
|
||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||
(cpu[channel] - gpu_channel).abs().round() as u32
|
||
});
|
||
differences.push(difference.max().unwrap_or_default());
|
||
}
|
||
}
|
||
differences
|
||
}
|
||
|
||
/// A straight-alpha pixel's levels with its color multiplied by its alpha, which compare meaningfully even where it's nearly transparent.
|
||
fn premultiplied_levels(pixel: [u8; 4]) -> [f32; 4] {
|
||
let alpha = pixel[3] as f32 / 255.;
|
||
[pixel[0] as f32 * alpha, pixel[1] as f32 * alpha, pixel[2] as f32 * alpha, pixel[3] as f32]
|
||
}
|
||
|
||
#[test]
|
||
fn motion_blurs_lean_alike_on_flipped_and_turned_content_on_the_cpu_gpu_and_svg() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::List;
|
||
use core_types::transform::Footprint;
|
||
use glam::{DMat2, DVec2};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
// Lines an odd number of pixels long along their major axis, so their boxes lean a whole half pixel
|
||
let slanted_distance = 15. / 30_f64.to_radians().cos();
|
||
let diagonal_distance = 15. * std::f64::consts::SQRT_2;
|
||
let blurs = [(0., 11.), (90., 9.), (30., slanted_distance), (-135., diagonal_distance)].map(|(angle, distance)| EffectOperation::MotionBlur { angle, distance, gamma: false });
|
||
|
||
// The content flipped across, flipped down, turned a half, and turned a quarter each way about its middle, which keeps its pixels on the render's
|
||
let middle = DVec2::splat(80.);
|
||
let about_middle = |linear: DMat2| DAffine2::from_translation(middle) * DAffine2::from_mat2(linear) * DAffine2::from_translation(-middle);
|
||
let placements = [
|
||
("flipped across", DMat2::from_diagonal(DVec2::new(-1., 1.))),
|
||
("flipped down", DMat2::from_diagonal(DVec2::new(1., -1.))),
|
||
("turned a half", DMat2::from_diagonal(DVec2::splat(-1.))),
|
||
("turned a quarter clockwise", DMat2::from_cols(DVec2::Y, -DVec2::X)),
|
||
("turned a quarter counterclockwise", DMat2::from_cols(-DVec2::Y, DVec2::X)),
|
||
];
|
||
|
||
let size = UVec2::splat(160);
|
||
for blur in &blurs {
|
||
for (name, linear) in placements {
|
||
// Blurred where it lies once placed, or blurred upright and then placed, which carries the blur along with it
|
||
for blurred_once_placed in [true, false] {
|
||
let mut item = patterned_raster(55., &[], 1.);
|
||
let placed = about_middle(linear) * item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||
if blurred_once_placed {
|
||
item.set_attribute(ATTR_TRANSFORM, placed);
|
||
}
|
||
stamp_effect(&mut item, Effect::new(blur));
|
||
item.set_attribute(ATTR_TRANSFORM, placed);
|
||
let case = format!("{blur:?} on content {name}, blurred {}", if blurred_once_placed { "once placed" } else { "before it's placed" });
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return };
|
||
assert!(worst <= 3, "{case} differs between the CPU and GPU by up to {worst} levels");
|
||
|
||
// SVG draws the item as an image the GPU renders of it, which has to show what the GPU draws in the view
|
||
let graphic = Graphic::RasterCPU(Box::new(item.clone()));
|
||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let mut svg = SvgRender::new();
|
||
List::new_from_item(item).render_svg(
|
||
&mut svg,
|
||
&RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
},
|
||
);
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: size,
|
||
..Default::default()
|
||
};
|
||
let Some(executor) = executor() else { return };
|
||
let (image_placement, image_width, image) = {
|
||
let _turn = take_turn();
|
||
let rendered = executor.render_deferred_svg_images(&svg.deferred_images, footprint);
|
||
let [(placement, texture)] = &rendered[..] else {
|
||
panic!("expected one image of {case}, got {}", rendered.len())
|
||
};
|
||
let pixels = executor.read_texture_pixels(texture).expect("Failed to read back the image");
|
||
(placement.transform, texture.width(), pixels.as_chunks::<4>().0.to_vec())
|
||
};
|
||
|
||
// The image's pixels lie on the view's from its corner
|
||
let corner = image_placement.translation.round().as_ivec2();
|
||
let mut compared = 0;
|
||
for (index, &image_pixel) in image.iter().enumerate() {
|
||
let position = corner + glam::IVec2::new((index as u32 % image_width) as i32, (index as u32 / image_width) as i32);
|
||
if position.cmplt(glam::IVec2::ZERO).any() || position.cmpge(size.as_ivec2()).any() {
|
||
continue;
|
||
}
|
||
|
||
let (svg_pixel, gpu_pixel) = (premultiplied_levels(image_pixel), premultiplied_levels(pixel(&gpu, size, position.x as u32, position.y as u32)));
|
||
let difference = (0..4).map(|channel| (svg_pixel[channel] - gpu_pixel[channel]).abs()).fold(0., f32::max);
|
||
assert!(difference <= 1.5, "{case} differs between SVG's image and the GPU by {difference} levels at {position}");
|
||
compared += 1;
|
||
}
|
||
assert!(compared >= 50 * 50, "SVG's image of {case} covers only {compared} of the view's pixels");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn long_motion_blurs_spread_their_samples_alike_on_the_cpu_and_gpu() {
|
||
use glam::{DMat2, DVec2};
|
||
use graphic_types::{EffectOperation, Effects};
|
||
use half::f16;
|
||
use raster_kernels::resample_kernels::{MAX_MOTION_BLUR_SAMPLES, MotionBlurShear, motion_blurred};
|
||
|
||
// Stripes repeating every two and three pixels along a strip, which a box sampling the wrong pixels of would average far off
|
||
let (width, height) = (1400, 48);
|
||
let texels: Vec<[f16; 4]> = (0..width * height)
|
||
.map(|index| {
|
||
let (x, y) = (index % width, index / width);
|
||
let alpha = if (600..640).contains(&x) && y < 10 { 0. } else { 1. };
|
||
let straight = [(x % 2) as f32, (x % 3) as f32 / 2., y as f32 / (height - 1) as f32];
|
||
let [red, green, blue] = straight.map(|channel| channel * alpha);
|
||
[red, green, blue, alpha].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let plane = raster_kernels::effect_kernels::Plane {
|
||
width,
|
||
height,
|
||
data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(),
|
||
};
|
||
|
||
// Lines past the most samples a box takes, so its samples lie two or three pixels apart, along the strip and slanting across it
|
||
for (angle, distance) in [(0., 1100.), (0., 2501.5), (4., 1300.)] {
|
||
let Some(shear) = MotionBlurShear::new(angle, distance, DMat2::IDENTITY, DVec2::ZERO) else {
|
||
panic!("a line {distance} long has shears")
|
||
};
|
||
assert!(shear.stride() > 1. && shear.length > MAX_MOTION_BLUR_SAMPLES, "the box of a line {distance} long takes every pixel");
|
||
|
||
let effects = Effects::from_operations([EffectOperation::MotionBlur { angle, distance, gamma: true }]);
|
||
let Some(gpu) = gpu_effect_texels(&effects, &texels, width, &[]) else { return };
|
||
let cpu = motion_blurred(&plane, &shear);
|
||
|
||
let levels = (gpu.iter().zip(&cpu.data))
|
||
.flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.))
|
||
.fold(0_f32, f32::max);
|
||
assert!(levels <= 1., "a line {distance} long at {angle} degrees strays from the CPU's kernel by {levels} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn skewed_motion_blurs_move_with_the_contents_origin() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::{ATTR_APPEARANCE, List};
|
||
use glam::{DMat2, DVec2, IVec2};
|
||
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
// A square around its origin, smeared along a slanted line, then skewed so its effects render along its skewed axes
|
||
let mut square = Vector::item_from_bezpath(&Rect::new(-16., -16., 16., 16.).to_path(0.1));
|
||
square.set_attribute(
|
||
ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(core_types::Color::WHITE))),
|
||
);
|
||
stamp_effect(
|
||
&mut square,
|
||
Effect::new(&EffectOperation::MotionBlur {
|
||
angle: 30.,
|
||
distance: 12.,
|
||
gamma: false,
|
||
}),
|
||
);
|
||
// Stretching at most twofold, the skew moves those texels by whole texels when the square moves by whole pixels
|
||
let skew = DAffine2::from_mat2(DMat2::from_cols(DVec2::X, DVec2::new(1.5, 1.)));
|
||
|
||
let size = UVec2::new(256, 160);
|
||
let draw_at = |origin: DVec2| {
|
||
let graphic = Graphic::Vector(Box::new(square.clone().with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(origin) * skew)));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
|
||
let origin = DVec2::new(100., 70.);
|
||
let shift = IVec2::new(7, 3);
|
||
let (Some(before), Some(after)) = (draw_at(origin), draw_at(origin + shift.as_dvec2())) else {
|
||
return;
|
||
};
|
||
let smeared = before.iter().filter(|pixel| (8..248).contains(&pixel[3])).count();
|
||
assert!(smeared > 500, "the blur smears only {smeared} pixels");
|
||
|
||
// Its shears are measured from its origin, so the smear moves along with it
|
||
let mut worst = 0;
|
||
for y in 0..size.y - shift.y as u32 {
|
||
for x in 0..size.x - shift.x as u32 {
|
||
let (expected, actual) = (pixel(&before, size, x, y), pixel(&after, size, x + shift.x as u32, y + shift.y as u32));
|
||
worst = worst.max(expected.iter().zip(actual).map(|(&expected, actual)| expected.abs_diff(actual)).max().unwrap_or_default());
|
||
}
|
||
}
|
||
assert!(worst <= 1, "moved by {shift}, the smear differs by up to {worst} levels");
|
||
}
|
||
|
||
#[test]
|
||
fn radial_blurs_reach_as_far_inside_faded_groups_and_from_out_of_view() {
|
||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||
use core_types::{ATTR_OPACITY, ATTR_TRANSFORM};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Effects, Graphic, RadialBlurMethod, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A spin about a center two widths to the right of content 32 across with its origin at (20, 64), which smears it up, down, and right far past its own bounds
|
||
let spin = EffectOperation::RadialBlur {
|
||
method: RadialBlurMethod::Spin,
|
||
amount: 120.,
|
||
transform: DAffine2::from_translation(DVec2::new(80., 16.)),
|
||
gamma: false,
|
||
};
|
||
let size = UVec2::new(160, 160);
|
||
let draw = |graphic: &Graphic, view: DAffine2| render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||
|
||
// Inside a group of nearly full opacity, a square smears as far as on its own
|
||
let mut square = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, core_types::Color::WHITE)))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(20., 64.)) * DAffine2::from_scale(DVec2::splat(32.)));
|
||
stamp_effect(&mut square, Effect::new(&spin));
|
||
let grouped = Graphic::Graphic(Box::new(Item::new_from_element(Graphic::RasterCPU(Box::new(square.clone()))).with_attribute(ATTR_OPACITY, 0.999_f64)));
|
||
let (Some(alone), Some(grouped)) = (draw(&Graphic::RasterCPU(Box::new(square)), DAffine2::IDENTITY), draw(&grouped, DAffine2::IDENTITY)) else {
|
||
return;
|
||
};
|
||
assert!(alone[..(size.x * 56) as usize].iter().any(|pixel| pixel[3] > 20), "the smear reaches well above the square");
|
||
for (index, (alone, grouped)) in alone.iter().zip(&grouped).enumerate() {
|
||
let (alone_levels, grouped_levels) = (premultiplied_levels(*alone), premultiplied_levels(*grouped));
|
||
let difference = (0..4).map(|channel| (alone_levels[channel] - grouped_levels[channel]).abs()).fold(0., f32::max);
|
||
assert!(
|
||
difference <= 2.,
|
||
"at ({}, {}) the group shows {grouped:?} rather than {alone:?}",
|
||
index as u32 % size.x,
|
||
index as u32 / size.x
|
||
);
|
||
}
|
||
|
||
// A circle viewed only where it smears, right of its own bounds, isn't culled
|
||
let circle_item = Vector::item_from_bezpath(&circle((16., 16.), 16.))
|
||
.with_attribute(
|
||
ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(core_types::Color::WHITE))),
|
||
)
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(20., 64.)))
|
||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([spin]));
|
||
let Some(beside) = draw(&Graphic::Vector(Box::new(circle_item)), DAffine2::from_translation(DVec2::new(-56., 0.))) else {
|
||
return;
|
||
};
|
||
assert!(beside.iter().any(|pixel| pixel[3] > 20), "the circle's smear shows beside it");
|
||
}
|
||
|
||
#[test]
|
||
fn resampling_effects_match_on_the_cpu_and_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{EffectOperation, RadialBlurMethod, WaveType};
|
||
|
||
let motion = |angle, distance, gamma| EffectOperation::MotionBlur { angle, distance, gamma };
|
||
let radial = |method, amount, center, gamma| EffectOperation::RadialBlur {
|
||
method,
|
||
amount,
|
||
transform: DAffine2::from_translation(center),
|
||
gamma,
|
||
};
|
||
let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75), DVec2::new(4., 5.), 3., 0.);
|
||
let mut hidden_highlights = graphic_types::blend_if::BlendIfRanges::default();
|
||
hidden_highlights.content.gray = blend_range([0., 0., 128., 192.]);
|
||
|
||
// The warps act within the image 50 pixels across, measured from its corner
|
||
let on_image = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
|
||
let cases = [
|
||
vec![motion(0., 12., false)],
|
||
vec![motion(30., 7.5, true)],
|
||
// Long enough for the shears to step many whole pixels across the line
|
||
vec![motion(-70., 90., false)],
|
||
// About the middle of the image 50 pixels across, measured from its corner
|
||
vec![radial(RadialBlurMethod::Spin, 20., DVec2::splat(25.), false)],
|
||
// A whole turn, and a zoom spanning more than each point's distance from the center
|
||
vec![radial(RadialBlurMethod::Spin, 360., DVec2::new(30., 27.5), false)],
|
||
vec![radial(RadialBlurMethod::Zoom, 250., DVec2::splat(25.), false)],
|
||
vec![radial(RadialBlurMethod::Zoom, 60., DVec2::new(35., 20.), true)],
|
||
// About centers off the image
|
||
vec![radial(RadialBlurMethod::Spin, 15., DVec2::new(-40., 90.), false)],
|
||
vec![radial(RadialBlurMethod::Zoom, 30., DVec2::new(120., -30.), false)],
|
||
vec![shadow, radial(RadialBlurMethod::Spin, 45., DVec2::new(10., 45.), false)],
|
||
vec![EffectOperation::Twirl { angle: 140., transform: on_image }],
|
||
vec![EffectOperation::Pinch { amount: 70., transform: on_image }],
|
||
vec![EffectOperation::Pinch { amount: -60., transform: on_image }],
|
||
vec![EffectOperation::Spherize {
|
||
amount: 100.,
|
||
cylindrical: false,
|
||
transform: on_image,
|
||
}],
|
||
vec![EffectOperation::Spherize {
|
||
amount: -80.,
|
||
cylindrical: true,
|
||
transform: on_image,
|
||
}],
|
||
// Turned a quarter, a cylinder bends the columns
|
||
vec![EffectOperation::Spherize {
|
||
amount: 50.,
|
||
cylindrical: true,
|
||
transform: on_image * DAffine2::from_angle(std::f64::consts::FRAC_PI_2),
|
||
}],
|
||
vec![EffectOperation::PolarCoordinates { inverse: false, transform: on_image }],
|
||
vec![EffectOperation::PolarCoordinates { inverse: true, transform: on_image }],
|
||
vec![EffectOperation::Pixelate { cell_size: 7., offset: DVec2::ZERO }],
|
||
vec![EffectOperation::Pixelate { cell_size: 9.5, offset: DVec2::ZERO }],
|
||
vec![EffectOperation::Pixelate { cell_size: 7.3, offset: DVec2::ZERO }],
|
||
vec![EffectOperation::Pixelate { cell_size: 10., offset: DVec2::ZERO }],
|
||
// Cells and screens placed off the content's origin, with its sides cutting cells on all four
|
||
vec![EffectOperation::Pixelate {
|
||
cell_size: 7.3,
|
||
offset: DVec2::new(3.25, -4.6),
|
||
}],
|
||
vec![EffectOperation::Pixelate {
|
||
cell_size: 10.,
|
||
offset: DVec2::new(-12.5, 7.),
|
||
}],
|
||
vec![EffectOperation::ColorHalftone {
|
||
radius: 4.,
|
||
red_angle: 45.,
|
||
green_angle: 45.,
|
||
blue_angle: 45.,
|
||
offset: DVec2::new(12.3, -5.7),
|
||
phase: 35.,
|
||
}],
|
||
vec![EffectOperation::ColorHalftone {
|
||
radius: 5.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: DVec2::new(-30.4, 61.),
|
||
phase: 80.,
|
||
}],
|
||
vec![EffectOperation::ColorHalftone {
|
||
radius: 4.,
|
||
red_angle: 45.,
|
||
green_angle: 45.,
|
||
blue_angle: 45.,
|
||
offset: DVec2::ZERO,
|
||
phase: 0.,
|
||
}],
|
||
vec![EffectOperation::ColorHalftone {
|
||
radius: 6.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
}],
|
||
// Dots too close together to print, which show their tone
|
||
vec![EffectOperation::ColorHalftone {
|
||
radius: 1.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
}],
|
||
// A halftone prints the content as a Blend If before it leaves it shown
|
||
vec![
|
||
EffectOperation::BlendIf(Box::new(hidden_highlights)),
|
||
EffectOperation::ColorHalftone {
|
||
radius: 4.,
|
||
red_angle: 15.,
|
||
green_angle: 75.,
|
||
blue_angle: 0.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
},
|
||
],
|
||
];
|
||
|
||
// Maps of grays rising across and falling down in whole 8-bit levels, a pixel for each of the content's, read across and down or along angles
|
||
let on_content = DAffine2::from_translation(DVec2::splat(55.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
let (across, down) = (gray_map(50, 50, on_content, |x, _| 60. + 3. * x), gray_map(50, 50, on_content, |_, y| 200. - 2. * y));
|
||
let across_and_down = |edge_mode| vec![x_and_y_displacement((across.clone(), 6.4), (down.clone(), -5.12), edge_mode)];
|
||
let angled = |angle, edge_mode| vec![angle_displacement(down.clone(), angle, 8., edge_mode)];
|
||
let edge_modes = [GradientSpread::Clear, GradientSpread::Repeat, GradientSpread::Pad, GradientSpread::Reflect];
|
||
let displacements = (edge_modes.map(across_and_down).into_iter()).chain([angled(135., GradientSpread::Clear), angled(-60., GradientSpread::Reflect)]);
|
||
|
||
// Procedural displacements, reading past the frame as each mode says
|
||
let ripple = |amount, size, edge_mode| vec![EffectOperation::Ripple { amount, size, edge_mode }];
|
||
let wave = |wave_type, edge_mode| {
|
||
vec![EffectOperation::Wave {
|
||
wave_type,
|
||
total_generators: 4,
|
||
wavelength_min: 9.,
|
||
wavelength_max: 40.,
|
||
amplitude_min: 1.,
|
||
amplitude_max: 5.,
|
||
horizontal_scale: 100.,
|
||
vertical_scale: 60.,
|
||
edge_mode,
|
||
seed: 11,
|
||
}]
|
||
};
|
||
// Mirrored by negative wavelengths and sizes, moving both ways by amplitudes of either sign, and reversed or strengthened past full scale
|
||
let mirrored_wave = |wave_type, edge_mode| {
|
||
vec![EffectOperation::Wave {
|
||
wave_type,
|
||
total_generators: 4,
|
||
wavelength_min: -40.,
|
||
wavelength_max: -9.,
|
||
amplitude_min: -4.,
|
||
amplitude_max: 3.,
|
||
horizontal_scale: -80.,
|
||
vertical_scale: 150.,
|
||
edge_mode,
|
||
seed: 11,
|
||
}]
|
||
};
|
||
let fields = [
|
||
ripple(150., 16., GradientSpread::Clear),
|
||
ripple(-400., 8., GradientSpread::Pad),
|
||
wave(WaveType::Sine, GradientSpread::Clear),
|
||
wave(WaveType::Triangle, GradientSpread::Repeat),
|
||
wave(WaveType::Square, GradientSpread::Pad),
|
||
ripple(250., 12., GradientSpread::Reflect),
|
||
wave(WaveType::Sine, GradientSpread::Reflect),
|
||
ripple(150., -16., GradientSpread::Clear),
|
||
ripple(-80., -10., GradientSpread::Reflect),
|
||
mirrored_wave(WaveType::Sine, GradientSpread::Clear),
|
||
mirrored_wave(WaveType::Triangle, GradientSpread::Repeat),
|
||
];
|
||
|
||
for effects in cases.into_iter().chain(displacements).chain(fields) {
|
||
for fill in [1., 0.5] {
|
||
let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., &effects, fill), UVec2::new(160, 160)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn resampling_effects_match_on_turned_zoomed_and_oblong_content() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{EffectOperation, RadialBlurMethod, WaveType, stamp_effect};
|
||
|
||
// An oblong raster of 60 by 36 pixels, two to each document unit, upright or turned a quarter and viewed at twice the size, so its pixels land on the render's
|
||
let level = |channel: f32| (channel * 255.).round() / 255.;
|
||
let data = (0..60 * 36)
|
||
.map(|index| {
|
||
let (x, y) = ((index % 60) as f32 + 0.5, (index / 60) as f32 + 0.5);
|
||
let alpha = if (x - 40.).hypot(y - 14.) < 6. { 0. } else { 1. };
|
||
GraphicColor::from_gamma_srgb_channels(level(x / 60.), level(y / 36.), level((x * 0.3).sin() * 0.5 + 0.5), alpha)
|
||
})
|
||
.collect::<Vec<_>>();
|
||
let upright = DAffine2::from_translation(DVec2::new(25., 25.)) * DAffine2::from_scale(DVec2::new(30., 18.));
|
||
let turned = DAffine2::from_translation(DVec2::new(58., 25.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_2) * DAffine2::from_scale(DVec2::new(30., 18.));
|
||
let content = |placement: DAffine2, effects: &[EffectOperation]| {
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image {
|
||
width: 60,
|
||
height: 36,
|
||
data: data.clone(),
|
||
}))
|
||
.with_attribute(ATTR_TRANSFORM, placement);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, stamped_at(operation, placement)));
|
||
item
|
||
};
|
||
|
||
// 7 by 5 image maps placed across the content, read across and down or along an angle, which turn with the content
|
||
let across = |placement: DAffine2| gray_map(7, 5, placement, |x, y| 90. + 9. * x - 5. * y);
|
||
let down = |placement: DAffine2| gray_map(7, 5, placement, |x, y| 170. - 11. * y + 3. * x);
|
||
let across_and_down = |placement: DAffine2| x_and_y_displacement((across(placement), 25.6), (down(placement), -19.2), GradientSpread::Repeat);
|
||
let angled = |placement: DAffine2| angle_displacement(down(placement), 150., 30., GradientSpread::Reflect);
|
||
|
||
// The warps act within each raster's own rectangle, measured from its origin in the effect space, which turns with the turned one
|
||
let warps = |placement: DAffine2| {
|
||
let transform = DAffine2::from_mat2(placement.matrix2) * DAffine2::from_translation(DVec2::splat(0.5));
|
||
[
|
||
EffectOperation::Twirl { angle: 150., transform },
|
||
EffectOperation::Pinch { amount: 60., transform },
|
||
EffectOperation::Spherize {
|
||
amount: -70.,
|
||
cylindrical: true,
|
||
transform,
|
||
},
|
||
EffectOperation::PolarCoordinates { inverse: false, transform },
|
||
EffectOperation::PolarCoordinates { inverse: true, transform },
|
||
]
|
||
};
|
||
|
||
let cases = [
|
||
EffectOperation::MotionBlur {
|
||
angle: 30.,
|
||
distance: 6.,
|
||
gamma: false,
|
||
},
|
||
// About a point within the upright raster and beside the turned one, measured from each one's origin
|
||
EffectOperation::RadialBlur {
|
||
method: RadialBlurMethod::Spin,
|
||
amount: 25.,
|
||
transform: DAffine2::from_translation(DVec2::new(18., 5.4)),
|
||
gamma: false,
|
||
},
|
||
EffectOperation::Ripple {
|
||
amount: 150.,
|
||
size: 8.,
|
||
edge_mode: GradientSpread::Pad,
|
||
},
|
||
EffectOperation::Wave {
|
||
wave_type: WaveType::Triangle,
|
||
total_generators: 3,
|
||
wavelength_min: 6.,
|
||
wavelength_max: 20.,
|
||
amplitude_min: 0.5,
|
||
amplitude_max: 2.,
|
||
horizontal_scale: 100.,
|
||
vertical_scale: 50.,
|
||
edge_mode: GradientSpread::Repeat,
|
||
seed: 5,
|
||
},
|
||
];
|
||
let pixelate = |offset| EffectOperation::Pixelate { cell_size: 2.3, offset };
|
||
let halftone = |radius, offset, phase| EffectOperation::ColorHalftone {
|
||
radius,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset,
|
||
phase,
|
||
};
|
||
// Dots of radius 0.75 have their boxes' sides on the centers of pixels half a unit across
|
||
let pixelations = [
|
||
pixelate(DVec2::ZERO),
|
||
pixelate(DVec2::new(0.7, -1.1)),
|
||
halftone(3., DVec2::ZERO, 0.),
|
||
halftone(3., DVec2::new(7.4, 2.9), 65.),
|
||
halftone(0.75, DVec2::ZERO, 0.),
|
||
];
|
||
let cases = cases.into_iter().chain(pixelations).collect::<Vec<_>>();
|
||
for placement in [upright, turned] {
|
||
let displacements = [across_and_down(placement), angled(placement)];
|
||
for effect in displacements.iter().chain(&warps(placement)).chain(&cases) {
|
||
let Some(worst) = gpu_and_cpu_difference_in_view(content(placement, std::slice::from_ref(effect)), UVec2::new(160, 160), DAffine2::from_scale(DVec2::splat(2.))) else {
|
||
return;
|
||
};
|
||
if matches!(effect, EffectOperation::Displace { .. }) && filters_8_bit_images_to_whole_levels() {
|
||
continue;
|
||
}
|
||
assert!(worst <= 3, "{effect:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Each warp, acting within the frame the `transform` places.
|
||
fn warps_within(transform: DAffine2) -> [graphic_types::EffectOperation; 7] {
|
||
use graphic_types::EffectOperation;
|
||
|
||
[
|
||
EffectOperation::Twirl { angle: 200., transform },
|
||
EffectOperation::Pinch { amount: 80., transform },
|
||
EffectOperation::Pinch { amount: -100., transform },
|
||
EffectOperation::Spherize {
|
||
amount: 100.,
|
||
cylindrical: false,
|
||
transform,
|
||
},
|
||
EffectOperation::Spherize {
|
||
amount: 100.,
|
||
cylindrical: true,
|
||
transform,
|
||
},
|
||
EffectOperation::PolarCoordinates { inverse: false, transform },
|
||
EffectOperation::PolarCoordinates { inverse: true, transform },
|
||
]
|
||
}
|
||
|
||
#[test]
|
||
fn warps_match_on_the_cpu_and_gpu_within_small_offset_and_turned_slanted_frames() {
|
||
use glam::DVec2;
|
||
|
||
// Within the image 50 pixels across, measured from its corner: a circle about a third its size toward its bottom right, and an oblong one turned and slanted about its middle
|
||
let small = DAffine2::from_translation(DVec2::new(32., 30.)) * DAffine2::from_scale(DVec2::splat(18.));
|
||
let slanted = DAffine2::from_translation(DVec2::new(24., 26.)) * DAffine2::from_angle(0.6) * DAffine2::from_cols_array(&[40., 0., 12., 24., 0., 0.]);
|
||
for warp in [small, slanted].into_iter().flat_map(warps_within) {
|
||
for fill in [1., 0.5] {
|
||
let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{warp:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warps_paint_as_far_as_their_ellipse_or_square_reaches_past_the_content() {
|
||
use glam::DVec2;
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A circle three times as large as the image 50 pixels across, about its middle, reaching 50 past each of its sides
|
||
let transform = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(150.));
|
||
let size = UVec2::new(160, 160);
|
||
for warp in warps_within(transform) {
|
||
let item = patterned_raster(55., std::slice::from_ref(&warp), 1.);
|
||
let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return };
|
||
assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels");
|
||
|
||
// All but pinching inward and wrapping, which gather the content toward the middle, paint more than 5 past the content from (55, 55) to (105, 105) rather than being cut off at its bounds
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(item));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let gathers = match &warp {
|
||
graphic_types::EffectOperation::Pinch { amount, .. } => *amount > 0.,
|
||
graphic_types::EffectOperation::PolarCoordinates { inverse, .. } => !inverse,
|
||
_ => false,
|
||
};
|
||
let past_content = |x: u32, y: u32| !(50..110).contains(&x) || !(50..110).contains(&y);
|
||
let painted_past = (0..size.y)
|
||
.flat_map(|y| (0..size.x).map(move |x| (x, y)))
|
||
.any(|(x, y)| past_content(x, y) && pixel(&pixels, size, x, y)[3] > 0);
|
||
assert!(gathers || painted_past, "{warp:?} paints nothing far past the content");
|
||
|
||
// Unwrapping fills the square's top row with the content's middle, 50 above the content
|
||
if matches!(warp, graphic_types::EffectOperation::PolarCoordinates { inverse: true, .. }) {
|
||
assert_eq!(pixel(&pixels, size, 80, 5)[3], 255, "the unwrapped square's top row is cut off");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warps_within_the_identity_or_a_collapsed_transform_change_nothing_else_unless_they_clear_it() {
|
||
use glam::DVec2;
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let draw = |effects: &[graphic_types::EffectOperation], view: DAffine2| {
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(55., effects, 1.)));
|
||
render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
|
||
// The identity is a circle 1 across at the image's corner (55, 55), changing nothing past a pixel or two, and a frame collapsed onto a line, even in a turned view, changes nothing at all.
|
||
// Polar Coordinates instead clears everything there, all outside its square.
|
||
let collapsed = DAffine2::from_scale(DVec2::new(50., 0.));
|
||
let singular = DAffine2::from_cols_array(&[100., 200., 300., 600., 0., 0.]);
|
||
let turned = DAffine2::from_translation(DVec2::splat(80.)) * DAffine2::from_angle(0.1) * DAffine2::from_translation(DVec2::splat(-80.));
|
||
for (transform, view, reach) in [(DAffine2::IDENTITY, DAffine2::IDENTITY, 2.), (collapsed, DAffine2::IDENTITY, 0.), (singular, turned, 0.)] {
|
||
let Some(plain) = draw(&[], view) else { return };
|
||
for warp in warps_within(transform) {
|
||
let clears = matches!(warp, graphic_types::EffectOperation::PolarCoordinates { .. });
|
||
let Some(warped) = draw(std::slice::from_ref(&warp), view) else { return };
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
if (DVec2::new(x as f64 + 0.5, y as f64 + 0.5) - 55.).abs().max_element() <= reach {
|
||
continue;
|
||
}
|
||
let expected = if clears { [0.; 4] } else { premultiplied_levels(pixel(&plain, size, x, y)) };
|
||
let actual = premultiplied_levels(pixel(&warped, size, x, y));
|
||
let difference = (0..4).map(|channel| (expected[channel] - actual[channel]).abs()).fold(0., f32::max);
|
||
assert!(difference <= 2., "{warp:?} shows {actual:?} at ({x}, {y}) rather than {expected:?}");
|
||
}
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), 1.), size) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warps_past_full_strength_fold_alike_on_the_cpu_and_gpu_reading_from_past_their_ellipse_and_the_view() {
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
|
||
// A circle 16 across within the image 50 pixels across, viewed whole or with the view's left edge 10 left of the circle's center, past which the strongest read the image
|
||
let transform = DAffine2::from_translation(DVec2::new(35., 25.)) * DAffine2::from_scale(DVec2::splat(16.));
|
||
let cropped = DAffine2::from_translation(DVec2::new(-80., -40.));
|
||
let sphere = |amount, cylindrical| EffectOperation::Spherize { amount, cylindrical, transform };
|
||
let warps = [
|
||
EffectOperation::Pinch { amount: 1000., transform },
|
||
EffectOperation::Pinch { amount: -500., transform },
|
||
EffectOperation::Pinch { amount: -1000., transform },
|
||
sphere(-300., false),
|
||
sphere(600., false),
|
||
sphere(1000., false),
|
||
sphere(-300., true),
|
||
sphere(400., true),
|
||
];
|
||
|
||
for warp in warps {
|
||
for (view, fill) in [(DAffine2::IDENTITY, 1.), (DAffine2::IDENTITY, 0.5), (cropped, 1.)] {
|
||
let Some(worst) = gpu_and_cpu_difference_in_view(patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160), view) else {
|
||
return;
|
||
};
|
||
// Folds this strong magnify where they read, so the GPU's 32-bit rounding of each read shows as a level or two more
|
||
assert!(worst <= 5, "{warp:?} at fill {fill} in the view {view} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The transforms of warps' squares in a texture 180 texels square, cutting through texels at every offset along their sides:
|
||
/// one 80 across with its sides meeting at 16 degrees, one 100 across turned 30 degrees, and an oblong turned and slanted.
|
||
fn slanted_and_turned_squares() -> [DAffine2; 3] {
|
||
use glam::DVec2;
|
||
|
||
[
|
||
DAffine2::from_cols_array(&[80., 0., 76.8, 22.4, 80.2, 80.3]),
|
||
DAffine2::from_translation(DVec2::new(90.3, 89.6)) * DAffine2::from_angle(30_f64.to_radians()) * DAffine2::from_scale(DVec2::splat(100.)),
|
||
DAffine2::from_translation(DVec2::new(88.7, 91.2)) * DAffine2::from_angle(0.6) * DAffine2::from_cols_array(&[110., 0., 30., 60., 0., 0.]),
|
||
]
|
||
}
|
||
|
||
#[test]
|
||
fn polar_coordinates_read_nothing_wholly_past_a_slanted_square_on_the_gpu() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
use half::f16;
|
||
|
||
// Clear content but for opaque red at the texel wholly past the slanted square's left side, which reads within the square beside that side have among the four around them
|
||
let size = 180;
|
||
let mut texels = vec![[f16::ZERO; 4]; size * size];
|
||
texels[89 * size + 69] = [f16::ONE, f16::ZERO, f16::ZERO, f16::ONE];
|
||
|
||
for inverse in [false, true] {
|
||
let transform = slanted_and_turned_squares()[0];
|
||
let effects = Effects::from_operations([EffectOperation::PolarCoordinates { inverse, transform }]);
|
||
let Some(gpu) = gpu_effect_texels(&effects, &texels, size, &[]) else { return };
|
||
for (index, texel) in gpu.iter().enumerate() {
|
||
let (x, y) = (index % size, index / size);
|
||
assert_eq!(*texel, [0.; 4], "({x}, {y}) shows {texel:?} with inverse {inverse}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn polar_coordinates_read_nothing_past_a_square_too_small_to_cover_a_texel_on_the_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
use half::f16;
|
||
|
||
// A square 0.4 across turned 45 degrees, ending about 0.017 above the texel from (10, 11), which only red fills, though the texel's extent along the square's axes reaches it
|
||
let transform = DAffine2::from_translation(DVec2::new(10.5, 10.7)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4) * DAffine2::from_scale(DVec2::splat(0.4));
|
||
let size = 20;
|
||
let mut texels = vec![[f16::ZERO; 4]; size * size];
|
||
texels[11 * size + 10] = [f16::ONE, f16::ZERO, f16::ZERO, f16::ONE];
|
||
|
||
for inverse in [false, true] {
|
||
let effects = Effects::from_operations([EffectOperation::PolarCoordinates { inverse, transform }]);
|
||
let Some(gpu) = gpu_effect_texels(&effects, &texels, size, &[]) else { return };
|
||
for (index, texel) in gpu.iter().enumerate() {
|
||
let (x, y) = (index % size, index / size);
|
||
assert_eq!(*texel, [0.; 4], "({x}, {y}) shows {texel:?} with inverse {inverse}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn polar_coordinates_match_the_cpu_within_slanted_and_turned_squares() {
|
||
use graphic_types::resampling::{FrameWarp, warp_frame};
|
||
use graphic_types::{EffectOperation, Effects};
|
||
use half::f16;
|
||
use raster_kernels::resample_kernels::frame_warped;
|
||
|
||
// Colors varying across a texture 180 texels square, around a hole and through a translucent band, so the squares' sides cut through edges and translucency
|
||
let size = 180;
|
||
let texels: Vec<[f16; 4]> = (0..size * size)
|
||
.map(|index| {
|
||
let (x, y) = ((index % size) as f32 + 0.5, (index / size) as f32 + 0.5);
|
||
let alpha = if (x - 70.).hypot(y - 95.) < 12. {
|
||
0.
|
||
} else if (60. ..72.).contains(&y) {
|
||
0.5
|
||
} else {
|
||
1.
|
||
};
|
||
let straight = [x / size as f32, y / size as f32, (x * 0.3).sin() * 0.5 + 0.5];
|
||
let [red, green, blue] = straight.map(|channel| channel * alpha);
|
||
[red, green, blue, alpha].map(f16::from_f32)
|
||
})
|
||
.collect();
|
||
let plane = raster_kernels::effect_kernels::Plane {
|
||
width: size,
|
||
height: size,
|
||
data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(),
|
||
};
|
||
|
||
for transform in slanted_and_turned_squares() {
|
||
for inverse in [false, true] {
|
||
let operation = EffectOperation::PolarCoordinates { inverse, transform };
|
||
let Some(gpu) = gpu_effect_texels(&Effects::from_operations([operation.clone()]), &texels, size, &[]) else {
|
||
return;
|
||
};
|
||
let (Some((warp, _)), Some(square)) = (FrameWarp::of(&operation), warp_frame(transform, DAffine2::IDENTITY)) else {
|
||
panic!("{operation:?} has no square")
|
||
};
|
||
let cpu = frame_warped(&plane, &warp, &square);
|
||
|
||
let levels = (gpu.iter().zip(&cpu.data))
|
||
.flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.))
|
||
.fold(0_f32, f32::max);
|
||
assert!(levels <= 1., "{operation:?} strays from the CPU's kernel by {levels} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The transforms of squares in a texture 160 texels square, all but the last with their left and right sides, which wrapping joins at its seam, cutting through texels:
|
||
/// one 120.5 wide, one 120 across turned 10 degrees, that one mirrored across, and one 121 across centered on a texel.
|
||
fn polar_seam_squares() -> [DAffine2; 4] {
|
||
use glam::DVec2;
|
||
|
||
let center = DAffine2::from_translation(DVec2::splat(80.));
|
||
let turned = center * DAffine2::from_angle(10_f64.to_radians()) * DAffine2::from_scale(DVec2::splat(120.));
|
||
[
|
||
center * DAffine2::from_scale(DVec2::new(120.5, 120.)),
|
||
turned,
|
||
turned * DAffine2::from_scale(DVec2::new(-1., 1.)),
|
||
DAffine2::from_translation(DVec2::splat(80.5)) * DAffine2::from_scale(DVec2::splat(121.)),
|
||
]
|
||
}
|
||
|
||
/// A texture 160 texels square of opaque blue, as half floats and as the CPU's plane.
|
||
fn opaque_polar_content() -> (Vec<[half::f16; 4]>, raster_kernels::effect_kernels::Plane<[f32; 4]>) {
|
||
let texels = vec![[0.2, 0.6, 0.9, 1.].map(half::f16::from_f32); 160 * 160];
|
||
let plane = raster_kernels::effect_kernels::Plane {
|
||
width: 160,
|
||
height: 160,
|
||
data: texels.iter().map(|texel| texel.map(half::f16::to_f32)).collect(),
|
||
};
|
||
(texels, plane)
|
||
}
|
||
|
||
/// The `plane` unwrapped within the square the `transform` places, then wrapped back within it, on the CPU.
|
||
fn polar_round_trip_on_the_cpu(plane: &raster_kernels::effect_kernels::Plane<[f32; 4]>, transform: DAffine2) -> raster_kernels::effect_kernels::Plane<[f32; 4]> {
|
||
use graphic_types::resampling::{FrameWarp, warp_frame};
|
||
use raster_kernels::resample_kernels::frame_warped;
|
||
|
||
let Some(square) = warp_frame(transform, DAffine2::IDENTITY) else {
|
||
panic!("{transform} has no square")
|
||
};
|
||
let unwrapped = frame_warped(plane, &FrameWarp::Polar { inverse: true }, &square);
|
||
frame_warped(&unwrapped, &FrameWarp::Polar { inverse: false }, &square)
|
||
}
|
||
|
||
#[test]
|
||
fn polar_coordinates_round_trip_opaque_content_without_a_seam() {
|
||
use glam::DVec2;
|
||
use graphic_types::resampling::warp_frame;
|
||
|
||
let (_, plane) = opaque_polar_content();
|
||
for transform in polar_seam_squares() {
|
||
let round_trip = polar_round_trip_on_the_cpu(&plane, transform);
|
||
let Some(square) = warp_frame(transform, DAffine2::IDENTITY) else {
|
||
panic!("{transform} has no square")
|
||
};
|
||
let (to_local, half) = (square.pixels_to_local(), square.size / 2.);
|
||
|
||
// Around the center and along the seam straight up from it, away from the rim, each texel shows the opaque content as those beside it do
|
||
for (index, texel) in round_trip.data.iter().enumerate() {
|
||
let (x, y) = (index % 160, index / 160);
|
||
let local = to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||
if local.x.abs() > 1.5 || !(-half.y + 2. ..1.5).contains(&local.y) {
|
||
continue;
|
||
}
|
||
|
||
let difference = texel.iter().zip(&plane.data[index]).map(|(actual, expected)| (actual - expected).abs()).fold(0., f32::max);
|
||
assert!(difference < 0.01, "({x}, {y}) on the seam within {transform} shows {texel:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn polar_coordinates_round_trip_without_a_seam_on_the_gpu_as_on_the_cpu() {
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let (texels, plane) = opaque_polar_content();
|
||
for transform in polar_seam_squares() {
|
||
let [unwrap, wrap] = [true, false].map(|inverse| EffectOperation::PolarCoordinates { inverse, transform });
|
||
let Some(gpu) = gpu_effect_texels(&Effects::from_operations([unwrap, wrap]), &texels, 160, &[]) else {
|
||
return;
|
||
};
|
||
let cpu = polar_round_trip_on_the_cpu(&plane, transform);
|
||
|
||
let levels = (gpu.iter().zip(&cpu.data))
|
||
.flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.))
|
||
.fold(0_f32, f32::max);
|
||
assert!(levels <= 1., "the round trip within {transform} strays from the CPU's kernel by {levels} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn motion_blurs_of_negative_distances_smear_as_positive_ones_do_on_the_cpu_and_gpu() {
|
||
use graphic_types::EffectOperation;
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::new(160, 160);
|
||
for (angle, distance) in [(0., 12.), (30., 7.5), (-70., 90.)] {
|
||
let [positive, negative] = [distance, -distance].map(|distance| patterned_raster(55., &[EffectOperation::MotionBlur { angle, distance, gamma: false }], 1.));
|
||
let Some(worst) = gpu_and_cpu_difference(negative.clone(), size) else { return };
|
||
assert!(worst <= 3, "a line {distance} long backward at {angle} degrees differs from the GPU by up to {worst} levels");
|
||
|
||
let draw = |item: &core_types::list::Item<_>| {
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone()));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
let (Some(forward), Some(backward)) = (draw(&positive), draw(&negative)) else { return };
|
||
assert!(forward == backward, "a line {distance} long at {angle} degrees smears differently backward on the GPU");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn elliptical_radial_blurs_match_on_the_cpu_and_gpu_whatever_their_transforms_size() {
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, RadialBlurMethod};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let radial = |method, transform| EffectOperation::RadialBlur {
|
||
method,
|
||
amount: 40.,
|
||
transform,
|
||
gamma: false,
|
||
};
|
||
let draw = |operation: &EffectOperation| {
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(55., std::slice::from_ref(operation), 1.)));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
// The most two renders differ by in levels of their premultiplied channels
|
||
let same = |first: &[[u8; 4]], second: &[[u8; 4]]| {
|
||
let difference = |(first, second): (&[u8; 4], &[u8; 4])| {
|
||
let (first, second) = (premultiplied_levels(*first), premultiplied_levels(*second));
|
||
(0..4).map(|channel| (first[channel] - second[channel]).abs()).fold(0., f32::max)
|
||
};
|
||
first.iter().zip(second).map(difference).fold(0., f32::max)
|
||
};
|
||
|
||
// About the image's middle and a point beyond its corner, along circles stretched across, turned, and slanted
|
||
let centers = [DAffine2::from_translation(DVec2::new(25., 27.)), DAffine2::from_translation(DVec2::new(-10., 60.))];
|
||
let shapes = [
|
||
DAffine2::from_scale(DVec2::new(3., 1.)),
|
||
DAffine2::from_angle(0.7) * DAffine2::from_scale(DVec2::new(1., 2.5)),
|
||
DAffine2::from_cols_array(&[1., 0., 0.8, 1., 0., 0.]),
|
||
];
|
||
for method in [RadialBlurMethod::Spin, RadialBlurMethod::Zoom] {
|
||
for (center, shape) in centers.into_iter().flat_map(|center| shapes.map(|shape| (center, shape))) {
|
||
let blur = radial(method, center * shape);
|
||
let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&blur), 1.), size) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{blur:?} differs from the GPU by up to {worst} levels");
|
||
|
||
// Scaling the transform evenly changes nothing but rounding
|
||
let (Some(blurred), Some(scaled)) = (draw(&blur), draw(&radial(method, center * shape * DAffine2::from_scale(DVec2::splat(6.))))) else {
|
||
return;
|
||
};
|
||
assert!(same(&blurred, &scaled) <= 2., "{blur:?} changes as its transform scales evenly");
|
||
}
|
||
|
||
// A round transform, however large and turned, blurs as its center alone does
|
||
for center in centers {
|
||
let (Some(alone), Some(round)) = (
|
||
draw(&radial(method, center)),
|
||
draw(&radial(method, center * DAffine2::from_angle(1.) * DAffine2::from_scale(DVec2::splat(30.)))),
|
||
) else {
|
||
return;
|
||
};
|
||
assert!(same(&alone, &round) <= 2., "{method:?} about {center} changes along circles");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn bands_read_from_past_the_view_along_their_rows() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A white square 1000 across bent across within a band as wide, with the band's square far below a view of the left tenth, whose rows read from twice as far right as the view reaches
|
||
let spherize = EffectOperation::Spherize {
|
||
amount: 100.,
|
||
cylindrical: true,
|
||
transform: DAffine2::from_translation(DVec2::new(500., 2000.)) * DAffine2::from_scale(DVec2::new(1000., 10.)),
|
||
};
|
||
let mut square = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, GraphicColor::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(1000.)));
|
||
stamp_effect(&mut square, Effect::new(&spherize));
|
||
let graphic = Graphic::RasterCPU(Box::new(square));
|
||
|
||
// Each bent row reads the square from right of the view, so it stays white
|
||
let size = UVec2::new(100, 1000);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
for (x, y) in [0, 510, 999].into_iter().flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
assert_eq!(pixel(&pixels, size, x, y), [255; 4], "the bent row reads nothing at ({x}, {y})");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn svgs_draw_warps_on_groups_of_endless_content_as_the_gpu_does_masking_them_once() {
|
||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||
use core_types::transform::Footprint;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::vector_types::gradient::Gradient;
|
||
use graphic_types::{EffectOperation, Effects, Graphic, MaskMode};
|
||
use rendering::deferred_image::MAX_DEFERRED_IMAGE_PIXELS;
|
||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||
|
||
// A group holding a gradient across the view, warped within a circle 40 across about its middle: twirled (also after an inverted endless mask hides it by half), wrapped within the square around it, or pinched to read from past the view
|
||
let size = UVec2::splat(64);
|
||
let circle = DAffine2::from_translation(DVec2::splat(32.)) * DAffine2::from_scale(DVec2::splat(40.));
|
||
let twirl = EffectOperation::Twirl { angle: 180., transform: circle };
|
||
let wrap = EffectOperation::PolarCoordinates { inverse: false, transform: circle };
|
||
let pinch = EffectOperation::Pinch { amount: 1000., transform: circle };
|
||
let half_hidden = EffectOperation::Mask {
|
||
mask: Graphic::from(GraphicColor::WHITE),
|
||
mode: MaskMode::default(),
|
||
density: 50.,
|
||
feather: 0.,
|
||
invert: true,
|
||
};
|
||
let gradient = Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE])).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
|
||
|
||
for effects in [vec![twirl.clone()], vec![half_hidden, twirl], vec![wrap], vec![pinch]] {
|
||
let group = Item::new_from_element(Graphic::Gradient(gradient.clone())).with_attribute(ATTR_EFFECTS, Effects::from_operations(effects.clone()));
|
||
let graphic = Graphic::Graphic(Box::new(group));
|
||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// Wrapping clears the gradient outside its square, from 12 to 52
|
||
if matches!(effects[..], [EffectOperation::PolarCoordinates { .. }]) {
|
||
assert_eq!(pixel(&gpu, size, 5, 30)[3], 0, "the wrap leaves the gradient outside its square");
|
||
}
|
||
|
||
// SVG draws the group as the GPU's image of the area in view
|
||
let footprint = Footprint {
|
||
transform: DAffine2::IDENTITY,
|
||
resolution: size,
|
||
..Default::default()
|
||
};
|
||
let mut render = SvgRender::new();
|
||
List::new_from_element(graphic).render_svg(
|
||
&mut render,
|
||
&RenderParams {
|
||
view: Some(footprint),
|
||
for_export: true,
|
||
..Default::default()
|
||
},
|
||
);
|
||
let [deferred] = &render.deferred_images[..] else {
|
||
panic!("{effects:?} draws {} images", render.deferred_images.len())
|
||
};
|
||
let Some(executor) = executor() else { return };
|
||
let _turn = take_turn();
|
||
let layout = deferred.layout(footprint.transform, size.as_dvec2(), MAX_DEFERRED_IMAGE_PIXELS).expect("the image is in view");
|
||
let rendered = executor.render_deferred_svg_images(&render.deferred_images, footprint);
|
||
let [(_, texture)] = &rendered[..] else { panic!("expected one image, got {}", rendered.len()) };
|
||
let image = executor.read_texture_pixels(texture).expect("the image reads back");
|
||
|
||
// The image matches the GPU's render of the view
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let texel = layout.document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor().as_uvec2();
|
||
let index = ((texel.y * layout.size.x + texel.x) * 4) as usize;
|
||
let (expected, actual) = (premultiplied_levels(pixel(&gpu, size, x, y)), premultiplied_levels(image[index..index + 4].try_into().unwrap()));
|
||
let difference = (0..4).map(|channel| (expected[channel] - actual[channel]).abs()).fold(0., f32::max);
|
||
assert!(difference <= 2., "{effects:?} draws {actual:?} at ({x}, {y}) rather than the GPU's {expected:?}");
|
||
}
|
||
|
||
// Nothing in the SVG masks the image again
|
||
let mut svg = render.svg.to_svg_string();
|
||
futures::executor::block_on(executor.resolve_deferred_svg_images(&mut svg, &mut Vec::new(), rendered));
|
||
assert!(svg.contains("data:image/png;base64,") && !svg.contains("mask="), "{effects:?} draws {svg}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warps_bend_endless_gradients_within_their_circle() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A gradient from black to white across the render, twirled within a circle 40 across about its middle
|
||
let stops = [(0., 0.), (1., 1.)].map(|(position, gray)| GradientStop {
|
||
position,
|
||
midpoint: 0.5,
|
||
color: GraphicColor::from_gamma_srgb_channels(gray, gray, gray, 1.),
|
||
});
|
||
let size = UVec2::splat(64);
|
||
let gradient = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
|
||
let mut twirled = gradient.clone();
|
||
let twirl = EffectOperation::Twirl {
|
||
angle: 180.,
|
||
transform: DAffine2::from_translation(DVec2::splat(32.)) * DAffine2::from_scale(DVec2::splat(40.)),
|
||
};
|
||
stamp_effect(&mut twirled, Effect::new(&twirl));
|
||
|
||
let draw = |graphic: Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||
let (Some(plain), Some(twirled)) = (draw(Graphic::Gradient(gradient)), draw(Graphic::Gradient(twirled))) else {
|
||
return;
|
||
};
|
||
|
||
// Past the circle the gradient stays as it is, and within it the twirl turns the gradient's levels
|
||
let mut turned = false;
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let distance = DVec2::new(x as f64 + 0.5, y as f64 + 0.5).distance(DVec2::splat(32.));
|
||
let difference = pixel(&plain, size, x, y)
|
||
.iter()
|
||
.zip(pixel(&twirled, size, x, y))
|
||
.map(|(plain, twirled)| plain.abs_diff(twirled))
|
||
.max()
|
||
.unwrap_or_default();
|
||
assert!(distance < 21. || difference <= 2, "the twirl changes ({x}, {y}) past its circle");
|
||
turned |= difference > 20;
|
||
}
|
||
assert!(turned, "the twirl leaves the gradient as it is within its circle");
|
||
}
|
||
|
||
#[test]
|
||
fn frame_relative_effects_carry_what_earlier_effects_paint_past_the_frame_on_the_cpu_and_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{EffectKind, EffectOperation, WaveType};
|
||
|
||
// A shadow cast down and right and a glow all around, each painting well past the content's frame
|
||
let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.9), DVec2::new(6., 8.), 4., 0.);
|
||
let mut glow = EffectOperation::default_for(EffectKind::OuterGlow);
|
||
if let EffectOperation::OuterGlow { size, spread, .. } = &mut glow {
|
||
(*size, *spread) = (9., 40.);
|
||
}
|
||
|
||
// The warps act within the image 50 pixels across, measured from its corner
|
||
let transform = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
let effects = [
|
||
EffectOperation::Twirl { angle: 140., transform },
|
||
EffectOperation::Spherize {
|
||
amount: -80.,
|
||
cylindrical: true,
|
||
transform,
|
||
},
|
||
EffectOperation::Spherize {
|
||
amount: 60.,
|
||
cylindrical: true,
|
||
transform: transform * DAffine2::from_angle(std::f64::consts::FRAC_PI_2),
|
||
},
|
||
EffectOperation::PolarCoordinates { inverse: false, transform },
|
||
EffectOperation::Ripple {
|
||
amount: 300.,
|
||
size: 16.,
|
||
edge_mode: GradientSpread::Pad,
|
||
},
|
||
EffectOperation::Wave {
|
||
wave_type: WaveType::Sine,
|
||
total_generators: 3,
|
||
wavelength_min: 9.,
|
||
wavelength_max: 30.,
|
||
amplitude_min: 1.,
|
||
amplitude_max: 4.,
|
||
horizontal_scale: 100.,
|
||
vertical_scale: 70.,
|
||
edge_mode: GradientSpread::Repeat,
|
||
seed: 7,
|
||
},
|
||
EffectOperation::Pixelate { cell_size: 7.3, offset: DVec2::ZERO },
|
||
EffectOperation::Pixelate {
|
||
cell_size: 10.,
|
||
offset: DVec2::new(4.5, -3.2),
|
||
},
|
||
EffectOperation::ColorHalftone {
|
||
radius: 6.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: DVec2::ZERO,
|
||
phase: 0.,
|
||
},
|
||
EffectOperation::ColorHalftone {
|
||
radius: 4.,
|
||
red_angle: 45.,
|
||
green_angle: 45.,
|
||
blue_angle: 45.,
|
||
offset: DVec2::new(-9., 14.),
|
||
phase: 50.,
|
||
},
|
||
];
|
||
// Image maps placed on the frame, leaving what's past it in place, or reaching past it to move that too.
|
||
// Each lies a pixel to each of the content's, so the GPU's interpolation can't round a level differently and move a hard edge.
|
||
let image = |offset: f64, size: u32, level: fn(f32, f32) -> f32| {
|
||
let placement = DAffine2::from_translation(DVec2::splat(offset)) * DAffine2::from_scale(DVec2::splat(size as f64));
|
||
gray_map(size, size, placement, level)
|
||
};
|
||
let (across, down): (fn(f32, f32) -> f32, fn(f32, f32) -> f32) = (|x, _| 60. + 3. * x, |_, y| 200. - 2. * y);
|
||
let displace = |offset, size, edge_mode| x_and_y_displacement((image(offset, size, across), 7.68), (image(offset, size, down), -6.4), edge_mode);
|
||
let effects = effects.into_iter().chain([
|
||
displace(55., 50, GradientSpread::Clear),
|
||
displace(55., 50, GradientSpread::Pad),
|
||
angle_displacement(image(55., 50, down), 120., 10., GradientSpread::Reflect),
|
||
displace(48., 64, GradientSpread::Clear),
|
||
]);
|
||
let effects: Vec<EffectOperation> = effects.collect();
|
||
for (earlier, effect) in [&shadow, &glow].into_iter().flat_map(|earlier| effects.iter().map(move |effect| (earlier, effect))) {
|
||
for fill in [1., 0.5] {
|
||
let chain = [earlier.clone(), effect.clone()];
|
||
let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., &chain, fill), UVec2::new(160, 160)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{chain:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn frame_relative_effects_read_nothing_of_the_contents_edge_past_a_frame_cutting_through_texels() {
|
||
use graphic_types::EffectOperation;
|
||
use graphic_types::vector_types::GradientSpread;
|
||
|
||
// A white square from 10.3 to 30.3, so the frame's sides cut through texels holding the content's antialiased edge, with nothing past the frame to carry
|
||
let ripple = |edge_mode| EffectOperation::Ripple { amount: 300., size: 16., edge_mode };
|
||
let size = UVec2::splat(48);
|
||
for effect in [
|
||
ripple(GradientSpread::Pad),
|
||
ripple(GradientSpread::Repeat),
|
||
ripple(GradientSpread::Reflect),
|
||
EffectOperation::Pixelate {
|
||
cell_size: 7.3,
|
||
offset: glam::DVec2::ZERO,
|
||
},
|
||
] {
|
||
let Some(pixels) = render_square_with_effects(vec![effect.clone()], 1., 10.3, 30.3, size) else {
|
||
return;
|
||
};
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let past_frame = !(10..=30).contains(&x) || !(10..=30).contains(&y);
|
||
assert!(!past_frame || pixel(&pixels, size, x, y)[3] == 0, "{effect:?} paints {:?} at ({x}, {y})", pixel(&pixels, size, x, y));
|
||
|
||
// The texels wholly within the frame read or average those wholly within it, which are opaque, rather than the content's edge
|
||
let within_frame = (11..30).contains(&x) && (11..30).contains(&y);
|
||
assert!(!within_frame || pixel(&pixels, size, x, y)[3] == 255, "{effect:?} fades ({x}, {y}) to {:?}", pixel(&pixels, size, x, y));
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn procedural_displacements_stay_put_as_the_frame_grows_far_from_the_contents_origin() {
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{EffectOperation, WaveType};
|
||
|
||
// The content's origin lies 2^24 units away, where single precision tells only every other unit apart, so a pattern measured from there would jump as the frame grows by one
|
||
let far_origin = DAffine2::from_translation(glam::DVec2::new(-16_777_216., 3.));
|
||
let ripple = EffectOperation::Ripple {
|
||
amount: 300.,
|
||
size: 16.,
|
||
edge_mode: GradientSpread::Clear,
|
||
};
|
||
let wave = EffectOperation::Wave {
|
||
wave_type: WaveType::Triangle,
|
||
total_generators: 5,
|
||
wavelength_min: 10.,
|
||
wavelength_max: 40.,
|
||
amplitude_min: 2.,
|
||
amplitude_max: 6.,
|
||
horizontal_scale: 100.,
|
||
vertical_scale: 100.,
|
||
edge_mode: GradientSpread::Clear,
|
||
seed: 7,
|
||
};
|
||
|
||
let size = UVec2::splat(64);
|
||
let mut square = BezPath::new();
|
||
square.move_to((14., 14.));
|
||
[(50., 14.), (50., 50.), (14., 50.)].into_iter().for_each(|corner| square.line_to(corner));
|
||
square.close_path();
|
||
let render_with_frame = |effect: &EffectOperation, left: f64| {
|
||
let effects = graphic_types::Effects::from_operations(vec![effect.clone()]);
|
||
let placement = graphic_types::resampling::frame_of_bounds([glam::DVec2::new(left, 14.), glam::DVec2::splat(50.)], DAffine2::IDENTITY);
|
||
render(size, |scene| {
|
||
scene.draw_effects(
|
||
&effects,
|
||
1.,
|
||
1.,
|
||
BlendMode::Normal,
|
||
true,
|
||
Some(vello_gpu::kurbo::Shape::bounding_box(&square)),
|
||
far_origin,
|
||
Some((placement, 0.)),
|
||
&mut |_, _| {},
|
||
&mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 255, 255), None, &square),
|
||
)
|
||
})
|
||
};
|
||
|
||
for effect in [ripple, wave] {
|
||
let (Some(original), Some(grown)) = (render_with_frame(&effect, 14.), render_with_frame(&effect, 13.)) else {
|
||
return;
|
||
};
|
||
let worst = original.iter().zip(&grown).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| a.abs_diff(*b))).max().unwrap_or(0);
|
||
assert!(worst <= 1, "{effect:?} moves by up to {worst} levels as its frame grows");
|
||
}
|
||
}
|
||
|
||
/// A render `size` across of a white square, the unit square `placement` puts in the scene, drawn through `effects` relative to its frame, with that frame.
|
||
fn square_through_effects(effects: Vec<graphic_types::EffectOperation>, placement: DAffine2, size: UVec2) -> Option<(Vec<[u8; 4]>, graphic_types::resampling::EffectFrame)> {
|
||
let corners = [glam::DVec2::ZERO, glam::DVec2::X, glam::DVec2::ONE, glam::DVec2::Y].map(|corner| placement.transform_point2(corner));
|
||
let mut square = BezPath::new();
|
||
square.move_to((corners[0].x, corners[0].y));
|
||
corners[1..].iter().for_each(|corner| square.line_to((corner.x, corner.y)));
|
||
square.close_path();
|
||
let bounds = vello_gpu::kurbo::Shape::bounding_box(&square);
|
||
|
||
let effects = graphic_types::Effects::from_operations(effects);
|
||
let pixels = render(size, |scene| {
|
||
scene.draw_effects(
|
||
&effects,
|
||
1.,
|
||
1.,
|
||
BlendMode::Normal,
|
||
true,
|
||
Some(bounds),
|
||
DAffine2::IDENTITY,
|
||
Some((placement, 0.)),
|
||
&mut |_, _| {},
|
||
&mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 255, 255), None, &square),
|
||
)
|
||
})?;
|
||
|
||
Some((pixels, graphic_types::resampling::EffectFrame::new(placement, DAffine2::IDENTITY)?))
|
||
}
|
||
|
||
/// The texels of a render `size` across that a white square, the unit square `placement` puts in the scene, paints through `effects` relative to its frame, which lie past the frame by more than a texel reaches along its sides.
|
||
fn texels_past_frame_through_effects(effects: Vec<graphic_types::EffectOperation>, placement: DAffine2, size: UVec2) -> Option<Vec<(u32, u32, [u8; 4])>> {
|
||
let (pixels, frame) = square_through_effects(effects, placement, size)?;
|
||
let (to_local, half, extent) = (frame.pixels_to_local(), frame.size / 2., frame.pixel_extent());
|
||
let past = (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))).filter(|&(x, y)| {
|
||
let center = to_local.transform_point2(glam::DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||
(center.abs() - half).cmpge(extent).any()
|
||
});
|
||
Some(past.map(|(x, y)| (x, y, pixel(&pixels, size, x, y))).collect())
|
||
}
|
||
|
||
#[test]
|
||
fn frame_relative_effects_read_nothing_of_the_contents_edge_past_a_turned_frame() {
|
||
use graphic_types::EffectOperation;
|
||
use graphic_types::vector_types::GradientSpread;
|
||
|
||
// A square 30 across turned 45 degrees about the middle of the render, so its sides cut through texels at every offset, with nothing past the frame to carry
|
||
let ripple = |edge_mode| EffectOperation::Ripple { amount: 300., size: 16., edge_mode };
|
||
let placement = DAffine2::from_translation(glam::DVec2::splat(32.))
|
||
* DAffine2::from_angle(std::f64::consts::FRAC_PI_4)
|
||
* DAffine2::from_scale(glam::DVec2::splat(30.))
|
||
* DAffine2::from_translation(glam::DVec2::splat(-0.5));
|
||
for effect in [
|
||
ripple(GradientSpread::Pad),
|
||
ripple(GradientSpread::Repeat),
|
||
ripple(GradientSpread::Reflect),
|
||
EffectOperation::Pixelate {
|
||
cell_size: 7.3,
|
||
offset: glam::DVec2::ZERO,
|
||
},
|
||
] {
|
||
let Some(past) = texels_past_frame_through_effects(vec![effect.clone()], placement, UVec2::splat(64)) else {
|
||
return;
|
||
};
|
||
for (x, y, color) in past {
|
||
assert_eq!(color[3], 0, "{effect:?} paints {color:?} at ({x}, {y})");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn frame_relative_effects_carry_a_shadow_past_a_turned_frame_without_holes_or_fades() {
|
||
use graphic_types::EffectOperation;
|
||
use graphic_types::vector_types::GradientSpread;
|
||
|
||
// A square 30 across turned 30 degrees, over a hard shadow of half alpha reaching 24 past it, which the displacements carry past the frame
|
||
let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0., 0., 0., 0.5), glam::DVec2::ZERO, 24., 100.);
|
||
let ripple = |edge_mode| EffectOperation::Ripple { amount: 300., size: 16., edge_mode };
|
||
let placement = DAffine2::from_translation(glam::DVec2::new(48.3, 48.))
|
||
* DAffine2::from_angle(30_f64.to_radians())
|
||
* DAffine2::from_scale(glam::DVec2::splat(30.))
|
||
* DAffine2::from_translation(glam::DVec2::splat(-0.5));
|
||
let size = UVec2::splat(96);
|
||
for effect in [ripple(GradientSpread::Pad), ripple(GradientSpread::Repeat), ripple(GradientSpread::Reflect)] {
|
||
let Some((pixels, frame)) = square_through_effects(vec![shadow.clone(), effect.clone()], placement, size) else {
|
||
return;
|
||
};
|
||
let (to_local, half, extent) = (frame.pixels_to_local(), frame.size / 2., frame.pixel_extent());
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let past_sides = to_local.transform_point2(glam::DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).abs() - half;
|
||
let alpha = pixel(&pixels, size, x, y)[3];
|
||
|
||
// Just past the frame each texel shows the shadow rather than a hole, and wholly within it the opaque content
|
||
let just_past = past_sides.cmpge(extent).any() && past_sides.max_element() < 6.;
|
||
assert!(!just_past || (120..=136).contains(&alpha), "{effect:?} leaves {alpha} at ({x}, {y}) past the frame");
|
||
assert!(!(-past_sides).cmpge(extent).all() || alpha == 255, "{effect:?} fades ({x}, {y}) within the frame to {alpha}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn neutral_displacement_maps_keep_content_covering_no_texel_wholly_and_its_blurs_as_they_are_on_the_cpu_and_gpu() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, List};
|
||
use glam::DVec2;
|
||
use graphic_types::resampling::{DISPLACEMENT_NEUTRAL_LEVEL, EffectFrame, frame_of_bounds};
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
|
||
use raster_kernels::effect_kernels::Plane;
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let level = DISPLACEMENT_NEUTRAL_LEVEL as f32 / 255.;
|
||
let neutral = Graphic::from(GraphicColor::from_gamma_srgb_channels(level, level, level, 1.));
|
||
|
||
// A box blur spreads each strip's paint two texels past its frame
|
||
let box_blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 2.,
|
||
box_blur: true,
|
||
gamma: false,
|
||
};
|
||
|
||
// White strips 20 tall, none covering a texel across wholly: a texel wide a quarter off the texels, half a texel wide within one, 0.3 wide across two, and 1.5 wide.
|
||
// A view this large keeps the region the displacement reaches past the blur at full resolution.
|
||
let size = UVec2::new(48, 48);
|
||
for (left, right) in [(10.25, 11.25), (10.25, 10.75), (10.85, 11.15), (10.25, 11.75)] {
|
||
let mut strip = Vector::item_from_bezpath(&Rect::new(left, 6., right, 26.).to_path(0.1));
|
||
strip.set_attribute(
|
||
ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
|
||
);
|
||
let frame = EffectFrame::new(frame_of_bounds([DVec2::new(left, 6.), DVec2::new(right, 26.)], DAffine2::IDENTITY), DAffine2::IDENTITY).unwrap();
|
||
|
||
for before in [None, Some(box_blur.clone())] {
|
||
let plain = Graphic::Vector(Box::new(strip.clone().with_attribute(ATTR_EFFECTS, Effects::from_operations(before.clone()))));
|
||
let Some(plain) = render(size, |scene| plain.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let plane = Plane {
|
||
width: size.x as usize,
|
||
height: size.y as usize,
|
||
data: plain.iter().map(|pixel| [pixel[3] as f32 / 255.; 4]).collect(),
|
||
};
|
||
let blurred = if before.is_some() { "blurred " } else { "" };
|
||
|
||
for edge_mode in [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect] {
|
||
let displace = match edge_mode {
|
||
GradientSpread::Repeat => angle_displacement(neutral.clone(), 135., 20., edge_mode),
|
||
_ => x_and_y_displacement((neutral.clone(), 12.8), (neutral.clone(), 12.8), edge_mode),
|
||
};
|
||
let displaced = Graphic::Vector(Box::new(
|
||
strip.clone().with_attribute(ATTR_EFFECTS, Effects::from_operations(before.clone().into_iter().chain([displace]))),
|
||
));
|
||
let Some(gpu) = render(size, |scene| displaced.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let cpu = raster_kernels::resample_kernels::displaced(&plane, |_, _| DVec2::ZERO, &frame, edge_mode);
|
||
|
||
// Moved nowhere, each texel keeps the coverage it had, as the CPU's kernel keeps it
|
||
for (index, ((plain, gpu), cpu)) in plain.iter().zip(&gpu).zip(&cpu.data).enumerate() {
|
||
let cpu = (cpu[3] * 255.).round() as u8;
|
||
assert!(
|
||
plain[3].abs_diff(gpu[3]) <= 1 && cpu.abs_diff(gpu[3]) <= 1,
|
||
"texel {index} of the {blurred}strip from {left} to {right} draws {} rather than {} (the CPU's {cpu}) with {edge_mode:?}",
|
||
gpu[3],
|
||
plain[3]
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn displacement_maps_match_on_the_cpu_and_gpu() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||
use graphic_types::{EffectOperation, Graphic, stamp_effect};
|
||
|
||
// Opaque content smooth enough, even where it wraps around, that a map level apart moves it by a level or two, so the maps themselves are what's compared.
|
||
// The modes keep what's read within the content, since moving its edge by a level's fraction of a pixel changes its alpha by much more.
|
||
let on_content = DAffine2::from_translation(DVec2::splat(55.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
let content = |effects: &[EffectOperation]| {
|
||
let data = (0..50 * 50)
|
||
.map(|index| {
|
||
let turn = |along: f32| along / 50. * std::f32::consts::TAU;
|
||
let (x, y) = ((index % 50) as f32 + 0.5, (index / 50) as f32 + 0.5);
|
||
GraphicColor::from_gamma_srgb_channels(0.5 + 0.25 * turn(x).sin(), 0.5 + 0.25 * turn(y).cos(), 0.5 + 0.2 * turn(x + y).sin(), 1.)
|
||
})
|
||
.collect();
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 50, height: 50, data })).with_attribute(ATTR_TRANSFORM, on_content);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, stamped_at(operation, on_content)));
|
||
item
|
||
};
|
||
|
||
// Maps of whole 8-bit levels placed across the content but not one to one on its pixels: an image and a gradient, each along an angle, and the two across and down
|
||
let image = gray_map(13, 9, on_content, |x, y| 90. + 9. * x - 5. * y);
|
||
let stops = [(0., 0.2), (1., 0.8)].map(|(position, gray)| GradientStop {
|
||
position,
|
||
midpoint: 0.5,
|
||
color: GraphicColor::from_gamma_srgb_channels(gray, gray, gray, 1.),
|
||
});
|
||
let gradient = Graphic::from(Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, on_content));
|
||
|
||
for edge_mode in [GradientSpread::Repeat, GradientSpread::Pad, GradientSpread::Reflect] {
|
||
let displacements = [
|
||
("image map", angle_displacement(image.clone(), 120., 32., edge_mode)),
|
||
("gradient map", angle_displacement(gradient.clone(), -30., 32., edge_mode)),
|
||
(
|
||
"image map across and gradient map down",
|
||
x_and_y_displacement((image.clone(), 25.6), (gradient.clone(), -19.2), edge_mode),
|
||
),
|
||
];
|
||
for (name, displace) in displacements {
|
||
let Some(worst) = gpu_and_cpu_difference(content(&[displace]), UVec2::new(160, 160)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "the {name} with {edge_mode:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn image_displacement_maps_take_their_own_adjustments_and_opacity() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_OPACITY, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Smooth opaque content kept within its frame, so the maps themselves are what's compared
|
||
let on_content = DAffine2::from_translation(DVec2::splat(55.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
let content = |map: Item<Raster<CPU>>, strength: f64| {
|
||
let data = (0..50 * 50)
|
||
.map(|index| {
|
||
let turn = |along: f32| along / 50. * std::f32::consts::TAU;
|
||
let (x, y) = ((index % 50) as f32 + 0.5, (index / 50) as f32 + 0.5);
|
||
GraphicColor::from_gamma_srgb_channels(0.5 + 0.25 * turn(x).sin(), 0.5 + 0.25 * turn(y).cos(), 0.5 + 0.2 * turn(x + y).sin(), 1.)
|
||
})
|
||
.collect();
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 50, height: 50, data })).with_attribute(ATTR_TRANSFORM, on_content);
|
||
let map = Graphic::from(map.with_attribute(ATTR_TRANSFORM, on_content));
|
||
let displace = x_and_y_displacement((map.clone(), 25.6 * strength), (map, -19.2 * strength), GradientSpread::Repeat);
|
||
stamp_effect(&mut item, stamped_at(&displace, on_content));
|
||
item
|
||
};
|
||
let data = (0..13 * 9)
|
||
.map(|index| {
|
||
let (x, y) = ((index % 13) as f32, (index / 13) as f32);
|
||
GraphicColor::from_gamma_srgb_channels((90. + 9. * x - 5. * y) / 255., (170. - 11. * y + 3. * x) / 255., 0.5, 1.)
|
||
})
|
||
.collect();
|
||
let plain = Raster::new_cpu(Image { width: 13, height: 9, data });
|
||
|
||
// An inverted map at half opacity moves the content half as far as its inverted pixels do
|
||
let mut adjusted = Item::new_from_element(plain.clone()).with_attribute(ATTR_OPACITY, 0.5);
|
||
stamp_effect(&mut adjusted, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
|
||
let inverted = Item::new_from_element(raster_kernels::raster_effects::adjusted_raster(&plain, &[Adjustment::Invert]));
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let rendered = |item: Item<Raster<CPU>>| {
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
let Some(actual) = rendered(content(adjusted.clone(), 1.)) else { return };
|
||
let Some(expected) = rendered(content(inverted, 0.5)) else { return };
|
||
|
||
let worst = actual
|
||
.iter()
|
||
.zip(&expected)
|
||
.flat_map(|(actual, expected)| actual.iter().zip(expected))
|
||
.map(|(actual, expected)| actual.abs_diff(*expected));
|
||
let worst = worst.max().unwrap_or_default();
|
||
assert!(worst <= 3, "the map with its own adjustment and opacity differs by up to {worst} levels");
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(content(adjusted, 1.), size) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "the map with its own adjustment and opacity differs from the GPU by up to {worst} levels");
|
||
}
|
||
|
||
/// A 50 by 50 opaque checkerboard of 5 pixel squares at (55, 55), one pixel per document unit, carrying `effects`. Its hard edges show a move by a fraction of a pixel as that fraction of their contrast.
|
||
fn checkered_raster(effects: &[graphic_types::EffectOperation]) -> core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>> {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::stamp_effect;
|
||
|
||
let data = (0..50 * 50)
|
||
.map(|index| match (index % 50 / 5 + index / 50 / 5) % 2 {
|
||
0 => GraphicColor::from_gamma_srgb_channels(0.15, 0.2, 0.3, 1.),
|
||
_ => GraphicColor::from_gamma_srgb_channels(0.9, 0.85, 0.7, 1.),
|
||
})
|
||
.collect();
|
||
let placement = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 50, height: 50, data })).with_attribute(ATTR_TRANSFORM, placement);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, stamped_at(operation, placement)));
|
||
item
|
||
}
|
||
|
||
#[test]
|
||
fn displacement_maps_between_whole_levels_move_hard_edges_alike_on_the_cpu_and_gpu() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use graphic_types::Graphic;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||
|
||
// Maps drawing levels between the whole 8-bit ones across most of the content: a gradient, and an image stretched across more pixels than its own
|
||
let on_content = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
let stops = [
|
||
(0., GraphicColor::from_gamma_srgb_channels(0.42, 0.55, 0.5, 1.)),
|
||
(1., GraphicColor::from_gamma_srgb_channels(0.58, 0.45, 0.5, 1.)),
|
||
];
|
||
let gradient = Item::new_from_element(Gradient::new(stops.map(|(position, color)| GradientStop { position, midpoint: 0.5, color })));
|
||
let gradient = Graphic::from(gradient.with_attribute(ATTR_TRANSFORM, on_content));
|
||
let image = |alpha: fn(f32, f32) -> f32| {
|
||
let data = (0..13 * 9)
|
||
.map(|index| {
|
||
let (x, y) = ((index % 13) as f32, (index / 13) as f32);
|
||
GraphicColor::from_gamma_srgb_channels((110. + 3. * x - y) / 255., (140. - 3. * y + x) / 255., 0.5, alpha(x, y))
|
||
})
|
||
.collect();
|
||
Graphic::from(Item::new_from_element(Raster::new_cpu(Image { width: 13, height: 9, data })).with_attribute(ATTR_TRANSFORM, on_content))
|
||
};
|
||
|
||
// The image translucent from 30% to 90% across, which the GPU premultiplies into 8-bit texels
|
||
let translucent_image = image(|x, y| (76. + 11. * x + 3. * y) / 255.);
|
||
|
||
// A color a quarter of the way between two levels, which a solid fill rounds to the nearer
|
||
let color = Graphic::from(GraphicColor::from_gamma_srgb_channels(141.25 / 255., 113.75 / 255., 0.5, 1.));
|
||
|
||
// At these distances a level of a map's luminance moves the content about a pixel each way, so a level's fraction apart shows at every edge.
|
||
// The maps' colors of whole levels mix into luminances between them, which both renderers take from the same rounded colors.
|
||
let maps = [
|
||
("gradient", gradient),
|
||
("stretched image", image(|_, _| 1.)),
|
||
("translucent stretched image", translucent_image),
|
||
("color", color),
|
||
];
|
||
for (name, map) in maps {
|
||
for edge_mode in [GradientSpread::Repeat, GradientSpread::Pad, GradientSpread::Reflect] {
|
||
let displace = match edge_mode {
|
||
GradientSpread::Pad => angle_displacement(map.clone(), 135., 181., edge_mode),
|
||
_ => x_and_y_displacement((map.clone(), 128.), (map.clone(), -102.4), edge_mode),
|
||
};
|
||
let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[displace]), UVec2::new(160, 160)) else {
|
||
return;
|
||
};
|
||
if matches!(map, Graphic::RasterCPU(_)) && filters_8_bit_images_to_whole_levels() {
|
||
continue;
|
||
}
|
||
assert!(worst <= 3, "the {name} map with {edge_mode:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn displacement_maps_draw_with_their_own_opacity_and_effects_on_the_cpu_and_gpu() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||
use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect};
|
||
|
||
let on_content = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
|
||
// A gradient inverted at half opacity, and at half fill, which fades its ramp rather than its layer
|
||
let stops = [
|
||
(0., GraphicColor::from_gamma_srgb_channels(0.2, 0.8, 0.5, 1.)),
|
||
(1., GraphicColor::from_gamma_srgb_channels(0.8, 0.3, 0.5, 1.)),
|
||
];
|
||
let inverted_gradient = |opacity_attribute: &str| {
|
||
let mut gradient = Item::new_from_element(Gradient::new(stops.map(|(position, color)| GradientStop { position, midpoint: 0.5, color })))
|
||
.with_attribute(opacity_attribute, 0.5_f64)
|
||
.with_attribute(ATTR_TRANSFORM, on_content);
|
||
stamp_effect(&mut gradient, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
|
||
Graphic::from(gradient)
|
||
};
|
||
|
||
// An image at half opacity under a paint overlay, an effect it can't take into its pixels
|
||
let data = (0..13 * 9)
|
||
.map(|index| {
|
||
let (x, y) = ((index % 13) as f32, (index / 13) as f32);
|
||
GraphicColor::from_gamma_srgb_channels((90. + 9. * x - 5. * y) / 255., (170. - 11. * y + 3. * x) / 255., 0.5, 1.)
|
||
})
|
||
.collect();
|
||
let plain = Raster::new_cpu(Image { width: 13, height: 9, data });
|
||
let mut image = Item::new_from_element(plain.clone()).with_attribute(ATTR_OPACITY, 0.5_f64).with_attribute(ATTR_TRANSFORM, on_content);
|
||
stamp_effect(&mut image, Effect::new(&color_overlay([0.2, 0.9, 0.5], BlendMode::Normal, 0.5)));
|
||
|
||
// The plain image at half opacity in a group, and in a list at half opacity over itself inverted
|
||
let placed = |raster: Raster<CPU>| Item::new_from_element(Graphic::from(Item::new_from_element(raster).with_attribute(ATTR_TRANSFORM, on_content)));
|
||
let group = Graphic::Graphic(Box::new(placed(plain.clone()).with_attribute(ATTR_OPACITY, 0.5_f64)));
|
||
let inverted = raster_kernels::raster_effects::adjusted_raster(&plain, &[Adjustment::Invert]);
|
||
let list = Graphic::GraphicList([placed(inverted), placed(plain).with_attribute(ATTR_OPACITY, 0.5_f64)].into_iter().collect::<List<_>>());
|
||
|
||
let displace = |map: Graphic| angle_displacement(map, 140., 64., GradientSpread::Repeat);
|
||
// Each with whether it draws a plain image straight from its 8-bit texture
|
||
let maps = [
|
||
("gradient", inverted_gradient(ATTR_OPACITY), false),
|
||
("filled gradient", inverted_gradient(ATTR_OPACITY_FILL), false),
|
||
("image", Graphic::from(image), false),
|
||
("group", group, true),
|
||
("list", list, true),
|
||
];
|
||
let size = UVec2::new(160, 160);
|
||
for (name, map, plain_image) in maps {
|
||
let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[displace(map)]), size) else {
|
||
return;
|
||
};
|
||
if plain_image && filters_8_bit_images_to_whole_levels() {
|
||
continue;
|
||
}
|
||
assert!(worst <= 3, "the {name} map differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn gpu_image_displacement_maps_draw_as_cpu_images_do() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::Graphic;
|
||
use graphic_types::raster_types::{GPU, Image, Raster};
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use rendering::{Render, RenderParams};
|
||
use wgpu::util::DeviceExt;
|
||
|
||
let Some(executor) = executor() else { return };
|
||
|
||
// The same 7 by 5 map of whole levels as a CPU image and as a texture, each placed on the content
|
||
let on_content = DAffine2::from_translation(DVec2::splat(55.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
let levels: Vec<[u8; 4]> = (0..7 * 5)
|
||
.map(|index| [90 + 9 * (index % 7) - 5 * (index / 7), 170 - 11 * (index / 7) + 3 * (index % 7), 128, 255])
|
||
.collect();
|
||
let data = levels
|
||
.iter()
|
||
.map(|&[red, green, blue, _]| GraphicColor::from_gamma_srgb_channels(red as f32 / 255., green as f32 / 255., blue as f32 / 255., 1.));
|
||
let cpu_map = Item::new_from_element(Raster::new_cpu(Image {
|
||
width: 7,
|
||
height: 5,
|
||
data: data.collect(),
|
||
}));
|
||
let cpu_map = Graphic::from(cpu_map.with_attribute(ATTR_TRANSFORM, on_content));
|
||
let descriptor = wgpu::TextureDescriptor {
|
||
label: Some("displacement_map_test"),
|
||
size: wgpu::Extent3d {
|
||
width: 7,
|
||
height: 5,
|
||
depth_or_array_layers: 1,
|
||
},
|
||
mip_level_count: 1,
|
||
sample_count: 1,
|
||
dimension: wgpu::TextureDimension::D2,
|
||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||
view_formats: &[],
|
||
};
|
||
let context = executor.context();
|
||
let texture = (context.device).create_texture_with_data(&context.queue.lock(), &descriptor, wgpu::util::TextureDataOrder::LayerMajor, bytemuck::cast_slice(&levels));
|
||
let gpu_map = Graphic::from(Item::new_from_element(Raster::<GPU>::new_gpu(texture)).with_attribute(ATTR_TRANSFORM, on_content));
|
||
|
||
// A shadow cast past the frame, which both maps leave in place past their edges
|
||
let shadow = drop_shadow(GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.9), DVec2::new(6., 8.), 4., 0.);
|
||
let size = UVec2::new(160, 160);
|
||
let rendered = |map: &Graphic| {
|
||
let displace = x_and_y_displacement((map.clone(), 25.6), (map.clone(), -19.2), GradientSpread::Clear);
|
||
let graphic = Graphic::RasterCPU(Box::new(patterned_raster(55., &[shadow.clone(), displace], 1.)));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
let (Some(by_image), Some(by_texture)) = (rendered(&cpu_map), rendered(&gpu_map)) else {
|
||
return;
|
||
};
|
||
|
||
let worst = by_image
|
||
.iter()
|
||
.zip(&by_texture)
|
||
.flat_map(|(image, texture)| image.iter().zip(texture))
|
||
.map(|(image, texture)| image.abs_diff(*texture));
|
||
let worst = worst.max().unwrap_or_default();
|
||
assert!(worst <= 1, "a texture map differs from the same image map by up to {worst} levels");
|
||
}
|
||
|
||
/// The most that two renders differ by at any of their pixels' channels, in levels.
|
||
fn largest_difference(first: &[[u8; 4]], second: &[[u8; 4]]) -> u8 {
|
||
let differences = first
|
||
.iter()
|
||
.zip(second)
|
||
.flat_map(|(first, second)| first.iter().zip(second).map(|(first, second)| first.abs_diff(*second)));
|
||
differences.max().unwrap_or_default()
|
||
}
|
||
|
||
#[test]
|
||
fn angled_displacements_match_those_across_and_down_by_the_angles_components() {
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{EffectOperation, Graphic};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A map of grays read along each angle, or across and down in place of it by the angle's components
|
||
let on_content = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
let map = gray_map(13, 9, on_content, |x, y| 90. + 9. * x - 5. * y);
|
||
let pairs = [(135., 30.), (-20., 45.), (90., 25.)].map(|(angle, distance): (f64, f64)| {
|
||
let (across, down) = (distance * angle.to_radians().cos(), -distance * angle.to_radians().sin());
|
||
let components = x_and_y_displacement((map.clone(), across), (map.clone(), down), GradientSpread::Repeat);
|
||
(angle_displacement(map.clone(), angle, distance, GradientSpread::Repeat), components)
|
||
});
|
||
|
||
// An unwired map down moves nothing, so the map across alone matches the angle pointing right
|
||
let across_alone = x_and_y_displacement((map.clone(), 25.), (Graphic::default(), 60.), GradientSpread::Repeat);
|
||
let pairs = pairs.into_iter().chain([(angle_displacement(map.clone(), 0., 25., GradientSpread::Repeat), across_alone)]);
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let gpu = |displace: &EffectOperation| {
|
||
let graphic = Graphic::RasterCPU(Box::new(checkered_raster(std::slice::from_ref(displace))));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
let cpu = |displace: &EffectOperation| raster_kernels::evaluate_raster_effects(checkered_raster(std::slice::from_ref(displace))).element().data.clone();
|
||
|
||
for (angled, components) in pairs {
|
||
let levels = |color: &core_types::Color| color.to_gamma_srgb_channels().map(|channel| channel * 255.);
|
||
let cpu_worst = (cpu(&angled).iter().zip(&cpu(&components)))
|
||
.flat_map(|(angled, components)| levels(angled).into_iter().zip(levels(components)).map(|(angled, components)| (angled - components).abs()))
|
||
.fold(0., f32::max);
|
||
assert!(cpu_worst <= 1., "{angled:?} differs on the CPU from {components:?} by up to {cpu_worst} levels");
|
||
|
||
let (Some(angled_render), Some(components_render)) = (gpu(&angled), gpu(&components)) else {
|
||
return;
|
||
};
|
||
let gpu_worst = largest_difference(&angled_render, &components_render);
|
||
assert!(gpu_worst <= 1, "{angled:?} differs on the GPU from {components:?} by up to {gpu_worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn unwired_displacement_maps_move_nothing_in_either_mode_on_the_cpu_and_gpu() {
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{EffectOperation, Graphic};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let rendered = |effects: &[EffectOperation]| {
|
||
let graphic = Graphic::RasterCPU(Box::new(checkered_raster(effects)));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
let Some(unmoved) = rendered(&[]) else { return };
|
||
|
||
// Maps that draw nothing, as unwired ones do, read as middle gray however far they would move the content
|
||
let displacements = [
|
||
angle_displacement(Graphic::default(), 135., 40., GradientSpread::Clear),
|
||
x_and_y_displacement((Graphic::default(), 40.), (Graphic::default(), -30.), GradientSpread::Clear),
|
||
];
|
||
for displace in displacements {
|
||
let effects = [displace];
|
||
let Some(displaced) = rendered(&effects) else { return };
|
||
let worst = largest_difference(&displaced, &unmoved);
|
||
assert!(worst <= 1, "{effects:?} moves the content by up to {worst} levels on the GPU");
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(checkered_raster(&effects), size) else { return };
|
||
assert!(worst <= 1, "{effects:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn resampling_effects_read_what_lies_beyond_the_view() {
|
||
use glam::DVec2;
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{EffectOperation, Graphic, RadialBlurMethod};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Only the right part of the content is in view, yet the arcs around its middle, twists, and wraps read from the part left of the view
|
||
let on_image = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||
let spin = EffectOperation::RadialBlur {
|
||
method: RadialBlurMethod::Spin,
|
||
amount: 90.,
|
||
transform: DAffine2::from_translation(DVec2::splat(25.)),
|
||
gamma: false,
|
||
};
|
||
let twirl = EffectOperation::Twirl { angle: 200., transform: on_image };
|
||
let polar = EffectOperation::PolarCoordinates { inverse: false, transform: on_image };
|
||
let ripple = |edge_mode| EffectOperation::Ripple { amount: 400., size: 32., edge_mode };
|
||
let ripples = [GradientSpread::Clear, GradientSpread::Repeat, GradientSpread::Pad, GradientSpread::Reflect].map(ripple);
|
||
|
||
let pixelate = EffectOperation::Pixelate {
|
||
cell_size: 7.3,
|
||
offset: glam::DVec2::ZERO,
|
||
};
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius: 5.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
|
||
for effect in [spin, twirl, polar, pixelate, halftone].into_iter().chain(ripples) {
|
||
let graphic = Graphic::RasterCPU(Box::new(patterned_raster(20., std::slice::from_ref(&effect), 1.)));
|
||
let graphic = &graphic;
|
||
let draw = |offset: f64| move |scene: &mut VelloSceneBuilder| graphic.render_to_vello(scene, DAffine2::from_translation(DVec2::new(-offset, 0.)), &RenderParams::default());
|
||
|
||
let Some(whole) = render(UVec2::new(96, 96), draw(0.)) else { return };
|
||
let Some(part) = render(UVec2::new(32, 96), draw(56.)) else { return };
|
||
for y in 0..96 {
|
||
for x in 0..32 {
|
||
let (expected, actual) = (pixel(&whole, UVec2::new(96, 96), x + 56, y), pixel(&part, UVec2::new(32, 96), x, y));
|
||
let difference = expected.iter().zip(actual).map(|(&expected, actual)| expected.abs_diff(actual)).max().unwrap_or_default();
|
||
assert!(difference <= 1, "{effect:?} at ({x}, {y}) shows {actual:?} rather than {expected:?}");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// An opaque raster `size` pixels across at (`offset`, `offset`), `pixels_per_unit` of them to each document unit, carrying `effects`.
|
||
/// Each pixel takes the gamma-encoded `color` at its column and row, rounded to whole 8-bit levels as the GPU uploads them.
|
||
fn leveled_raster(
|
||
offset: f64,
|
||
size: UVec2,
|
||
pixels_per_unit: f64,
|
||
color: impl Fn(u32, u32) -> [f32; 3],
|
||
effects: &[graphic_types::EffectOperation],
|
||
) -> core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>> {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, stamp_effect};
|
||
|
||
let data = (0..size.x * size.y)
|
||
.map(|index| {
|
||
let [red, green, blue] = color(index % size.x, index / size.x).map(|channel| (channel * 255.).round() / 255.);
|
||
core_types::Color::from_gamma_srgb_channels(red, green, blue, 1.)
|
||
})
|
||
.collect();
|
||
let placement = DAffine2::from_translation(glam::DVec2::splat(offset)) * DAffine2::from_scale(size.as_dvec2() / pixels_per_unit);
|
||
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: size.x, height: size.y, data })).with_attribute(ATTR_TRANSFORM, placement);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
item
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftones_with_large_dots_match_on_the_cpu_and_gpu() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Dark content prints dots nearly filling their cells, up to the largest radius PSD interop brings.
|
||
// Light content prints small dots, with edges that move farthest for a change in ink, in levels just past steps of a half float, which the GPU's working textures round to.
|
||
let dark = |x: u32, y: u32| [0.02 + 0.14 * x as f32 / 200., 0.16 - 0.12 * y as f32 / 200., 0.04 + 0.1 * (x * y) as f32 / 40_000.];
|
||
let light = |_: u32, _: u32| [224. / 255., 192. / 255., 160. / 255.];
|
||
for radius in [127., 90., 64.] {
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
for (tone, color) in [("dark", &dark as &dyn Fn(u32, u32) -> [f32; 3]), ("light", &light)] {
|
||
let Some(worst) = gpu_and_cpu_difference(leveled_raster(28., UVec2::splat(200), 1., color, std::slice::from_ref(&halftone)), UVec2::splat(256)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{tone} dots of radius {radius} differ from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn pixelations_averaging_sparsely_match_on_the_cpu_and_gpu() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// A cell and a dot's square each hold more pixels than an average takes, so they're sampled every other one across and down.
|
||
// Red alternates by column and green by row, in levels just past steps of a half float, so sampling other columns or rows than the CPU's would change the colors.
|
||
let level = |odd: u32| (64 + 128 * odd) as f32 / 255.;
|
||
let stripes = |x: u32, y: u32| [level(x % 2), level(y % 2), 128. / 255.];
|
||
let pixelate = EffectOperation::Pixelate {
|
||
cell_size: 280.,
|
||
offset: glam::DVec2::ZERO,
|
||
};
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius: 140.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
for effect in [pixelate, halftone] {
|
||
let Some(worst) = gpu_and_cpu_difference(leveled_raster(10., UVec2::splat(300), 1., stripes, std::slice::from_ref(&effect)), UVec2::splat(320)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{effect:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
/// Renders the raster `item` at its own placement into a render `size` across.
|
||
fn render_raster(item: core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(item));
|
||
render_in_view(size, DAffine2::IDENTITY, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
}
|
||
|
||
#[test]
|
||
fn pixelations_of_more_texels_than_an_average_tests_one_by_one_take_the_mean_of_every_one() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Opaque columns a texel wide alternating between levels 64 and 192, which average to 128, as a flat gray of that level does
|
||
let stripes = |x: u32, _: u32| [(64 + 128 * (x % 2)) as f32 / 255.; 3];
|
||
let gray = |_: u32, _: u32| [128. / 255.; 3];
|
||
let size = UVec2::splat(320);
|
||
|
||
// Cells 280 texels across from the content's origin, the first from 10 to 290, show the gray
|
||
let Some(pixelated) = render_raster(
|
||
leveled_raster(
|
||
10.,
|
||
UVec2::splat(300),
|
||
1.,
|
||
stripes,
|
||
&[EffectOperation::Pixelate {
|
||
cell_size: 280.,
|
||
offset: glam::DVec2::ZERO,
|
||
}],
|
||
),
|
||
size,
|
||
) else {
|
||
return;
|
||
};
|
||
for (x, y) in [(10, 10), (150, 149), (289, 289)] {
|
||
let shown = pixel(&pixelated, size, x, y);
|
||
assert!(
|
||
shown[..3].iter().all(|&channel| channel.abs_diff(128) <= 1),
|
||
"({x}, {y}) shows {shown:?} rather than the gray of level 128"
|
||
);
|
||
}
|
||
|
||
// A halftone's dot squares 260 across ink the stripes as they ink the gray, where each dot reaching a texel has its whole square within the content, from 10 to 610
|
||
let halftone = [EffectOperation::ColorHalftone {
|
||
radius: 130.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
}];
|
||
let size = UVec2::splat(620);
|
||
let (Some(striped), Some(flat)) = (
|
||
render_raster(leveled_raster(10., UVec2::splat(600), 1., stripes, &halftone), size),
|
||
render_raster(leveled_raster(10., UVec2::splat(600), 1., gray, &halftone), size),
|
||
) else {
|
||
return;
|
||
};
|
||
for (x, y) in (280..340).flat_map(|y| (280..340).map(move |x| (x, y))) {
|
||
let (striped, flat) = (pixel(&striped, size, x, y), pixel(&flat, size, x, y));
|
||
let worst = (0..3).map(|channel| striped[channel].abs_diff(flat[channel])).max().unwrap_or_default();
|
||
assert!(worst <= 2, "({x}, {y}) inks the stripes as {striped:?} rather than {flat:?}");
|
||
}
|
||
}
|
||
|
||
/// Holds pixelations' tables on this thread to textures `limit` texels across for as long as it lives.
|
||
struct TableDimensionLimit;
|
||
|
||
impl TableDimensionLimit {
|
||
fn new(limit: u32) -> Self {
|
||
crate::vello_effects::TABLE_DIMENSION_LIMIT.with(|forced| forced.set(Some(limit)));
|
||
Self
|
||
}
|
||
}
|
||
|
||
impl Drop for TableDimensionLimit {
|
||
fn drop(&mut self) {
|
||
crate::vello_effects::TABLE_DIMENSION_LIMIT.with(|forced| forced.set(None));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn pixelation_tables_wider_than_a_texture_allows_wrap_their_rows_rather_than_change_how_they_look() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
let gradient = |x: u32, y: u32| [0.2 + 0.6 * x as f32 / 512., 0.7 - 0.5 * y as f32 / 512., 0.4];
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius: 2.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
|
||
// Held to these sizes, neither table fits without wrapping: a halftone's three channels of dots take more than 400 rows, and Pixelate's cells over a strip of 512 by 64 more than 100 columns
|
||
for (raster, size, limit) in [
|
||
(leveled_raster(8., UVec2::splat(384), 1., gradient, std::slice::from_ref(&halftone)), UVec2::splat(400), 400),
|
||
(
|
||
leveled_raster(
|
||
8.,
|
||
UVec2::new(512, 64),
|
||
1.,
|
||
gradient,
|
||
&[EffectOperation::Pixelate {
|
||
cell_size: 4.,
|
||
offset: glam::DVec2::ZERO,
|
||
}],
|
||
),
|
||
UVec2::new(528, 80),
|
||
100,
|
||
),
|
||
] {
|
||
let Some(unlimited) = render_raster(raster.clone(), size) else { return };
|
||
let limited = {
|
||
let _limit = TableDimensionLimit::new(limit);
|
||
render_raster(raster, size)
|
||
};
|
||
let Some(limited) = limited else { return };
|
||
|
||
let differing = unlimited.iter().zip(&limited).position(|(unlimited, limited)| unlimited != limited);
|
||
assert!(
|
||
differing.is_none(),
|
||
"held to {limit} texels across, ({}, {}) shows {:?} rather than {:?}",
|
||
differing.unwrap_or_default() as u32 % size.x,
|
||
differing.unwrap_or_default() as u32 / size.x,
|
||
differing.map(|index| limited[index]),
|
||
differing.map(|index| unlimited[index])
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftones_with_dots_under_a_unit_across_match_on_the_cpu_and_gpu() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Dark content of four pixels to each unit, viewed at four times the size so its pixels land on the render's.
|
||
// Its dots snap far enough from their lattice points to reach pixels nearest a cell well past their own.
|
||
let dark = |x: u32, y: u32| [0.1 + 0.2 * x as f32 / 128., 0.2 - 0.1 * y as f32 / 128., 0.05];
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius: 0.5,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
let view = DAffine2::from_scale(glam::DVec2::splat(4.));
|
||
let Some(worst) = gpu_and_cpu_difference_in_view(leveled_raster(4., UVec2::splat(128), 4., dark, &[halftone]), UVec2::splat(160), view) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "the dots differ from the GPU by up to {worst} levels");
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftones_of_dots_far_under_a_unit_apart_ink_each_texel_they_snap_together_to_reach_on_the_cpu_and_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// Opaque black over a frame 4 units across and 2 units past each side, at 40 pixels to each unit, with dots of radius 0.05 on upright screens placed as PSD places them.
|
||
// Lattice points up to a unit and a half away snap together onto each whole unit, where the 98 at (-1, 1) from the frame's corner fill their dot.
|
||
let (size, bounds) = (UVec2::splat(320), Rect::new(0., 0., 320., 320.));
|
||
let (frame, effect_space) = (
|
||
DAffine2::from_translation(DVec2::splat(80.)) * DAffine2::from_scale(DVec2::splat(160.)),
|
||
DAffine2::from_scale(DVec2::splat(40.)) * DAffine2::from_translation(DVec2::splat(2.)),
|
||
);
|
||
let halftone = psd_color_halftone(0.05, [0.; 3], DVec2::splat(4.));
|
||
let Some(pixels) = render_with_effect_in_frame(halftone.clone(), frame, effect_space, bounds, size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &bounds);
|
||
}) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 40, 120), [0, 0, 0, 255], "the texel past the frame's side nearest the unit at (-1, 1) isn't inked");
|
||
|
||
// The CPU's halftone of the same texels and frame
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = vec![[0., 0., 0., 1.]; (size.x * size.y) as usize];
|
||
let Some(frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else {
|
||
panic!("the frame doesn't collapse")
|
||
};
|
||
let expected = cpu_pixelated(&halftone, &plane, &frame);
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&pixels, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 3., "({x}, {y}) shows {gpu:?} rather than {cpu:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftones_under_a_fill_print_what_lies_beneath_the_content_alike_on_the_cpu_and_gpu() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||
|
||
// Opaque white content at a fill over an opaque black shadow beneath it and a translucent red one overlapping it, neither knocked out, printed as dots too close together to print and as dots that print
|
||
let shadow = |color: core_types::Color, offset: DVec2| EffectOperation::DropShadow {
|
||
color,
|
||
blend_mode: BlendMode::Normal,
|
||
angle: offset.y.atan2(-offset.x).to_degrees(),
|
||
distance: offset.length(),
|
||
spread: 0.,
|
||
size: 0.,
|
||
contour: Default::default(),
|
||
knockout: false,
|
||
};
|
||
let shadows = [
|
||
shadow(core_types::Color::BLACK, DVec2::ZERO),
|
||
shadow(core_types::Color::from_rgbaf32_unchecked(1., 0., 0., 0.6), DVec2::splat(6.)),
|
||
];
|
||
for (fill, radius) in [(0., 1.), (0.5, 1.), (0., 3.), (0.5, 3.)] {
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(24, 24, core_types::Color::WHITE)))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(8.)) * DAffine2::from_scale(DVec2::splat(24.)))
|
||
.with_attribute(ATTR_OPACITY_FILL, fill);
|
||
shadows.iter().chain([&halftone]).for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(item, UVec2::splat(48)) else { return };
|
||
assert!(worst <= 3, "at fill {fill} and radius {radius}, the halftone differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftones_ink_nothing_of_the_contents_edge_at_a_frame_cutting_through_texels() {
|
||
use glam::DVec2;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// A black square from 10.3 to 30.3 amid its hard white shadow, so the frame's sides cut through texels holding the content's antialiased edge, with its origin at its corner and its dots placed as PSD places them
|
||
let shadow = drop_shadow(core_types::Color::WHITE, DVec2::ZERO, 12., 100.);
|
||
let halftone = psd_color_halftone(4. * std::f64::consts::SQRT_2, [0., 90., 180.], DVec2::splat(20.));
|
||
let (size, effect_space) = (UVec2::splat(48), DAffine2::from_translation(DVec2::splat(10.3)));
|
||
let Some(pixels) = render_square_over_backdrop_in(vec![shadow, halftone.clone()], effect_space, 1., 1., BlendMode::Normal, None, Color::BLACK, 10.3, 30.3, size) else {
|
||
return;
|
||
};
|
||
|
||
// The CPU's halftone of the square as its dots should read it, black wherever a texel's center lies within the frame and white past it
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = (0..size.x * size.y)
|
||
.map(|index| {
|
||
if (10..30).contains(&(index % size.x)) && (10..30).contains(&(index / size.x)) {
|
||
[0., 0., 0., 1.]
|
||
} else {
|
||
[1.; 4]
|
||
}
|
||
})
|
||
.collect();
|
||
let Some(frame) = EffectFrame::new(DAffine2::from_scale(DVec2::splat(20.)), effect_space) else {
|
||
panic!("the square has a frame")
|
||
};
|
||
let expected = cpu_pixelated(&halftone, &plane, &frame);
|
||
|
||
// Within the shadow, the dots take their ink only from texels the frame covers wholly or not at all, so the edge's gray changes none of them
|
||
for (x, y) in (4..=36).flat_map(|y| (4..=36).map(move |x| (x, y))) {
|
||
let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&pixels, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 3., "({x}, {y}) shows {gpu:?} rather than {cpu:?}");
|
||
}
|
||
}
|
||
|
||
/// Renders `draw` through the `effect` placed in the `frame`, with the content within `bounds`, in an `effect_space` placed in the document.
|
||
fn render_with_effect_in_frame(
|
||
effect: graphic_types::EffectOperation,
|
||
frame: DAffine2,
|
||
effect_space: DAffine2,
|
||
bounds: Rect,
|
||
size: UVec2,
|
||
mut draw: impl FnMut(&mut VelloSceneBuilder),
|
||
) -> Option<Vec<[u8; 4]>> {
|
||
let effects = graphic_types::Effects::from_operations([effect]);
|
||
render(size, |scene| {
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(bounds), effect_space, Some((frame, 0.)), &mut |_, _| {}, &mut draw)
|
||
})
|
||
}
|
||
|
||
/// The CPU's Pixelate or Color Halftone of a premultiplied `plane` in the `frame`, as the `effect` makes it.
|
||
fn cpu_pixelated(
|
||
effect: &graphic_types::EffectOperation,
|
||
plane: &raster_kernels::effect_kernels::Plane<[f32; 4]>,
|
||
frame: &graphic_types::resampling::EffectFrame,
|
||
) -> raster_kernels::effect_kernels::Plane<[f32; 4]> {
|
||
use graphic_types::EffectOperation;
|
||
use graphic_types::resampling::HalftoneScreen;
|
||
use raster_kernels::resample_kernels::{halftoned, pixelated};
|
||
|
||
match (effect, HalftoneScreen::of(effect, frame)) {
|
||
(&EffectOperation::Pixelate { cell_size, offset }, _) => pixelated(plane, cell_size, offset, frame),
|
||
(_, Some(screens)) => halftoned(plane, &screens, frame),
|
||
_ => panic!("{effect:?} isn't a pixelation"),
|
||
}
|
||
}
|
||
|
||
/// For PSD interop, a color halftone of dots up to `radius` across on screens at `angles`, placed as PSD places them on content `size` across with its origin at its frame's corner.
|
||
fn psd_color_halftone(radius: f64, [red_angle, green_angle, blue_angle]: [f64; 3], size: glam::DVec2) -> graphic_types::EffectOperation {
|
||
let (offset, phase) = graphic_types::resampling::halftone_placement_from_psd(size, radius);
|
||
graphic_types::EffectOperation::ColorHalftone {
|
||
radius,
|
||
red_angle,
|
||
green_angle,
|
||
blue_angle,
|
||
offset,
|
||
phase,
|
||
}
|
||
}
|
||
|
||
/// Asserts that the `effect`, placed in a frame leaning `lean` radians from flat, leaves a square from (12, 12) to (52, 52) of black and white columns a pixel wide as it is, on the CPU and GPU alike.
|
||
/// Each row of texels lies in a row of the frame's cells of its own, and runs across cells or dots holding a few texels each.
|
||
fn assert_stripes_stay_in_a_frame_leaning_nearly_flat(effect: graphic_types::EffectOperation, lean: f64) {
|
||
use glam::DVec2;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
let frame = DAffine2::from_cols(DVec2::new(40., 0.), DVec2::new(lean.cos(), lean.sin()) * 40., DVec2::splat(12.));
|
||
let square = Rect::new(12., 12., 52., 52.);
|
||
let draw_stripes = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square);
|
||
for x in (12..52).step_by(2) {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(x as f64, 12., x as f64 + 1., 52.));
|
||
}
|
||
};
|
||
|
||
let size = UVec2::splat(64);
|
||
let Some(with_effect) = render_with_effect_in_frame(effect.clone(), frame, DAffine2::IDENTITY, square, size, draw_stripes) else {
|
||
return;
|
||
};
|
||
let Some(stripes) = render(size, draw_stripes) else { return };
|
||
for (index, (actual, expected)) in with_effect.iter().zip(&stripes).enumerate() {
|
||
let worst = (0..4).map(|channel| actual[channel].abs_diff(expected[channel])).max().unwrap_or_default();
|
||
assert!(worst <= 1, "{effect:?} leaning {lean} shows {actual:?} at ({}, {}) rather than {expected:?}", index % 64, index / 64);
|
||
}
|
||
|
||
// The CPU's result on the same texels and frame
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = (0..size.x * size.y)
|
||
.map(|index| match ((12..52).contains(&(index % size.x)) && (12..52).contains(&(index / size.x)), index % 2 == 0) {
|
||
(true, true) => [0., 0., 0., 1.],
|
||
(true, false) => [1.; 4],
|
||
(false, _) => [0.; 4],
|
||
})
|
||
.collect();
|
||
let Some(frame) = EffectFrame::new(frame, DAffine2::IDENTITY) else {
|
||
panic!("the frame doesn't collapse")
|
||
};
|
||
let expected = cpu_pixelated(&effect, &plane, &frame);
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&with_effect, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 1., "{effect:?} leaning {lean} shows {gpu:?} at ({x}, {y}) on the GPU rather than {cpu:?} as on the CPU");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn pixelations_of_more_texels_than_an_average_tests_one_by_one_match_on_the_cpu_and_gpu_in_a_skewed_frame() {
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// Black and white columns a texel wide over a square from 16 to 496, under a frame turned and skewed off the texels, so its sides cut through them
|
||
let (size, square) = (UVec2::splat(512), Rect::new(16., 16., 496., 496.));
|
||
let placement = DAffine2::from_cols(DVec2::new(400., 230.9), DVec2::new(-150., 360.), DVec2::new(160.3, 20.7));
|
||
let draw_stripes = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square);
|
||
for x in (16..496).step_by(2) {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(x as f64, 16., x as f64 + 1., 496.));
|
||
}
|
||
};
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = (0..size.x * size.y)
|
||
.map(|index| {
|
||
let (x, y) = (index % size.x, index / size.x);
|
||
match ((16..496).contains(&x) && (16..496).contains(&y), x % 2 == 0) {
|
||
(true, true) => [0., 0., 0., 1.],
|
||
(true, false) => [1.; 4],
|
||
(false, _) => [0.; 4],
|
||
}
|
||
})
|
||
.collect();
|
||
let Some(frame) = EffectFrame::new(placement, DAffine2::IDENTITY) else {
|
||
panic!("the frame doesn't collapse")
|
||
};
|
||
|
||
// Cells and dot squares wider than an average tests one by one, within the frame, past its sides, and cut by them
|
||
let pixelate = EffectOperation::Pixelate {
|
||
cell_size: 300.,
|
||
offset: DVec2::new(120., -45.),
|
||
};
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius: 130.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: DVec2::new(300., 210.),
|
||
phase: 30.,
|
||
};
|
||
|
||
// Within the square, since the render draws a frame-relative effect no farther than the content's bounds and what earlier effects paint past them
|
||
for effect in [pixelate, halftone] {
|
||
let expected = cpu_pixelated(&effect, &plane, &frame);
|
||
let Some(pixels) = render_with_effect_in_frame(effect.clone(), placement, DAffine2::IDENTITY, square, size, draw_stripes) else {
|
||
return;
|
||
};
|
||
for (x, y) in (16..496).flat_map(|y| (16..496).map(move |x| (x, y))) {
|
||
let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&pixels, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 3., "{effect:?} shows {gpu:?} at ({x}, {y}) rather than {cpu:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn pixelates_with_far_more_cells_than_texels_leave_the_content_as_it_is() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Leaning 1e-4, the render spans hundreds of thousands of rows of cells, more than a texture holds.
|
||
// Leaning 0.01, it spans hundreds of rows and as many columns, which a texture holds, though that's over a hundred cells for each texel.
|
||
// Pixelating would average each run of a row's texels in one cell to gray.
|
||
for (lean, cell_size) in [(1e-4, 2.), (0.01, 8.)] {
|
||
assert_stripes_stay_in_a_frame_leaning_nearly_flat(EffectOperation::Pixelate { cell_size, offset: glam::DVec2::ZERO }, lean);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftones_with_far_more_dots_than_texels_print_their_tone() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Far more dots than texels, though few enough around each texel to print, which give way to their tone, the opaque content's own color
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius: 8.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
assert_stripes_stay_in_a_frame_leaning_nearly_flat(halftone, 0.02);
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftones_over_regions_far_wider_than_tall_match_on_the_cpu_and_gpu() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// A strip 1024 by 64 texels, with dots 2.8 texels apart on screens turned from its axes.
|
||
// Their lattices span about the square on its longer side, so their table holds six times as many dots as the strip has texels.
|
||
let gradient = |x: u32, y: u32| [0.2 + 0.6 * x as f32 / 1024., 0.7 - 0.5 * y as f32 / 64., 0.4];
|
||
let halftone = EffectOperation::ColorHalftone {
|
||
radius: 2.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset: glam::DVec2::ZERO,
|
||
phase: 0.,
|
||
};
|
||
let size = UVec2::new(1024, 64);
|
||
let Some(worst) = gpu_and_cpu_difference(leveled_raster(0., size, 1., gradient, &[halftone]), size) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "the dots differ from the GPU by up to {worst} levels");
|
||
}
|
||
|
||
#[test]
|
||
fn pixelate_cells_hundreds_of_texels_wide_hold_the_texels_up_to_their_boundaries() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Cells 512 texels wide over red and then blue halves, each half one cell
|
||
let (size, bounds) = (UVec2::new(1024, 2), Rect::new(0., 0., 1024., 2.));
|
||
let frame = DAffine2::from_scale(glam::DVec2::new(1024., 2.));
|
||
let pixelate = EffectOperation::Pixelate {
|
||
cell_size: 512.,
|
||
offset: glam::DVec2::ZERO,
|
||
};
|
||
let Some(pixels) = render_with_effect_in_frame(pixelate, frame, DAffine2::IDENTITY, bounds, size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 0, 0), None, &Rect::new(0., 0., 512., 2.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(0, 0, 255), None, &Rect::new(512., 0., 1024., 2.));
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
for x in [0, 511, 512, 1023] {
|
||
let expected = if x < 512 { [255, 0, 0, 255] } else { [0, 0, 255, 255] };
|
||
assert_eq!(pixel(&pixels, size, x, 0), expected, "texel {x} shows another cell");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_same_texels_on_the_cpu_and_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::resampling::{EffectFrame, HalftoneScreen};
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// Dots of radius 256 square to a frame 1024 across, placed as PSD places them, seen through a window holding the dot at the frame's center and the column of texels just before its box's near side
|
||
let frame_size = DVec2::splat(1024.);
|
||
let halftone = psd_color_halftone(256., [0.; 3], frame_size);
|
||
let Some([screen, ..]) = EffectFrame::new(DAffine2::from_scale(frame_size), DAffine2::IDENTITY).and_then(|frame| HalftoneScreen::of(&halftone, &frame)) else {
|
||
panic!("the halftone has screens")
|
||
};
|
||
let center = screen.dot_center(screen.cell_at(frame_size / 2.));
|
||
let window = center - DVec2::new(260., 3.);
|
||
let (frame, effect_space) = (DAffine2::from_translation(-window) * DAffine2::from_scale(frame_size), DAffine2::from_translation(-window));
|
||
|
||
// White but for that column, which only the box of the dot before it holds, and that dot lies outside the window
|
||
let (size, bounds) = (UVec2::new(264, 6), Rect::new(0., 0., 264., 6.));
|
||
let column = (center.x - 257. - window.x) as u32;
|
||
let Some(pixels) = render_with_effect_in_frame(halftone.clone(), frame, effect_space, bounds, size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &bounds);
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(column as f64, 0., column as f64 + 1., 6.));
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// The CPU's halftone of the same window
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = (0..size.x * size.y).map(|index| if index % size.x == column { [0., 0., 0., 1.] } else { [1.; 4] }).collect();
|
||
let Some(frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else {
|
||
panic!("the window has a frame")
|
||
};
|
||
let expected = cpu_pixelated(&halftone, &plane, &frame);
|
||
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&pixels, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 1., "({x}, {y}) shows {gpu:?} rather than {cpu:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftone_dot_boxes_hundreds_of_texels_wide_hold_the_row_a_tie_nudge_brings_into_them_on_the_cpu_and_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// A frame 1000 units across at 2 texels to each unit from (10.53125, 10.53125), with its origin there, seen through a window from texel 770.
|
||
// The box of the dot of radius 127 nearest its center, placed as PSD places it, starts at 8.53125, a 32nd of a texel past row 8's centers, which a tie's nudge of a 16th of a texel brings within it.
|
||
let (size, bounds) = (UVec2::splat(280), Rect::new(0., 0., 280., 280.));
|
||
let (frame, effect_space) = (
|
||
DAffine2::from_translation(DVec2::splat(10.53125 - 770.)) * DAffine2::from_scale(DVec2::splat(2000.)),
|
||
DAffine2::from_translation(DVec2::splat(10.53125 - 770.)) * DAffine2::from_scale(DVec2::splat(2.)),
|
||
);
|
||
let halftone = psd_color_halftone(127., [0.; 3], DVec2::splat(1000.));
|
||
|
||
// White but for that row, which inks the dot at (262.5, 262.5) about 13 texels across
|
||
let Some(pixels) = render_with_effect_in_frame(halftone.clone(), frame, effect_space, bounds, size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &bounds);
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(0., 8., 280., 9.));
|
||
}) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 262, 262), [0, 0, 0, 255], "the dot's center isn't inked");
|
||
|
||
// The CPU's halftone of the same window
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = (0..size.x * size.y).map(|index| if index / size.x == 8 { [0., 0., 0., 1.] } else { [1.; 4] }).collect();
|
||
let Some(frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else {
|
||
panic!("the window has a frame")
|
||
};
|
||
let expected = cpu_pixelated(&halftone, &plane, &frame);
|
||
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&pixels, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 3., "({x}, {y}) shows {gpu:?} rather than {cpu:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn pixelate_cells_cut_by_the_frames_far_sides_keep_the_contents_edge() {
|
||
use graphic_types::EffectOperation;
|
||
|
||
// Squares from 10.3, with their origin there, and far sides cutting through texels, in cells leaving none on their side of the frame's edge in the last column and row or just past them.
|
||
// That's the last to 30.8 in cells of 10 and to 30.3 in cells of 6.6, those past it to 29.3 in cells of 10, and both to 30.3 in cells of 1.5.
|
||
let (size, effect_space) = (UVec2::splat(48), DAffine2::from_translation(glam::DVec2::splat(10.3)));
|
||
for (max, cell_size) in [(30.8, 10.), (30.3, 6.6), (29.3, 10.), (30.3, 1.5)] {
|
||
let Some(square) = render_square_with_effects(vec![], 1., 10.3, max, size) else { return };
|
||
let pixelate = EffectOperation::Pixelate { cell_size, offset: glam::DVec2::ZERO };
|
||
let Some(pixelated) = render_square_with_effects_in(vec![pixelate], effect_space, 1., 10.3, max, size) else {
|
||
return;
|
||
};
|
||
|
||
// Flat content averages to itself, so the texels the frame's sides cut through keep the content's edge
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let (expected, actual) = (premultiplied_levels(pixel(&square, size, x, y)), premultiplied_levels(pixel(&pixelated, size, x, y)));
|
||
let worst = (0..4).map(|channel| (expected[channel] - actual[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 2., "in cells of {cell_size}, ({x}, {y}) shows {actual:?} rather than {expected:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_halftone_dots_snap_alike_on_the_cpu_and_gpu_across_a_vast_frame() {
|
||
use glam::DVec2;
|
||
use graphic_types::Effects;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// A gray square 8001 across with its origin at its corner, viewed where dots of its red screen, placed as PSD places them, lie within a ten-thousandth of a unit of a tie between two whole units from its corner.
|
||
// Single precision can't tell those apart there.
|
||
let halftone = psd_color_halftone(8., [108., 162., 90.], DVec2::splat(8001.));
|
||
let effects = Effects::from_operations([halftone.clone()]);
|
||
let gray = 128. / 255.;
|
||
let (size, margin) = (UVec2::splat(64), 32);
|
||
|
||
for near_tie in [
|
||
DVec2::new(370., 7376.),
|
||
DVec2::new(678., 7417.),
|
||
DVec2::new(986., 7457.),
|
||
DVec2::new(1294., 7498.),
|
||
DVec2::new(268., 6665.),
|
||
] {
|
||
let corner = DVec2::splat(32.) - near_tie;
|
||
let placement = DAffine2::from_translation(corner) * DAffine2::from_scale(DVec2::splat(8001.));
|
||
let square = Rect::new(corner.x, corner.y, corner.x + 8001., corner.y + 8001.);
|
||
let pixels = render(size, |scene| {
|
||
scene.draw_effects(
|
||
&effects,
|
||
1.,
|
||
1.,
|
||
BlendMode::Normal,
|
||
true,
|
||
Some(square),
|
||
DAffine2::from_translation(corner),
|
||
Some((placement, 0.)),
|
||
&mut |_, _| {},
|
||
&mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(128, 128, 128), None, &square),
|
||
)
|
||
});
|
||
let Some(pixels) = pixels else { return };
|
||
|
||
// The CPU's halftone of the same part of the square, with a margin holding all that the dots in view average
|
||
let mut plane = Plane::<[f32; 4]>::new((size.x + 2 * margin) as usize, (size.y + 2 * margin) as usize);
|
||
plane.data.fill([gray, gray, gray, 1.]);
|
||
let Some(frame) = EffectFrame::new(DAffine2::from_scale(DVec2::splat(8001.)), DAffine2::from_translation(DVec2::splat(margin as f64) + corner)) else {
|
||
panic!("the square has a frame")
|
||
};
|
||
let expected = cpu_pixelated(&halftone, &plane, &frame);
|
||
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let cpu = expected.data[((y + margin) * (size.x + 2 * margin) + x + margin) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&pixels, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 3., "near {near_tie}, ({x}, {y}) shows {gpu:?} rather than {cpu:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn pixelations_far_from_the_contents_origin_match_on_the_cpu_and_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// A square of four colors from 8 to 56 with its origin 100,000 units away, under cells and dots placed back on it, which single precision can't place from that origin
|
||
let (size, square) = (UVec2::splat(64), Rect::new(8., 8., 56., 56.));
|
||
let frame = DAffine2::from_translation(DVec2::splat(8.)) * DAffine2::from_scale(DVec2::splat(48.));
|
||
let effect_space = DAffine2::from_translation(DVec2::new(-100_000., 70_000.));
|
||
let on_square = DVec2::new(100_019.3, -69_985.6);
|
||
let quadrant_color = |x: u32, y: u32| [[220, 40, 40], [40, 200, 60], [30, 60, 210], [230, 200, 50]][(x >= 32) as usize + 2 * (y >= 32) as usize];
|
||
let draw_quadrants = |scene: &mut VelloSceneBuilder| {
|
||
for (x, y) in [(8, 8), (32, 8), (8, 32), (32, 32)] {
|
||
let [red, green, blue] = quadrant_color(x, y);
|
||
scene.fill(
|
||
Fill::NonZero,
|
||
Affine::IDENTITY,
|
||
Color::from_rgb8(red, green, blue),
|
||
None,
|
||
&Rect::new(x as f64, y as f64, x as f64 + 24., y as f64 + 24.),
|
||
);
|
||
}
|
||
};
|
||
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = (0..size.x * size.y)
|
||
.map(|index| {
|
||
let (x, y) = (index % size.x, index / size.x);
|
||
if !(8..56).contains(&x) || !(8..56).contains(&y) {
|
||
return [0.; 4];
|
||
}
|
||
let [red, green, blue] = quadrant_color(x, y).map(|level| level as f32 / 255.);
|
||
[red, green, blue, 1.]
|
||
})
|
||
.collect();
|
||
let Some(cpu_frame) = EffectFrame::new(effect_space.inverse() * frame, effect_space) else {
|
||
panic!("the square has a frame")
|
||
};
|
||
|
||
// Then cells and screens placed far away themselves, with boundaries and dots hundreds of millions of cells from where they're placed
|
||
let pixelate = |cell_size, offset| EffectOperation::Pixelate { cell_size, offset };
|
||
let halftone = |offset, phase| EffectOperation::ColorHalftone {
|
||
radius: 3.,
|
||
red_angle: 108.,
|
||
green_angle: 162.,
|
||
blue_angle: 90.,
|
||
offset,
|
||
phase,
|
||
};
|
||
let effects = [pixelate(5.3, on_square), halftone(on_square, 40.), pixelate(1e9, on_square), halftone(DVec2::splat(-1e9), 0.)];
|
||
for effect in effects {
|
||
let Some(pixels) = render_with_effect_in_frame(effect.clone(), frame, effect_space, square, size, draw_quadrants) else {
|
||
return;
|
||
};
|
||
let expected = cpu_pixelated(&effect, &plane, &cpu_frame);
|
||
for (x, y) in (8..56).flat_map(|y| (8..56).map(move |x| (x, y))) {
|
||
let cpu = expected.data[(y * size.x + x) as usize].map(|channel| channel * 255.);
|
||
let gpu = premultiplied_levels(pixel(&pixels, size, x, y));
|
||
let worst = (0..4).map(|channel| (cpu[channel] - gpu[channel]).abs()).fold(0., f32::max);
|
||
assert!(worst <= 3., "{effect:?} shows {gpu:?} at ({x}, {y}) rather than {cpu:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn pixelate_cells_far_wider_than_the_frame_meet_where_they_lie_within_it_on_the_gpu() {
|
||
use glam::DVec2;
|
||
use graphic_types::EffectOperation;
|
||
use graphic_types::resampling::EffectFrame;
|
||
use raster_kernels::effect_kernels::Plane;
|
||
|
||
// An opaque square 64 across with its origin at its corner, black on its left half and white on its right, in cells 10^9 across meeting at its middle
|
||
let (size, square) = (UVec2::splat(64), Rect::new(0., 0., 64., 64.));
|
||
let frame = DAffine2::from_scale(DVec2::splat(64.));
|
||
let pixelate = EffectOperation::Pixelate {
|
||
cell_size: 1e9,
|
||
offset: DVec2::splat(32.),
|
||
};
|
||
let Some(pixels) = render_with_effect_in_frame(pixelate.clone(), frame, DAffine2::IDENTITY, square, size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::BLACK, None, &Rect::new(0., 0., 32., 64.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &Rect::new(32., 0., 64., 64.));
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// Each cell holds one half, which keeps its color, as on the CPU
|
||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||
plane.data = (0..size.x * size.y).map(|index| if index % size.x < 32 { [0., 0., 0., 1.] } else { [1.; 4] }).collect();
|
||
let Some(cpu_frame) = EffectFrame::new(frame, DAffine2::IDENTITY) else {
|
||
panic!("the square has a frame")
|
||
};
|
||
let expected = cpu_pixelated(&pixelate, &plane, &cpu_frame);
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let index = (y * size.x + x) as usize;
|
||
assert_eq!(expected.data[index], plane.data[index], "({x}, {y}) shows another half on the CPU");
|
||
let shown = if x < 32 { [0, 0, 0, 255] } else { [255; 4] };
|
||
assert_eq!(pixel(&pixels, size, x, y), shown, "({x}, {y}) shows another half on the GPU");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warps_fill_the_corners_of_their_square_in_a_clipped_turned_group() {
|
||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let filled = |path: &BezPath, color: GraphicColor| {
|
||
let mut item = Vector::item_from_bezpath(path);
|
||
item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))));
|
||
item
|
||
};
|
||
|
||
// A red disc in a group turned an eighth and clipped to a white base, unwrapped across the whole square around it, with corners past the disc's own bounds
|
||
let base = Item::new_from_element(Graphic::Vector(Box::new(filled(&Rect::new(0., 0., 128., 128.).to_path(0.1), GraphicColor::WHITE))));
|
||
let disc = filled(&vello_gpu::kurbo::Circle::new((0., 0.), 30.).to_path(0.1), GraphicColor::RED).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
let unwrap = EffectOperation::PolarCoordinates {
|
||
inverse: true,
|
||
transform: DAffine2::from_scale(DVec2::splat(60.)),
|
||
};
|
||
let group = Item::new_from_element(Graphic::Vector(Box::new(disc)))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(64.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4))
|
||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([unwrap]));
|
||
let graphic = Graphic::GraphicList([base, group].into_iter().collect());
|
||
|
||
let size = UVec2::splat(128);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 64, 64), [255, 0, 0, 255], "the unwrapped disc shows over the base");
|
||
assert_eq!(pixel(&pixels, size, 101, 64), [255, 0, 0, 255], "the square's corner past the disc's bounds is filled");
|
||
}
|
||
|
||
/// A Warp of `style` bending by `bend` within the square its `transform` places.
|
||
fn warp_effect(style: graphic_types::WarpStyle, bend: f64, transform: DAffine2) -> graphic_types::EffectOperation {
|
||
graphic_types::EffectOperation::Warp {
|
||
style,
|
||
bend,
|
||
horizontal_distortion: 0.,
|
||
vertical_distortion: 0.,
|
||
vertical: false,
|
||
transform,
|
||
}
|
||
}
|
||
|
||
/// The transform placing a warp's square on the unit square that `placement` places, as on the frame of content it places.
|
||
fn square_on(placement: DAffine2) -> DAffine2 {
|
||
placement * DAffine2::from_translation(glam::DVec2::splat(0.5))
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_on_a_tilted_canvas_keep_all_they_paint() {
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, Graphic, WarpStyle};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Within a square on a raster 200 by 100 at the origin
|
||
let on_raster = square_on(DAffine2::from_scale(DVec2::new(200., 100.)));
|
||
let chains = [
|
||
// A rise with both distortions reaches far past one corner of its square, past both sides there, on a canvas tilted off the document's axes
|
||
vec![EffectOperation::Warp {
|
||
style: WarpStyle::Rise,
|
||
bend: -50.,
|
||
horizontal_distortion: 50.,
|
||
vertical_distortion: 50.,
|
||
vertical: false,
|
||
transform: on_raster,
|
||
}],
|
||
// An arch bends far above its square yet within its tilted bounds, where a twist after it clears it, bending what remains within the square
|
||
vec![warp_effect(WarpStyle::Arch, 80., on_raster), warp_effect(WarpStyle::Twist, -50., on_raster)],
|
||
];
|
||
let size = UVec2::splat(480);
|
||
|
||
for effects in &chains {
|
||
let item = patterned_raster_sized(0., UVec2::new(200, 100), effects, 1.);
|
||
|
||
for degrees in [30_f64, 45.] {
|
||
let view = DAffine2::from_translation(DVec2::splat(240.)) * DAffine2::from_angle(degrees.to_radians()) * DAffine2::from_translation(-DVec2::new(100., 50.));
|
||
|
||
// The GPU's warp, beside the CPU's warped image drawn plainly through the same view
|
||
let warped = Graphic::RasterCPU(Box::new(item.clone()));
|
||
let Some(gpu) = render_in_view(size, view, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(item.clone())));
|
||
let Some(cpu) = render_in_view(size, view, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// Where the CPU's image shows the content, so does the GPU's
|
||
let missing = (0..size.x * size.y).filter(|index| pixel(&cpu, size, index % size.x, index / size.x)[3] > 192 && pixel(&gpu, size, index % size.x, index / size.x)[3] < 64);
|
||
let missing = missing.count();
|
||
assert!(missing <= 2, "{effects:?} tilted {degrees} degrees, {missing} pixels of the content are missing on the GPU");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_match_on_the_cpu_and_gpu() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, WarpStyle};
|
||
|
||
let warp = |style, bend, horizontal_distortion, vertical_distortion, vertical, transform| EffectOperation::Warp {
|
||
style,
|
||
bend,
|
||
horizontal_distortion,
|
||
vertical_distortion,
|
||
vertical,
|
||
transform,
|
||
};
|
||
let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75), DVec2::new(4., 5.), 3., 0.);
|
||
|
||
// Within a square on the image 50 pixels across, measured from its corner
|
||
let on_image = square_on(DAffine2::from_scale(DVec2::splat(50.)));
|
||
|
||
// Every style bent both ways short of folding over itself, where a crease's texels could fall to either side
|
||
use WarpStyle::*;
|
||
let styles = [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist];
|
||
let mut cases: Vec<Vec<EffectOperation>> = styles.iter().flat_map(|&style| [40., -30.].map(|bend| vec![warp(style, bend, 0., 0., false, on_image)])).collect();
|
||
cases.extend([
|
||
vec![warp(Arc, 30., 25., -20., false, on_image)],
|
||
vec![warp(Flag, 35., 0., 0., true, on_image)],
|
||
vec![warp(Bulge, -25., -30., 15., true, on_image)],
|
||
// What a shadow paints past the square clears, as on the CPU
|
||
vec![shadow.clone(), warp(Arc, 45., 0., 0., false, on_image)],
|
||
vec![shadow.clone(), warp(Wave, 50., 0., 0., false, on_image)],
|
||
]);
|
||
// All of them side by side in one render
|
||
let filled_cases: Vec<_> = cases.iter().flat_map(|effects| [1., 0.5].map(|fill| (effects, fill))).collect();
|
||
let items = filled_cases.iter().map(|&(effects, fill)| patterned_raster(55., effects, fill)).collect();
|
||
let Some(tiles) = gpu_tiles_and_cpu_differences(items, UVec2::new(160, 160), 10) else {
|
||
return;
|
||
};
|
||
for (&(effects, fill), (_, differences)) in filled_cases.iter().zip(tiles) {
|
||
let worst = differences.into_iter().max().unwrap_or_default();
|
||
assert!(worst <= 3, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||
}
|
||
|
||
// A square wider than it's tall, bending into arcs that are circles in its own units
|
||
let on_oblong = square_on(DAffine2::from_scale(DVec2::new(50., 30.)));
|
||
for effect in [
|
||
warp(Arc, 40., 0., 0., false, on_oblong),
|
||
warp(Bulge, 35., 0., 0., true, on_oblong),
|
||
warp(Twist, 40., 0., 0., false, on_oblong),
|
||
] {
|
||
let Some(worst) = gpu_and_cpu_difference(patterned_raster_sized(55., UVec2::new(50, 30), std::slice::from_ref(&effect), 1.), UVec2::new(160, 160)) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{effect:?} on a raster 50 by 30 differs from the GPU by up to {worst} levels");
|
||
}
|
||
|
||
// Where the patch folds over itself, the GPU shows the sheet turned over on top as the CPU does, so only the texels along its creases differ.
|
||
// The wave's square is nudged off the texel grid, since the side its turned-over part ends at, which fades only outward, otherwise runs exactly through texel centers that roundoff splits between layers.
|
||
let nudged = DAffine2::from_translation(DVec2::new(0.3, 0.18)) * on_image;
|
||
for effect in [
|
||
warp(Wave, 100., 100., 100., false, nudged),
|
||
warp(Fisheye, 100., 0., 0., false, on_image),
|
||
warp(ShellLower, -100., 0., 0., false, on_image),
|
||
] {
|
||
let Some(differences) = gpu_and_cpu_differences_in_view(patterned_raster(55., std::slice::from_ref(&effect), 1.), UVec2::new(160, 160), DAffine2::IDENTITY) else {
|
||
return;
|
||
};
|
||
let differing = differences.iter().filter(|&&difference| difference > 3).count();
|
||
assert!(differing <= 8, "{effect:?} differs from the GPU by over 3 levels at {differing} texels");
|
||
}
|
||
|
||
// Only the right part of the warped content in view reads the part of the content left of the view, which the patch carries there.
|
||
// Premultiplied, so a faint pixel's colors don't magnify roundoff.
|
||
let partial_cases = [
|
||
vec![warp(Arc, 60., 0., 0., false, on_image)],
|
||
vec![warp(Twist, 70., 0., 0., false, on_image)],
|
||
vec![shadow.clone(), warp(Flag, 40., 0., 0., false, on_image)],
|
||
];
|
||
for effects in partial_cases {
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(20., &effects, 1.)));
|
||
let graphic = &graphic;
|
||
let draw = |offset: f64| move |scene: &mut VelloSceneBuilder| graphic.render_to_vello(scene, DAffine2::from_translation(DVec2::new(-offset, 0.)), &RenderParams::default());
|
||
let Some(whole) = render(UVec2::new(96, 96), draw(0.)) else { return };
|
||
let Some(part) = render(UVec2::new(32, 96), draw(56.)) else { return };
|
||
let premultiplied = |[red, green, blue, alpha]: [u8; 4]| [red, green, blue].map(|channel| channel as f32 * alpha as f32 / 255.).into_iter().chain([alpha as f32]);
|
||
for y in 0..96 {
|
||
for x in 0..32 {
|
||
let (expected, actual) = (pixel(&whole, UVec2::new(96, 96), x + 56, y), pixel(&part, UVec2::new(32, 96), x, y));
|
||
let difference = premultiplied(expected)
|
||
.zip(premultiplied(actual))
|
||
.map(|(expected, actual)| (expected - actual).abs())
|
||
.fold(0., f32::max);
|
||
assert!(difference <= 1.5, "{effects:?} at ({x}, {y}) shows {actual:?} rather than {expected:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
// Upright and turned a quarter, viewed at twice the size so the content's pixels land on the render's
|
||
let upright = DAffine2::from_translation(DVec2::splat(27.)) * DAffine2::from_scale(DVec2::splat(25.));
|
||
let turned = DAffine2::from_translation(DVec2::new(52., 27.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_2) * DAffine2::from_scale(DVec2::splat(25.));
|
||
for placement in [upright, turned] {
|
||
for effect in [warp(Arc, 40., 0., 0., false, on_image), warp(Rise, -35., 10., 0., true, on_image)] {
|
||
let item = patterned_raster(0., std::slice::from_ref(&effect), 1.).with_attribute(ATTR_TRANSFORM, placement);
|
||
let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::new(160, 160), DAffine2::from_scale(DVec2::splat(2.))) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{effect:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_match_on_the_cpu_and_gpu_within_offset_turned_and_slanted_squares() {
|
||
use glam::DVec2;
|
||
use graphic_types::{EffectOperation, WarpStyle};
|
||
|
||
// Within the image 50 pixels across, measured from its corner: a square smaller than it toward its bottom right, an oblong one turned about its middle, and one slanted
|
||
let offset = DAffine2::from_translation(DVec2::new(32., 30.)) * DAffine2::from_scale(DVec2::new(24., 18.));
|
||
let turned = DAffine2::from_translation(DVec2::new(25., 26.)) * DAffine2::from_angle(0.6) * DAffine2::from_scale(DVec2::new(40., 24.));
|
||
let slanted = DAffine2::from_translation(DVec2::new(24., 26.)) * DAffine2::from_cols_array(&[40., 0., 12., 24., 0., 0.]);
|
||
let warps = |transform| {
|
||
[
|
||
warp_effect(WarpStyle::Arc, 50., transform),
|
||
warp_effect(WarpStyle::Flag, -40., transform),
|
||
warp_effect(WarpStyle::Twist, 60., transform),
|
||
warp_effect(WarpStyle::Fisheye, 50., transform),
|
||
EffectOperation::Warp {
|
||
style: WarpStyle::Rise,
|
||
bend: -35.,
|
||
horizontal_distortion: 20.,
|
||
vertical_distortion: -15.,
|
||
vertical: true,
|
||
transform,
|
||
},
|
||
]
|
||
};
|
||
// All of them side by side in one render
|
||
let cases: Vec<_> = [offset, turned, slanted]
|
||
.into_iter()
|
||
.flat_map(warps)
|
||
.flat_map(|warp| [1., 0.5].map(|fill| (warp.clone(), fill)))
|
||
.collect();
|
||
let items = cases.iter().map(|(warp, fill)| patterned_raster(55., std::slice::from_ref(warp), *fill)).collect();
|
||
let Some(tiles) = gpu_tiles_and_cpu_differences(items, UVec2::new(160, 160), 6) else {
|
||
return;
|
||
};
|
||
for ((warp, fill), (_, differences)) in cases.iter().zip(tiles) {
|
||
let worst = differences.into_iter().max().unwrap_or_default();
|
||
assert!(worst <= 3, "{warp:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
/// Content of one `color` 60 by 40 pixels, one to each document unit, bent by a Warp of the `style` and `bend` within the square its `transform` places, if any.
|
||
fn one_color_raster(
|
||
color: core_types::Color,
|
||
warp: Option<(graphic_types::WarpStyle, f64, DAffine2)>,
|
||
) -> core_types::list::Item<graphic_types::raster_types::Raster<graphic_types::raster_types::CPU>> {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, stamp_effect};
|
||
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(60, 40, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::new(60., 40.)));
|
||
if let Some((style, bend, transform)) = warp {
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(style, bend, transform)));
|
||
}
|
||
item
|
||
}
|
||
|
||
/// How much of the pixel with its corner at `pixel` a Warp's square that `placement` places (from -0.5 to 0.5, at a pixel per unit) covers, fading across its sides as a side the warp keeps in place does.
|
||
fn warp_square_coverage(placement: DAffine2, pixel: glam::DVec2) -> f64 {
|
||
use graphic_types::resampling::{warp_frame, warp_half_fade};
|
||
|
||
let Some(square) = warp_frame(placement, DAffine2::IDENTITY) else { return 0. };
|
||
let (local, half, half_fade) = (square.pixels_to_local().transform_point2(pixel + 0.5), square.size / 2., warp_half_fade(&square));
|
||
(0.5 + (half - local.abs()) / (2. * half_fade)).clamp(glam::DVec2::ZERO, glam::DVec2::ONE).element_product()
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_leave_the_content_as_it_is_along_sides_they_keep_in_place_at_any_squeeze_and_offset() {
|
||
use glam::DVec2;
|
||
use graphic_types::WarpStyle;
|
||
use graphic_types::warp::Warp;
|
||
|
||
// Content of one color within a square 39 by 19 at two offsets and at a scale between pixels, and within squares slanted and turned off the pixel grid, which fisheyes, waves, and twists bend
|
||
// both ways, either side of where fisheyes squeeze the content nearly flat, past where they fold, and farther, keeping all four sides in place. The CPU's sweep covers their whole range.
|
||
let size = UVec2::new(64, 44);
|
||
let bends = [-60., 40., 59., 60., 67., 76., 100.];
|
||
let placements = [
|
||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30., 20.]),
|
||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]),
|
||
DAffine2::from_cols_array(&[42.5, 0., 0., 20.75, 30.25, 20.375]),
|
||
DAffine2::from_cols_array(&[24., 0., 16., 14., 30.3, 20.6]),
|
||
DAffine2::from_translation(DVec2::new(30.4, 20.15)) * DAffine2::from_angle(0.5) * DAffine2::from_scale(DVec2::new(30., 14.)),
|
||
];
|
||
let cases: Vec<_> = [WarpStyle::Fisheye, WarpStyle::Wave, WarpStyle::Twist]
|
||
.into_iter()
|
||
.flat_map(|style| bends.into_iter().flat_map(move |bend| placements.map(|placement| (style, bend, placement))))
|
||
.collect();
|
||
|
||
// All the cases side by side in one render for each color
|
||
for color in [core_types::Color::WHITE, core_types::Color::from_rgbaf32_unchecked(1., 1., 1., 0.5)] {
|
||
let items = cases.iter().map(|&(style, bend, placement)| one_color_raster(color, Some((style, bend, placement)))).collect();
|
||
let Some(tiles) = gpu_tiles_and_cpu_differences(items, size, 15) else { return };
|
||
|
||
for (&(style, bend, placement), (warped, differences)) in cases.iter().zip(tiles) {
|
||
let offset = placement.translation;
|
||
|
||
// Whether the patch turns over anywhere
|
||
let warp = Warp {
|
||
style,
|
||
bend: bend / 100.,
|
||
horizontal_distortion: 0.,
|
||
vertical_distortion: 0.,
|
||
vertical: false,
|
||
};
|
||
let mesh = warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length()));
|
||
let folds = (0..65 * 65).any(|index| {
|
||
let [_, along_s, along_t] = mesh.point_and_tangents(DVec2::new((index % 65) as f64, (index / 65) as f64) / 64.);
|
||
along_s.perp_dot(along_t) <= 1e-9
|
||
});
|
||
|
||
// Where the patch doesn't fold, it shows the content within the square, clear past it, and the content faded by the square's coverage across its sides.
|
||
// Where it folds, the layers of opaque content cover at least that much.
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let expected = warp_square_coverage(placement, DVec2::new(x as f64, y as f64)) as f32 * color.a() * 255.;
|
||
let alpha = pixel(&warped, size, x, y)[3] as f32;
|
||
if !folds {
|
||
assert!(
|
||
(alpha - expected).abs() <= 1.,
|
||
"{style:?} at {bend} placed at {offset}, {color:?}, shows alpha {alpha} rather than {expected} at ({x}, {y})"
|
||
);
|
||
} else if color.a() == 1. {
|
||
assert!(alpha >= expected - 1., "{style:?} at {bend} placed at {offset} shows alpha {alpha}, short of {expected} at ({x}, {y})");
|
||
}
|
||
}
|
||
|
||
// Around each corner, it matches the CPU, which matches a supersampled reference there
|
||
let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner));
|
||
for pixel in corners
|
||
.into_iter()
|
||
.flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64)))
|
||
{
|
||
let difference = differences[(pixel.y as u32 * size.x + pixel.x as u32) as usize];
|
||
assert!(
|
||
difference <= 2,
|
||
"{style:?} at {bend} placed at {offset}, {color:?}, differs from the CPU by {difference} levels at {pixel}"
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_with_folds_out_past_a_side_clear_what_lies_outside_the_square_beneath_them() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Opaque rows 60 pixels wide down to just above a square's top side, and clear rows below, which a fisheye folds out over the rows above
|
||
let mut image = Image::new(60, 40, core_types::Color::TRANSPARENT);
|
||
image.data[..10 * 60].fill(core_types::Color::WHITE);
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(60., 40.)));
|
||
stamp_effect(
|
||
&mut item,
|
||
Effect::new(&warp_effect(WarpStyle::Fisheye, 100., DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.]))),
|
||
);
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
|
||
let size = UVec2::new(60, 40);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// The fold carries only the square's clear content, and the rows above clear
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let alpha = pixel(&pixels, size, x, y)[3];
|
||
assert!(alpha <= 1, "({x}, {y}) shows alpha {alpha}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_clear_content_well_outside_the_bent_square() {
|
||
use glam::DVec2;
|
||
use graphic_types::warp::Warp;
|
||
use graphic_types::{Graphic, WarpStyle};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Opaque content 60 by 40 pixels, within which a flag bends a square 30 by 20 at its middle
|
||
let size = UVec2::new(60, 40);
|
||
let placement = DAffine2::from_cols_array(&[30., 0., 0., 20., 30., 20.]);
|
||
let graphic = Graphic::RasterCPU(Box::new(one_color_raster(core_types::Color::WHITE, Some((WarpStyle::Flag, 40., placement)))));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// The pixels within two and a half of where the patch carries the square, past which its edge's fade and its fringe's miters reach nothing
|
||
let warp = Warp {
|
||
style: WarpStyle::Flag,
|
||
bend: 0.4,
|
||
horizontal_distortion: 0.,
|
||
vertical_distortion: 0.,
|
||
vertical: false,
|
||
};
|
||
let (mesh, to_pixels) = (warp.mesh(DVec2::new(30., 20.)), placement * DAffine2::from_translation(DVec2::splat(-0.5)));
|
||
let mut near = vec![false; (size.x * size.y) as usize];
|
||
for index in 0..201 * 201 {
|
||
let point = to_pixels.transform_point2(mesh.point(DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.));
|
||
for (x, y) in (-3..=3).flat_map(|y| (-3..=3).map(move |x| (x, y))) {
|
||
let pixel = (point - 0.5).round() + DVec2::new(x as f64, y as f64);
|
||
if (pixel + 0.5).distance(point) <= 2.5 && pixel.cmpge(DVec2::ZERO).all() && pixel.x < size.x as f64 && pixel.y < size.y as f64 {
|
||
near[(pixel.y as u32 * size.x + pixel.x as u32) as usize] = true;
|
||
}
|
||
}
|
||
}
|
||
|
||
// All else is clear, though the content was opaque there
|
||
let far: Vec<u32> = (0..size.x * size.y).filter(|&index| !near[index as usize]).collect();
|
||
assert!(far.len() > 1000, "only {} pixels lie far from the patch", far.len());
|
||
for index in far {
|
||
let alpha = pixel(&pixels, size, index % size.x, index / size.x)[3];
|
||
assert!(alpha == 0, "({}, {}) shows alpha {alpha}", index % size.x, index / size.x);
|
||
}
|
||
}
|
||
|
||
/// For fish bent far within a square that `placement` places on opaque content `content` pixels across, both ways and turned, and placed at zooms between pixels,
|
||
/// the alphas the GPU renders at the pixels of each fish's body (the half of the square nearer the side it bends out from, where it doesn't fold) farther than `margin` from the curves its sides bend into.
|
||
fn warp_fish_body_alphas(content: UVec2, placement: DAffine2, margin: f64) -> Option<Vec<(f64, bool, f64, glam::DVec2, u8)>> {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::warp::Warp;
|
||
use graphic_types::{Effect, EffectOperation, WarpStyle, stamp_effect};
|
||
|
||
// Each fish stamped on the content, which is then placed at its zoom, as a view between pixels would show it
|
||
let cases: Vec<(f64, bool, f64)> = [60., 80., 100.]
|
||
.into_iter()
|
||
.flat_map(|bend| [false, true].into_iter().flat_map(move |vertical| [0.91, 1.09, 1.37].map(move |zoom| (bend, vertical, zoom))))
|
||
.collect();
|
||
let view = |zoom: f64| DAffine2::from_translation(DVec2::new(40.3, 60.2)) * DAffine2::from_scale(DVec2::splat(zoom));
|
||
let items: Vec<_> = (cases.iter())
|
||
.map(|&(bend, vertical, zoom)| {
|
||
let unplaced = DAffine2::from_scale(content.as_dvec2());
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(content.x, content.y, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, unplaced);
|
||
let fish = EffectOperation::Warp {
|
||
style: WarpStyle::Fish,
|
||
bend,
|
||
horizontal_distortion: 0.,
|
||
vertical_distortion: 0.,
|
||
vertical,
|
||
transform: placement,
|
||
};
|
||
stamp_effect(&mut item, Effect::new(&fish));
|
||
item.with_attribute(ATTR_TRANSFORM, view(zoom) * unplaced)
|
||
})
|
||
.collect();
|
||
let tile = UVec2::new(240, 260);
|
||
let tiles = gpu_tiles(&items, tile, 6)?;
|
||
|
||
let mut alphas = Vec::new();
|
||
for (&(bend, vertical, zoom), pixels) in cases.iter().zip(&tiles) {
|
||
let warp = Warp {
|
||
style: WarpStyle::Fish,
|
||
bend: bend / 100.,
|
||
horizontal_distortion: 0.,
|
||
vertical_distortion: 0.,
|
||
vertical,
|
||
};
|
||
let mesh = warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length()));
|
||
let to_pixels = view(zoom) * placement * DAffine2::from_translation(DVec2::splat(-0.5));
|
||
let sides: Vec<DVec2> = (0..=400)
|
||
.flat_map(|index| {
|
||
let t = index as f64 / 400.;
|
||
[DVec2::new(0., t), DVec2::new(1., t), DVec2::new(t, 0.), DVec2::new(t, 1.)]
|
||
})
|
||
.map(|uv| to_pixels.transform_point2(mesh.point(uv)))
|
||
.collect();
|
||
|
||
for index in 0..101 * 101 {
|
||
let across = DVec2::new((index % 101) as f64 / 200., (index / 101) as f64 / 100.);
|
||
let uv = if vertical { DVec2::new(across.y, across.x) } else { across };
|
||
let texel = to_pixels.transform_point2(mesh.point(uv)).floor();
|
||
let within_tile = texel.cmpge(DVec2::ZERO).all() && texel.x < tile.x as f64 && texel.y < tile.y as f64;
|
||
if within_tile && sides.iter().all(|side| side.distance(texel + 0.5) >= margin) {
|
||
alphas.push((bend, vertical, zoom, texel, pixel(pixels, tile, texel.x as u32, texel.y as u32)[3]));
|
||
}
|
||
}
|
||
}
|
||
Some(alphas)
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_bending_far_leave_no_holes_within_their_patch_at_any_zoom() {
|
||
// Opaque content just the size of the square, so its own edge fades where the zoom stretches it, yet nowhere within the body is anything like a hole
|
||
let Some(alphas) = warp_fish_body_alphas(UVec2::new(60, 40), DAffine2::from_cols_array(&[60., 0., 0., 40., 30., 20.]), 3.) else {
|
||
return;
|
||
};
|
||
for (bend, vertical, zoom, texel, alpha) in alphas {
|
||
assert!(alpha >= 192, "the fish at {bend}, vertical {vertical}, at zoom {zoom}, shows alpha {alpha} at {texel}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_bending_far_keep_opaque_content_opaque_within_their_patch_at_any_zoom() {
|
||
// Opaque content reaching 20 pixels past the square on each side, so each pixel within the body reads only opaque content
|
||
let Some(alphas) = warp_fish_body_alphas(UVec2::new(100, 80), DAffine2::from_cols_array(&[60., 0., 0., 40., 50., 40.]), 2.) else {
|
||
return;
|
||
};
|
||
for (bend, vertical, zoom, texel, alpha) in alphas {
|
||
assert!(alpha >= 254, "the fish at {bend}, vertical {vertical}, at zoom {zoom}, shows alpha {alpha} at {texel}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_with_sides_curving_sharply_toward_a_pixel_fade_it() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Opaque content past a square 10 by 200 that a flag waves far, so its top side's crest curves tightly past the pixel (28, 87), a third of a pixel within it, as on the CPU
|
||
let size = UVec2::new(80, 500);
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(size.x, size.y, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2()));
|
||
stamp_effect(
|
||
&mut item,
|
||
Effect::new(&warp_effect(WarpStyle::Flag, 100., DAffine2::from_cols_array(&[10., 0., 0., 200., 25.625, 300.75]))),
|
||
);
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
let alpha = pixel(&pixels, size, 28, 87)[3];
|
||
assert!(alpha.abs_diff(212) <= 4, "the pixel shows alpha {alpha}");
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_of_fisheyes_squeezing_the_content_nearly_flat_against_a_side_keep_it_seamless() {
|
||
use graphic_types::{Graphic, WarpStyle};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Opaque content past a square with its top side three quarters of the way down a row of pixels, against which fisheyes squeeze the content nearly flat
|
||
let size = UVec2::new(60, 40);
|
||
for bend in [59., 60.] {
|
||
let transform = DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]);
|
||
let graphic = Graphic::RasterCPU(Box::new(one_color_raster(core_types::Color::WHITE, Some((WarpStyle::Fisheye, bend, transform)))));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let (alpha, expected) = (pixel(&pixels, size, x, y)[3] as f64, warp_square_coverage(transform, glam::DVec2::new(x as f64, y as f64)) * 255.);
|
||
assert!((alpha - expected).abs() <= 1., "bent {bend}, ({x}, {y}) shows alpha {alpha} rather than {expected}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_within_slanted_squares_keep_the_content_as_it_is_past_corners_they_keep_in_place() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Opaque content past a square slanted to corners an eighth of a turn sharp, off the pixel grid, within which a fisheye keeps the sides in place
|
||
let size = UVec2::new(120, 80);
|
||
let transform = DAffine2::from_cols_array(&[40., 0., 40., 40., 61., 40.75]);
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(size.x, size.y, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2()));
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Fisheye, 40., transform)));
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let (alpha, expected) = (pixel(&pixels, size, x, y)[3] as f64, warp_square_coverage(transform, glam::DVec2::new(x as f64, y as f64)) * 255.);
|
||
assert!((alpha - expected).abs() <= 1., "({x}, {y}) shows alpha {alpha} rather than {expected}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_of_folds_returning_over_a_side_change_smoothly_as_the_side_moves() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Clear rows down through the one a square's top side runs through the middle of, and opaque rows below, which a fisheye folds out over the clear rows and back
|
||
let size = UVec2::new(60, 40);
|
||
let alpha_at = |down: f64| {
|
||
let mut image = Image::new(size.x, size.y, core_types::Color::WHITE);
|
||
image.data[..11 * 60].fill(core_types::Color::TRANSPARENT);
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(60., 40.)));
|
||
stamp_effect(
|
||
&mut item,
|
||
Effect::new(&warp_effect(WarpStyle::Fisheye, 100., DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, down]))),
|
||
);
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())).map(|pixels| pixel(&pixels, size, 30, 10)[3])
|
||
};
|
||
|
||
// Moving the side a fiftieth of a pixel across the pixel's center moves its fade only as far
|
||
let (Some(above), Some(below)) = (alpha_at(19.99), alpha_at(20.01)) else { return };
|
||
assert!(above.abs_diff(below) <= 8, "the pixel's alpha jumps from {above} to {below}");
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_carry_nothing_wholly_outside_a_slanted_or_turned_square() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Clear content, one pixel to each document unit, but for an opaque pixel just above the top side of a slanted square, which an upper arc raises past where the pixel lies,
|
||
// or just above the top corner of a square turned an eighth, which an arc bends far around
|
||
let cases = [
|
||
(UVec2::new(80, 40), UVec2::new(30, 9), WarpStyle::ArcUpper, 50., [40., 0., 40., 4., 50., 12.]),
|
||
(UVec2::new(80, 60), UVec2::new(40, 9), WarpStyle::Arc, 80., [20., 20., -20., 20., 40.5, 30.01]),
|
||
];
|
||
for (size, opaque, style, bend, transform) in cases {
|
||
let mut image = Image::new(size.x, size.y, core_types::Color::TRANSPARENT);
|
||
image.data[(opaque.y * size.x + opaque.x) as usize] = core_types::Color::WHITE;
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2()));
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(style, bend, DAffine2::from_cols_array(&transform))));
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
|
||
// The patch carries none of the pixel anywhere, and the pixel clears where it lies
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
let alpha = pixel(&pixels, size, x, y)[3];
|
||
assert!(alpha <= 1, "{style:?} shows alpha {alpha} at ({x}, {y})");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_within_squares_far_smaller_than_a_pixel_match_on_the_cpu_and_gpu() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, WarpStyle, stamp_effect};
|
||
|
||
// Opaque white 25 pixels across stretched to 2500 units and viewed at a hundredth of that, twisted within a square one unit across at its middle
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(25, 25, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2500.)));
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Twist, 80., DAffine2::from_translation(DVec2::splat(1275.)))));
|
||
|
||
let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::splat(64), DAffine2::from_scale(DVec2::splat(0.01))) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "the GPU differs from the CPU by up to {worst} levels");
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_within_the_identity_or_a_collapsed_transform_clear_all_but_a_pixel_or_two() {
|
||
use glam::DVec2;
|
||
use graphic_types::WarpStyle;
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let draw = |effects: &[graphic_types::EffectOperation]| {
|
||
let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(55., effects, 1.)));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
|
||
// The identity is a square 1 across at the image's corner (55, 55), clearing all a pixel or two from it, and a square collapsed onto a line clears everything
|
||
let collapsed = DAffine2::from_scale(DVec2::new(50., 0.));
|
||
for (transform, reach) in [(DAffine2::IDENTITY, 2.), (collapsed, 0.)] {
|
||
for warp in [WarpStyle::Arc, WarpStyle::Twist, WarpStyle::Squeeze].map(|style| warp_effect(style, 80., transform)) {
|
||
let Some(warped) = draw(std::slice::from_ref(&warp)) else { return };
|
||
for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) {
|
||
if (DVec2::new(x as f64 + 0.5, y as f64 + 0.5) - 55.).abs().max_element() <= reach {
|
||
continue;
|
||
}
|
||
let alpha = pixel(&warped, size, x, y)[3];
|
||
assert!(alpha == 0, "{warp:?} shows alpha {alpha} at ({x}, {y})");
|
||
}
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), 1.), size) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_on_squares_turned_since_an_earlier_warp_match_on_the_cpu_and_gpu() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, WarpStyle, stamp_effect};
|
||
|
||
// A banner of 160 by 40 pixels, one to each document unit, of colors varying across it
|
||
let banner = UVec2::new(160, 40);
|
||
let data: Vec<_> = (0..banner.x * banner.y)
|
||
.map(|index| {
|
||
let (x, y) = ((index % banner.x) as f32 + 0.5, (index / banner.x) as f32 + 0.5);
|
||
core_types::Color::from_gamma_srgb_channels(x / banner.x as f32, y / banner.y as f32, (x * 0.2).sin() * 0.5 + 0.5, 1.)
|
||
})
|
||
.collect();
|
||
let image = Image {
|
||
width: banner.x,
|
||
height: banner.y,
|
||
data,
|
||
};
|
||
|
||
// An arc within a square on the banner bends it far above its top side, then a transform turns it off the document's axes.
|
||
// A flag within a square on the turned banner, stamped after the turn, starts a run of its own.
|
||
for degrees in [45_f64, 30., -60.] {
|
||
let turn = DAffine2::from_angle(degrees.to_radians());
|
||
let stamped = DAffine2::from_scale(banner.as_dvec2());
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image.clone())).with_attribute(ATTR_TRANSFORM, stamped);
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Arc, 50., square_on(stamped))));
|
||
let mut item = item.with_attribute(ATTR_TRANSFORM, turn * stamped);
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Flag, 30., square_on(turn * stamped))));
|
||
|
||
// Viewed turned back, so the content's pixels land on the render's
|
||
let view = DAffine2::from_translation(DVec2::new(48., 64.)) * turn.inverse();
|
||
let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::new(256, 136), view) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "turned {degrees} degrees, the flag differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn radial_blurs_spin_all_that_earlier_warps_bent_past_a_frame_turned_or_scaled_since() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::Item;
|
||
use glam::DVec2;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, RadialBlurMethod, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A banner of 300 by 30 pixels, one to each document unit once placed, of colors varying across it
|
||
let banner = UVec2::new(300, 30);
|
||
let data: Vec<_> = (0..banner.x * banner.y)
|
||
.map(|index| {
|
||
let (x, y) = ((index % banner.x) as f32 + 0.5, (index / banner.x) as f32 + 0.5);
|
||
core_types::Color::from_gamma_srgb_channels(x / banner.x as f32, y / banner.y as f32, (x * 0.2).sin() * 0.5 + 0.5, 1.)
|
||
})
|
||
.collect();
|
||
|
||
// An arc within a square on the banner bends it into a half ring where it spans `stamped_size`, then it's placed by `placement`, and a spin about a point past its end stamped after starts a run of its own
|
||
let bent_and_spun = |stamped_size: DVec2, placement: DAffine2| {
|
||
let image = Image {
|
||
width: banner.x,
|
||
height: banner.y,
|
||
data: data.clone(),
|
||
};
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(stamped_size));
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Arc, 100., square_on(DAffine2::from_scale(stamped_size)))));
|
||
let mut item = item.with_attribute(ATTR_TRANSFORM, placement);
|
||
stamp_effect(
|
||
&mut item,
|
||
Effect::new(&EffectOperation::RadialBlur {
|
||
method: RadialBlurMethod::Spin,
|
||
amount: 45.,
|
||
transform: DAffine2::from_translation(placement.transform_point2(DVec2::new(1.5, 0.5))),
|
||
gamma: false,
|
||
}),
|
||
);
|
||
item
|
||
};
|
||
let size = banner.as_dvec2();
|
||
|
||
// Scaled twice as large and turned a half since, its pixels still land on the render's, so the CPU and GPU match throughout
|
||
let scaled = bent_and_spun(size / 2., DAffine2::from_angle(std::f64::consts::PI) * DAffine2::from_scale(size));
|
||
let Some(worst) = gpu_and_cpu_difference_in_view(scaled, UVec2::new(440, 520), DAffine2::from_translation(DVec2::new(380., 240.))) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "scaled and turned a half, the spin differs from the GPU by up to {worst} levels");
|
||
|
||
// Turned 60 degrees since, the GPU shows the smear wherever the CPU's image drawn plainly does
|
||
let turned = bent_and_spun(size, DAffine2::from_angle(60_f64.to_radians()) * DAffine2::from_scale(size));
|
||
let (render_size, view) = (UVec2::new(560, 460), DAffine2::from_translation(DVec2::new(200., 100.)));
|
||
let warped = Graphic::RasterCPU(Box::new(turned.clone()));
|
||
let Some(gpu) = render_in_view(render_size, view, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(turned)));
|
||
let Some(cpu) = render_in_view(render_size, view, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, render_size, index % render_size.x, index / render_size.x)[3];
|
||
let missing = (0..render_size.x * render_size.y).filter(|&index| alpha(&cpu, index) >= 8 && alpha(&gpu, index) == 0).count();
|
||
assert!(missing <= 2, "turned 60 degrees, {missing} pixels of the smear are missing on the GPU");
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_clear_what_earlier_effects_paint_past_a_slanted_square() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use glam::{DMat2, DVec2};
|
||
use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Content slanted 45 degrees within a square on it, casting a sharp shadow 20 units down, past the square's slanted bottom side
|
||
let slant = DMat2::from_cols(DVec2::new(100., 0.), DVec2::new(100., 100.));
|
||
let skewed = DAffine2::from_translation(DVec2::new(20., 10.)) * DAffine2::from_mat2(slant);
|
||
let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 1.), DVec2::new(0., 20.), 0., 0.);
|
||
let flag = warp_effect(WarpStyle::Flag, 0.25, square_on(DAffine2::from_mat2(slant)));
|
||
|
||
// The shadow alone, and with a flag too slight to move the content more than a pixel
|
||
let size = UVec2::new(240, 160);
|
||
let draw = |effects: &[graphic_types::EffectOperation]| {
|
||
let mut item = patterned_raster(0., &[], 1.).with_attribute(ATTR_TRANSFORM, skewed);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
let (Some(alone), Some(flagged)) = (draw(std::slice::from_ref(&shadow)), draw(&[shadow.clone(), flag])) else {
|
||
return;
|
||
};
|
||
|
||
// Wherever the shadow alone shows well within the slanted square, so does the flagged one, and wherever it shows well past the square, the flagged one is clear
|
||
let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, size, index % size.x, index / size.x)[3];
|
||
let local = |index: u32| skewed.inverse().transform_point2(DVec2::new((index % size.x) as f64 + 0.5, (index / size.x) as f64 + 0.5));
|
||
let shown: Vec<u32> = (0..size.x * size.y).filter(|&index| alpha(&alone, index) > 192).collect();
|
||
let within: Vec<u32> = shown
|
||
.iter()
|
||
.copied()
|
||
.filter(|&index| local(index).cmpgt(DVec2::splat(0.03)).all() && local(index).cmplt(DVec2::splat(0.97)).all())
|
||
.collect();
|
||
let past: Vec<u32> = shown
|
||
.iter()
|
||
.copied()
|
||
.filter(|&index| local(index).cmplt(DVec2::splat(-0.03)).any() || local(index).cmpgt(DVec2::splat(1.03)).any())
|
||
.collect();
|
||
assert!(past.len() > 500, "only {} pixels of the shadow lie past the slanted square", past.len());
|
||
|
||
let missing = within.iter().filter(|&&index| alpha(&flagged, index) < 64).count();
|
||
assert!(missing <= 2, "{missing} pixels of the content are missing within the slanted square");
|
||
let kept = past.iter().filter(|&&index| alpha(&flagged, index) > 1).count();
|
||
assert!(kept == 0, "{kept} pixels of the shadow show past the slanted square");
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_clear_what_a_minimum_grows_past_a_turned_square() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::{ATTR_APPEARANCE, List};
|
||
use glam::DVec2;
|
||
use graphic_types::{Appearance, Coverage, Effect, Graphic, Vector, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
// An opaque rectangle 200 by 100 turned 45 degrees when its effects were stamped, within a square on it, then left turned or turned back upright,
|
||
// so a minimum's square leans across the rectangle and grows it past each side by the square's half diagonal
|
||
let centered = |transform: DAffine2| DAffine2::from_translation(DVec2::splat(200.)) * transform * DAffine2::from_translation(-DVec2::new(100., 50.));
|
||
let turned = centered(DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
|
||
let minimum = minimum_maximum(20., MinimumMaximumMode::Minimum);
|
||
let flag = warp_effect(WarpStyle::Flag, 0.25, DAffine2::from_mat2(turned.matrix2) * square_on(DAffine2::from_scale(DVec2::new(200., 100.))));
|
||
let size = UVec2::splat(400);
|
||
|
||
for placement in [turned, centered(DAffine2::IDENTITY)] {
|
||
// The grown rectangle alone, and with a flag too slight to move the content more than a pixel
|
||
let draw = |effects: &[graphic_types::EffectOperation]| {
|
||
let mut item = Vector::item_from_bezpath(&Rect::new(0., 0., 200., 100.).to_path(0.1));
|
||
item.set_attribute(
|
||
ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(core_types::Color::WHITE))),
|
||
);
|
||
item.set_attribute(ATTR_TRANSFORM, turned);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
item.set_attribute(ATTR_TRANSFORM, placement);
|
||
let graphic = Graphic::Vector(Box::new(item));
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
let (Some(alone), Some(flagged)) = (draw(std::slice::from_ref(&minimum)), draw(&[minimum.clone(), flag.clone()])) else {
|
||
return;
|
||
};
|
||
|
||
// Wherever the grown rectangle alone shows well within the square, so does the flagged one, and wherever it shows well past the square, the flagged one is clear
|
||
let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, size, index % size.x, index / size.x)[3];
|
||
let local = |index: u32| placement.inverse().transform_point2(DVec2::new((index % size.x) as f64 + 0.5, (index / size.x) as f64 + 0.5));
|
||
let shown: Vec<u32> = (0..size.x * size.y).filter(|&index| alpha(&alone, index) > 192).collect();
|
||
let within: Vec<u32> = shown
|
||
.iter()
|
||
.copied()
|
||
.filter(|&index| local(index).cmpgt(DVec2::splat(3.)).all() && local(index).cmplt(DVec2::new(197., 97.)).all())
|
||
.collect();
|
||
let past: Vec<u32> = shown
|
||
.iter()
|
||
.copied()
|
||
.filter(|&index| local(index).cmplt(DVec2::splat(-3.)).any() || local(index).cmpgt(DVec2::new(203., 103.)).any())
|
||
.collect();
|
||
assert!(past.len() > 500, "placed at {placement}, only {} pixels of the grown rectangle lie past its square", past.len());
|
||
|
||
let missing = within.iter().filter(|&&index| alpha(&flagged, index) < 64).count();
|
||
assert!(missing <= 2, "placed at {placement}, {missing} pixels of the rectangle are missing within its square");
|
||
let kept = past.iter().filter(|&&index| alpha(&flagged, index) > 1).count();
|
||
assert!(kept == 0, "placed at {placement}, {kept} pixels of the grown rectangle show past its square");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_leave_what_earlier_warps_bent_before_a_stretch_alike_on_the_cpu_and_gpu() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use glam::DVec2;
|
||
use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
let size = UVec2::new(560, 200);
|
||
|
||
// A square bent into an arc within a square on it, then stretched four times as wide, its ends then far past its sides, past the square of a warp stamped after the stretch
|
||
let stretched = DAffine2::from_translation(DVec2::new(180., 70.)) * DAffine2::from_scale(DVec2::new(200., 50.));
|
||
let arc = warp_effect(WarpStyle::Arc, 50., square_on(DAffine2::from_scale(DVec2::splat(50.))));
|
||
for second in [WarpStyle::Flag, WarpStyle::Twist] {
|
||
let mut item = patterned_raster(0., std::slice::from_ref(&arc), 1.).with_attribute(ATTR_TRANSFORM, stretched);
|
||
stamp_effect(&mut item, Effect::new(&warp_effect(second, 30., square_on(DAffine2::from_mat2(stretched.matrix2)))));
|
||
|
||
// The GPU's warps, beside the CPU's warped image drawn plainly, with pixels four times as wide as the render's
|
||
let warped = Graphic::RasterCPU(Box::new(item.clone()));
|
||
let Some(gpu) = render(size, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(item)));
|
||
let Some(cpu) = render(size, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// Each shows the content wherever the other does
|
||
let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, size, index % size.x, index / size.x)[3];
|
||
let shown_by_one = |index: &u32| (alpha(&gpu, *index) > 192 && alpha(&cpu, *index) < 64) || (alpha(&cpu, *index) > 192 && alpha(&gpu, *index) < 64);
|
||
let differing = (0..size.x * size.y).filter(shown_by_one).count();
|
||
assert!(differing <= 2, "after {second:?}, {differing} pixels of the content show on only one of the CPU and GPU");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warp_effects_stretched_after_they_bend_keep_their_bend_stretched() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use glam::DVec2;
|
||
use graphic_types::{Graphic, WarpStyle};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A square 50 across bent into an arc within a square on it, then stretched four times as wide, as a transform after the warp does
|
||
let arc = warp_effect(WarpStyle::Arc, 50., square_on(DAffine2::from_scale(DVec2::splat(50.))));
|
||
let stretched = DAffine2::from_translation(DVec2::new(160., 40.)) * DAffine2::from_scale(DVec2::new(200., 50.));
|
||
let graphic = Graphic::RasterCPU(Box::new(patterned_raster(0., std::slice::from_ref(&arc), 1.).with_attribute(ATTR_TRANSFORM, stretched)));
|
||
let size = UVec2::new(520, 140);
|
||
let Some(image) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
// The square's arcs stretched with it, their ends 0.707 of its width past its sides and their top 0.207 of its height above it
|
||
let painted = (0..size.x * size.y).filter(|index| pixel(&image, size, index % size.x, index / size.x)[3] > 128);
|
||
let (left, right, top) = painted.fold((size.x, 0, size.y), |(left, right, top), index| {
|
||
(left.min(index % size.x), right.max(index % size.x), top.min(index / size.x))
|
||
});
|
||
let within = |edge: u32, expected: f64| (edge as f64 - expected).abs() < 3.;
|
||
assert!(within(left, 18.6) && within(right, 501.4) && within(top, 29.6), "the bend spans {left} to {right} from {top} down");
|
||
}
|
||
|
||
/// Blend If's ranges: from the falloff start, through the range start and end, to the falloff end, as levels from 0 to 255.
|
||
fn blend_range([falloff_start, range_start, range_end, falloff_end]: [f64; 4]) -> graphic_types::blend_if::BlendRange {
|
||
let percent = |level: f64| level / 255. * 100.;
|
||
graphic_types::blend_if::BlendRange {
|
||
falloff_start: percent(falloff_start),
|
||
range_start: percent(range_start),
|
||
range_end: percent(range_end),
|
||
falloff_end: percent(falloff_end),
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_fade_the_content_by_its_tones_on_the_gpu_like_on_the_cpu() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||
use glam::DVec2;
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{EffectOperation, Effects};
|
||
use raster_kernels::evaluate_raster_effects;
|
||
|
||
let size = UVec2::new(160, 160);
|
||
let (min, max) = (30_u32, 130_u32);
|
||
|
||
// One-pixel columns stepping through every other level, in gray above a band of red and green rising against each other
|
||
let column_color = |x: u32, y: u32| {
|
||
let level = ((x - min) * 255 / (max - min - 1)) as u8;
|
||
match y < 80 {
|
||
true => [level, level, level],
|
||
false => [level, 255 - level, 64],
|
||
}
|
||
};
|
||
|
||
let with_content = |ranges: BlendIfRanges| EffectOperation::BlendIf(Box::new(ranges));
|
||
let gray = |range: [f64; 4]| {
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.content.gray = blend_range(range);
|
||
ranges
|
||
};
|
||
let soft = gray([40., 90., 160., 220.]);
|
||
let hard = gray([64., 64., 192., 192.]);
|
||
let colored = {
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.content.red = blend_range([30., 120., 255., 255.]);
|
||
ranges.content.green = blend_range([0., 0., 200., 240.]);
|
||
ranges.content.blue = blend_range([0., 0., 128., 160.]);
|
||
ranges
|
||
};
|
||
let shadow = drop_shadow(GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75), DVec2::new(6., 4.), 8., 25.);
|
||
let inner_shadow = EffectOperation::InnerShadow {
|
||
color: GraphicColor::from_rgbaf32_unchecked(0.8, 0.2, 0.1, 0.75),
|
||
blend_mode: core_types::blending::BlendMode::Screen,
|
||
angle: 135.,
|
||
distance: 5.,
|
||
choke: 0.,
|
||
size: 6.,
|
||
contour: Default::default(),
|
||
};
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 3.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
|
||
let cases = [
|
||
vec![with_content(soft)],
|
||
vec![with_content(hard)],
|
||
vec![with_content(colored)],
|
||
// The shadow is knocked out by the content as Blend If leaves it, wherever it lies in the order
|
||
vec![shadow.clone(), with_content(soft)],
|
||
vec![with_content(hard), shadow.clone()],
|
||
// Blend If reads the content as a blur before it leaves it, and a blur after it softens what it hides
|
||
vec![blur.clone(), with_content(soft)],
|
||
vec![with_content(hard), blur.clone()],
|
||
// An adjustment changing nothing ahead of it leaves it acting first, as at the start
|
||
vec![EffectOperation::Adjustment(graphic_types::Adjustment::MakeOpaque { strength: 0. }), with_content(hard), blur],
|
||
// Two Blend Ifs multiply
|
||
vec![with_content(soft), with_content(colored)],
|
||
// An interior piece blends over what shows through where Blend If fades the content, as through a partial fill
|
||
vec![inner_shadow, with_content(soft)],
|
||
];
|
||
|
||
for effects in cases {
|
||
for fill in [1., 0.5] {
|
||
let effects_list = Effects::from_operations(effects.clone());
|
||
let draw_columns = |scene: &mut VelloSceneBuilder| {
|
||
for y in [min, 80] {
|
||
for x in min..max {
|
||
let [red, green, blue] = column_color(x, y);
|
||
let column = Rect::new(x as f64, y as f64, (x + 1) as f64, (y + 50) as f64);
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(red, green, blue), None, &column);
|
||
}
|
||
}
|
||
};
|
||
let bounds = Rect::new(min as f64, min as f64, max as f64, max as f64);
|
||
let Some(gpu) = render(size, |scene| {
|
||
scene.draw_effects(&effects_list, fill, 1., BlendMode::Normal, true, Some(bounds), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
draw_columns(scene)
|
||
})
|
||
}) else {
|
||
return;
|
||
};
|
||
|
||
// The same columns as a raster covering the render one pixel to one pixel
|
||
let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT);
|
||
for y in min..max {
|
||
for x in min..max {
|
||
let [red, green, blue] = column_color(x, if y < 80 { min } else { 80 });
|
||
image.data[(y * size.x + x) as usize] = GraphicColor::from(core_types::color::SRGBA8::new(red, green, blue, 255));
|
||
}
|
||
}
|
||
let mut item = Item::new_from_element(Raster::new_cpu(image))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2()))
|
||
.with_attribute(ATTR_OPACITY_FILL, fill as f64);
|
||
effects.iter().for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)));
|
||
let evaluated = evaluate_raster_effects(item);
|
||
let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||
let raster = evaluated.element();
|
||
let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse();
|
||
|
||
let mut worst = 0;
|
||
for y in 0..size.y {
|
||
for x in 0..size.x {
|
||
let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor();
|
||
let [red, green, blue, alpha] = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize].to_gamma_srgb_channels();
|
||
let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.);
|
||
|
||
// Compared premultiplied, so a nearly transparent pixel's color can't dominate
|
||
let gpu = pixel(&gpu, size, x, y);
|
||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||
for channel in 0..4 {
|
||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||
worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32);
|
||
}
|
||
}
|
||
}
|
||
// A blur leaves colors between levels, where the GPU's and the CPU's precisions can round to neighboring levels, which a falloff amplifies
|
||
let tolerance = if matches!(effects[0], EffectOperation::Blur { .. }) { 8 } else { 2 };
|
||
assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_fade_everything_the_content_draws_by_what_lies_beneath() {
|
||
use core_types::Color as GraphicColor;
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = Rect::new(24., 24., 104., 104.);
|
||
|
||
// Shown fully over backdrops at least half gray, fading in from a quarter
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.underlying.gray = blend_range([64., 128., 255., 255.]);
|
||
let effects = Effects::from_operations([drop_shadow(GraphicColor::BLACK, glam::DVec2::new(0., 16.), 0., 100.), EffectOperation::BlendIf(Box::new(ranges))]);
|
||
|
||
// A black backdrop on the left, a gray of 96 in the middle, and white on the right, leaving the bottom rows empty
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(0, 0, 0), None, &Rect::new(0., 0., 48., 112.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(96, 96, 96), None, &Rect::new(48., 0., 80., 112.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 255, 255), None, &Rect::new(80., 0., 128., 112.));
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 0, 0), None, &square)
|
||
});
|
||
};
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
|
||
assert_eq!(pixel(&pixels, size, 30, 60), [0, 0, 0, 255], "over black, the content is hidden");
|
||
assert_eq!(pixel(&pixels, size, 90, 60), [255, 0, 0, 255], "over white, it shows fully");
|
||
let [middle_red, middle_green, ..] = pixel(&pixels, size, 64, 60);
|
||
assert!(
|
||
(middle_red as i32 - 96 - (255 - 96) / 2).abs() <= 2 && (middle_green as i32 - 48).abs() <= 2,
|
||
"half-way up the falloff, half of it shows: {middle_red}, {middle_green}"
|
||
);
|
||
assert_eq!(pixel(&pixels, size, 30, 108), [0, 0, 0, 255], "its shadow is hidden over black too");
|
||
assert_eq!(pixel(&pixels, size, 90, 116), [0, 0, 0, 255], "and shows where nothing lies beneath");
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_beneath_multiply_their_channels_and_ease_over_translucent_backdrops() {
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(96, 96);
|
||
let square = Rect::new(16., 16., 80., 80.);
|
||
|
||
// Two rows: one shows only over a gray of at least 128, and the other only over a red of at most 200
|
||
let mut gray = BlendIfRanges::default();
|
||
gray.underlying.gray = blend_range([128., 128., 255., 255.]);
|
||
let mut red = BlendIfRanges::default();
|
||
red.underlying.red = blend_range([0., 0., 200., 200.]);
|
||
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(gray)), EffectOperation::BlendIf(Box::new(red))]);
|
||
|
||
// Light gray on the left, white in the middle, and black at half alpha on the right
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(180, 180, 180), None, &Rect::new(0., 0., 32., 96.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(255, 255, 255), None, &Rect::new(32., 0., 64., 96.));
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgba8(0, 0, 0, 128), None, &Rect::new(64., 0., 96., 96.));
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgb8(0, 0, 255), None, &square)
|
||
});
|
||
};
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
|
||
assert_eq!(pixel(&pixels, size, 24, 48), [0, 0, 255, 255], "over light gray, both rows show it");
|
||
assert_eq!(pixel(&pixels, size, 48, 48), [255, 255, 255, 255], "over white, its red hides it");
|
||
// Over black at half alpha, the weight eases halfway from hidden to shown, leaving half the blue over the black
|
||
let [_, _, blue, alpha] = pixel(&pixels, size, 72, 48);
|
||
assert!(blue.abs_diff(170) <= 2 && alpha.abs_diff(191) <= 2, "{:?}", pixel(&pixels, size, 72, 48));
|
||
}
|
||
|
||
#[test]
|
||
fn a_paint_overlay_beside_a_blend_if_looks_the_same_at_a_full_fill() {
|
||
use core_types::list::{ATTR_EFFECTS, Item};
|
||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::Adjustment;
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{EffectOperation, Effects, Graphic};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A gray ramp, painted red over, then shown only where its own gray is at least 40%
|
||
let data: Vec<core_types::Color> = (0..64)
|
||
.map(|x| core_types::Color::from_gamma_srgb_channels(x as f32 / 63., x as f32 / 63., x as f32 / 63., 1.))
|
||
.collect();
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.content.gray.range_start = 40.;
|
||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||
color: core_types::Color::RED,
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
});
|
||
let effects = Effects::from_operations([red, EffectOperation::BlendIf(Box::new(ranges))]);
|
||
let item = |fill: f64| {
|
||
let image = Image {
|
||
width: 64,
|
||
height: 1,
|
||
data: data.clone(),
|
||
};
|
||
let raster = Item::new_from_element(Raster::new_cpu(image))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(64., 16.)))
|
||
.with_attribute(ATTR_EFFECTS, effects.clone())
|
||
.with_attribute(ATTR_OPACITY_FILL, fill);
|
||
Graphic::RasterCPU(Box::new(raster))
|
||
};
|
||
|
||
let size = UVec2::new(64, 16);
|
||
let render_item = |fill: f64| render(size, |scene| item(fill).render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||
let (Some(full), Some(nearly_full)) = (render_item(1.), render_item(0.999)) else { return };
|
||
|
||
// The overlay paints at full strength over the content's share, which Blend If reads before it, so only the light end shows
|
||
assert_eq!(pixel(&full, size, 60, 8), [255, 0, 0, 255], "the light end shows the overlay");
|
||
assert_eq!(pixel(&full, size, 4, 8)[3], 255, "and so does the dark end, where the content is blended out beneath it");
|
||
for x in 0..size.x {
|
||
let (first, second) = (pixel(&full, size, x, 8), pixel(&nearly_full, size, x, 8));
|
||
assert!(first.iter().zip(second).all(|(a, b)| a.abs_diff(b) <= 1), "at {x}: {first:?} at a full fill, {second:?} at 99.9%");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_beneath_read_the_straight_color_of_translucent_backdrops() {
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(64, 64);
|
||
let square = Rect::new(16., 16., 48., 48.);
|
||
|
||
// Shown only over light backdrops, which white at half alpha is, though its premultiplied color is a middle gray
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.underlying.gray = blend_range([200., 200., 255., 255.]);
|
||
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::from_rgba8(255, 255, 255, 128), None, &Rect::new(0., 0., 64., 64.));
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), DAffine2::IDENTITY, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, BLUE, None, &square)
|
||
});
|
||
};
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
|
||
assert_eq!(pixel(&pixels, size, 32, 32), [0, 0, 255, 255], "the content shows fully over the translucent white");
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_read_what_lies_beneath_them_in_any_effect_space() {
|
||
use glam::{DMat2, DVec2};
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::{EffectOperation, Effects};
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let square = Rect::new(32., 32., 96., 96.);
|
||
|
||
// Shown only over backdrops at least half red
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.underlying.red = blend_range([128., 128., 255., 255.]);
|
||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||
let box_blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 1.,
|
||
box_blur: true,
|
||
gamma: false,
|
||
};
|
||
|
||
// Content stretched or sheared since its Blend If was stamped, and turned content with a box blur, each rendered along its effect space's axes
|
||
let stretched = DAffine2::from_scale(DVec2::new(2., 1.));
|
||
let sheared = DAffine2::from_mat2(DMat2::from_cols(DVec2::X, DVec2::new(0.5, 1.)));
|
||
let turned = DAffine2::from_angle(30_f64.to_radians());
|
||
let cases = [
|
||
("stretched", stretched, vec![blend_if.clone()]),
|
||
("sheared", sheared, vec![blend_if.clone()]),
|
||
("turned", turned, vec![blend_if, box_blur]),
|
||
];
|
||
|
||
// A color in each quarter of the render, beneath a black square covering part of each
|
||
let (green, white, black) = (Color::from_rgb8(0, 255, 0), Color::from_rgb8(255, 255, 255), Color::from_rgb8(0, 0, 0));
|
||
let quarters = [(0., 0., RED), (64., 0., green), (0., 64., BLUE), (64., 64., white)];
|
||
|
||
for (name, effect_space, operations) in cases {
|
||
let effects = Effects::from_operations(operations);
|
||
let draw = |scene: &mut VelloSceneBuilder| {
|
||
for (x, y, color) in quarters {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, color, None, &Rect::new(x, y, x + 64., y + 64.));
|
||
}
|
||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), effect_space, None, &mut |_, _| {}, &mut |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, black, None, &square)
|
||
});
|
||
};
|
||
let Some(pixels) = render(size, draw) else { return };
|
||
|
||
// The square shows over the red and white quarters and hides over the others, near the borders between them and near the square's corners
|
||
let expected = [
|
||
(54, 54, [0, 0, 0]),
|
||
(74, 54, [0, 255, 0]),
|
||
(54, 74, [0, 0, 255]),
|
||
(74, 74, [0, 0, 0]),
|
||
(38, 38, [0, 0, 0]),
|
||
(90, 38, [0, 255, 0]),
|
||
(38, 90, [0, 0, 255]),
|
||
(90, 90, [0, 0, 0]),
|
||
];
|
||
for (x, y, expected) in expected {
|
||
let [red, green, blue, alpha] = pixel(&pixels, size, x, y);
|
||
let close = [red, green, blue].iter().zip(expected).all(|(&channel, expected)| channel.abs_diff(expected) <= 2);
|
||
assert!(close && alpha == 255, "{name} content at ({x}, {y}): {:?} against {expected:?}", pixel(&pixels, size, x, y));
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_stamped_before_a_transform_fade_everything_the_content_draws_by_what_lies_beneath() {
|
||
use core_types::ATTR_TRANSFORM;
|
||
use core_types::list::{Item, List};
|
||
use glam::DVec2;
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// Black to the left of x = 64 and white to the right
|
||
let image = |color: core_types::Color, min: DVec2, size: DVec2| {
|
||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(min) * DAffine2::from_scale(size))
|
||
};
|
||
let mut images = List::new_from_item(image(core_types::Color::BLACK, DVec2::ZERO, DVec2::new(64., 128.)));
|
||
images.push(image(core_types::Color::WHITE, DVec2::new(64., 0.), DVec2::new(64., 128.)));
|
||
|
||
// Then a red square straddling the border, shown only over light backdrops by a Blend If stamped before the square was scaled up and given a blue shadow
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.underlying.gray = blend_range([128., 128., 255., 255.]);
|
||
let mut square = image(core_types::Color::RED, DVec2::splat(48.), DVec2::splat(16.));
|
||
stamp_effect(&mut square, Effect::new(&EffectOperation::BlendIf(Box::new(ranges))));
|
||
square.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(32.)) * DAffine2::from_scale(DVec2::splat(64.)));
|
||
stamp_effect(&mut square, Effect::new(&drop_shadow(core_types::Color::BLUE, DVec2::new(0., 16.), 0., 100.)));
|
||
images.push(square);
|
||
let graphic = Graphic::RasterCPUList(images);
|
||
|
||
let size = UVec2::new(128, 128);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
|
||
assert_eq!(pixel(&pixels, size, 40, 64), [0, 0, 0, 255], "over black, the content is hidden");
|
||
assert_eq!(pixel(&pixels, size, 88, 64), [255, 0, 0, 255], "over white, it shows");
|
||
assert_eq!(pixel(&pixels, size, 40, 104), [0, 0, 0, 255], "its shadow is hidden over black too");
|
||
assert_eq!(pixel(&pixels, size, 88, 104), [0, 0, 255, 255], "and shows over white");
|
||
}
|
||
|
||
/// A Blend If row hiding the content where its own gray is darker than half, cut off sharply.
|
||
fn blend_if_hiding_darks() -> graphic_types::EffectOperation {
|
||
let mut ranges = graphic_types::blend_if::BlendIfRanges::default();
|
||
(ranges.content.gray.falloff_start, ranges.content.gray.range_start) = (50., 50.);
|
||
graphic_types::EffectOperation::BlendIf(Box::new(ranges))
|
||
}
|
||
|
||
/// A mask of a 50 by 50 image without a placement, so it's fitted to the content, showing all but its bottom 10 rows.
|
||
fn mask_hiding_the_bottom_fifth() -> graphic_types::EffectOperation {
|
||
use core_types::list::Item;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{EffectOperation, Graphic, MaskMode};
|
||
|
||
let data = (0..50 * 50).map(|index| if index / 50 < 40 { core_types::Color::WHITE } else { core_types::Color::BLACK }).collect();
|
||
EffectOperation::Mask {
|
||
mask: Graphic::from(Item::new_from_element(Raster::new_cpu(Image { width: 50, height: 50, data }))),
|
||
mode: MaskMode::Luminance,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn flattened_glows_before_a_mask_hide_where_a_blend_if_after_it_hides_the_content() {
|
||
use core_types::list::Item;
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
|
||
// A glow in a mode CSS lacks, which flattens it into the content's image
|
||
let glow = EffectOperation::OuterGlow {
|
||
color: GraphicColor::from_gamma_srgb_channels(1., 0.8, 0.3, 1.).into(),
|
||
blend_mode: BlendMode::LinearDodge,
|
||
technique: Default::default(),
|
||
spread: 50.,
|
||
size: 6.,
|
||
range: 50.,
|
||
contour: Default::default(),
|
||
noise: 0.,
|
||
jitter: 0.,
|
||
seed: 0,
|
||
};
|
||
let (mask, blend_if) = (mask_hiding_the_bottom_fifth(), blend_if_hiding_darks());
|
||
|
||
// A 50 by 50 raster at (55, 55), dark on its left half and light on its right
|
||
let (dark, light) = (40, 220);
|
||
let raster = |effects: &[EffectOperation]| {
|
||
let level = |index: u32| if index % 50 < 25 { dark } else { light };
|
||
let data = (0..50 * 50)
|
||
.map(|index| GraphicColor::from(core_types::color::SRGBA8::new(level(index), level(index), level(index), 255)))
|
||
.collect();
|
||
let placement = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 50, height: 50, data })).with_attribute(ATTR_TRANSFORM, placement);
|
||
effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
item
|
||
};
|
||
|
||
// After the mask or before it, the Blend If hides the glow beneath the dark half along with the content
|
||
let size = UVec2::splat(160);
|
||
for operations in [[glow.clone(), mask.clone(), blend_if.clone()], [glow.clone(), blend_if.clone(), mask.clone()]] {
|
||
let kinds: Vec<_> = operations.iter().map(|operation| operation.kind()).collect();
|
||
let item = raster(&operations);
|
||
|
||
let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return };
|
||
assert!(worst <= 2, "{kinds:?} differs between the CPU and GPU by up to {worst} levels");
|
||
|
||
let graphic = Graphic::RasterCPU(Box::new(item));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 65, 70)[3], 0, "{kinds:?}: the glow hides with the dark half: {:?}", pixel(&pixels, size, 65, 70));
|
||
assert_eq!(pixel(&pixels, size, 95, 70), [light, light, light, 255], "{kinds:?}: the light half shows");
|
||
assert_eq!(pixel(&pixels, size, 95, 100)[3], 0, "{kinds:?}: the mask hides the bottom");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn color_overlays_before_a_mask_paint_the_colors_a_blend_if_after_it_reads_on_every_kind_of_content() {
|
||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Appearance, Coverage, Effect, Effects, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
// White content painted blue, which Blend If hides as darker than half, and masked between the two
|
||
let operations = [color_overlay([0., 0., 1.], BlendMode::Normal, 1.), mask_hiding_the_bottom_fifth(), blend_if_hiding_darks()];
|
||
let size = UVec2::splat(160);
|
||
|
||
// A 50 by 50 white raster at (55, 55), compared with its CPU evaluation
|
||
let placement = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
let mut raster = Item::new_from_element(Raster::new_cpu(Image::new(50, 50, GraphicColor::WHITE))).with_attribute(ATTR_TRANSFORM, placement);
|
||
operations.iter().for_each(|operation| stamp_effect(&mut raster, Effect::new(operation)));
|
||
let Some(worst) = gpu_and_cpu_difference(raster.clone(), size) else { return };
|
||
assert!(worst <= 2, "the raster differs between the CPU and GPU by up to {worst} levels");
|
||
|
||
// The same square as a vector with a solid fill, which takes the overlay into its paint, and in a group carrying the effects, which takes it as a piece
|
||
let mut vector = Vector::item_from_bezpath(&Rect::new(55., 55., 105., 105.).to_path(0.1));
|
||
vector.set_attribute(
|
||
ATTR_APPEARANCE,
|
||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
|
||
);
|
||
let effects = Effects::from_operations(operations);
|
||
let group = Item::new_from_element(Graphic::VectorList(List::new_from_item(vector.clone()))).with_attribute(ATTR_EFFECTS, effects.clone());
|
||
let contents = [
|
||
("raster", Graphic::RasterCPU(Box::new(raster))),
|
||
("vector", Graphic::Vector(Box::new(vector.with_attribute(ATTR_EFFECTS, effects)))),
|
||
("group", Graphic::Graphic(Box::new(group))),
|
||
];
|
||
|
||
for (name, graphic) in contents {
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
for (x, y) in [(60, 60), (80, 80), (100, 90)] {
|
||
assert_eq!(pixel(&pixels, size, x, y)[3], 0, "the {name} painted blue is hidden at ({x}, {y}): {:?}", pixel(&pixels, size, x, y));
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn clipping_bases_clip_alike_with_a_blend_if_before_or_after_their_mask() {
|
||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||
use core_types::{ATTR_CLIPPING_MASK, Color as GraphicColor};
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, MaskMode, Vector};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let square = |color: GraphicColor, rect: Rect| {
|
||
let mut item = Vector::item_from_bezpath(&rect.to_path(0.1));
|
||
item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))));
|
||
item
|
||
};
|
||
let mask = EffectOperation::Mask {
|
||
mask: Graphic::Vector(Box::new(square(GraphicColor::WHITE, Rect::new(30., 30., 90., 60.)))),
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
|
||
// Over black, a base dark on its left half and light on its right, masked to its top half, with a red square of the same size clipped to it
|
||
let clipped_scene = |operations: &[EffectOperation]| {
|
||
let dark = GraphicColor::from_gamma_srgb_channels(0.15, 0.15, 0.15, 1.);
|
||
let halves: List<Vector> = [square(dark, Rect::new(30., 30., 60., 90.)), square(GraphicColor::WHITE, Rect::new(60., 30., 90., 90.))]
|
||
.into_iter()
|
||
.collect();
|
||
let base = Item::new_from_element(Graphic::VectorList(halves)).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations.to_vec()));
|
||
|
||
let backdrop = Item::new_from_element(Graphic::Vector(Box::new(square(GraphicColor::BLACK, Rect::new(0., 0., 120., 120.)))));
|
||
let clipped = square(GraphicColor::RED, Rect::new(30., 30., 90., 90.)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
Graphic::GraphicList([backdrop, base, Item::new_from_element(Graphic::Vector(Box::new(clipped)))].into_iter().collect())
|
||
};
|
||
|
||
// Hiding the base by its own darks, or by the black beneath it, a Blend If shapes no clip in either order
|
||
let mut beneath = BlendIfRanges::default();
|
||
beneath.underlying.gray.range_start = 50.;
|
||
let blend_ifs = [("content", blend_if_hiding_darks()), ("underlying", EffectOperation::BlendIf(Box::new(beneath)))];
|
||
for (side, blend_if) in blend_ifs {
|
||
let orders = [("before", [blend_if.clone(), mask.clone()]), ("after", [mask.clone(), blend_if.clone()])];
|
||
|
||
// In SVG, the clip's mask leaves out the Blend If, so only the base's own render weighs the gray
|
||
let gray_weights = orders.clone().map(|(_, operations)| {
|
||
let mut render = SvgRender::new();
|
||
clipped_scene(&operations).render_svg(
|
||
&mut render,
|
||
&RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
},
|
||
);
|
||
render.svg_defs.matches(r#"values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0.0000196"#).count()
|
||
});
|
||
assert_eq!(gray_weights, [1, 1], "the {side} Blend If's gray weights in SVG, before the mask and after it");
|
||
|
||
for (order, operations) in orders {
|
||
let graphic = clipped_scene(&operations);
|
||
let size = UVec2::splat(120);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
for (x, y) in [(40, 45), (80, 45)] {
|
||
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "{side} Blend If {order} the mask: the clipped square shows at ({x}, {y})");
|
||
}
|
||
for (x, y) in [(40, 75), (80, 75)] {
|
||
assert_eq!(
|
||
pixel(&pixels, size, x, y),
|
||
[0, 0, 0, 255],
|
||
"{side} Blend If {order} the mask: the mask hides the clipped square at ({x}, {y})"
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_beneath_within_a_group_clipping_base_shape_no_clip() {
|
||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY, Color as GraphicColor};
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, MaskMode, Vector};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let square = |color: GraphicColor, rect: Rect| {
|
||
let mut item = Vector::item_from_bezpath(&rect.to_path(0.1));
|
||
item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))));
|
||
item
|
||
};
|
||
let mask = EffectOperation::Mask {
|
||
mask: Graphic::Vector(Box::new(square(GraphicColor::WHITE, Rect::new(30., 30., 90., 60.)))),
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
|
||
// Hiding the content where what lies beneath it is lighter than a level of 64
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.underlying.gray = blend_range([0., 0., 64., 64.]);
|
||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||
|
||
// Also hiding the content's own grays lighter than a level of 200, before a blur merging it into the content's image, so it stays in the clip
|
||
let mut both_sides = ranges;
|
||
both_sides.content.gray = blend_range([0., 0., 200., 200.]);
|
||
let blur = EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius: 2.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
|
||
// Over black, a group of a white square at half opacity and a gray one over it taking the effects, with a red square of the same size clipped to the group
|
||
let clipped_scene = |operations: [EffectOperation; 2]| {
|
||
let half_white = Item::new_from_element(Graphic::Vector(Box::new(square(GraphicColor::WHITE, Rect::new(30., 30., 90., 90.))))).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||
let gray = square(GraphicColor::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.), Rect::new(30., 30., 90., 90.)).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations));
|
||
let base = Item::new_from_element(Graphic::GraphicList([half_white, Item::new_from_element(Graphic::Vector(Box::new(gray)))].into_iter().collect()));
|
||
|
||
let backdrop = Item::new_from_element(Graphic::Vector(Box::new(square(GraphicColor::BLACK, Rect::new(0., 0., 120., 120.)))));
|
||
let clipped = square(GraphicColor::RED, Rect::new(30., 30., 90., 90.)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
Graphic::GraphicList([backdrop, base, Item::new_from_element(Graphic::Vector(Box::new(clipped)))].into_iter().collect())
|
||
};
|
||
|
||
let cases = [
|
||
("before the mask", [blend_if.clone(), mask.clone()]),
|
||
("after the mask", [mask.clone(), blend_if]),
|
||
("reading both sides before a blur", [EffectOperation::BlendIf(Box::new(both_sides)), blur]),
|
||
];
|
||
for (case, operations) in cases {
|
||
// In SVG, only the base's own render copies what lies beneath the gray, so the clip draws the gray whole as Vello's does
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
clipped_scene(operations.clone()).render_svg(&mut svg, &export);
|
||
let copies = svg.svg_defs.matches(r#"<mask id="blend-if-mask-"#).count();
|
||
assert_eq!(copies, 1, "with the Blend If {case}, SVG copies what lies beneath the gray {copies} times");
|
||
|
||
// In the top half, where the white lies beneath the gray, the clip is opaque
|
||
let graphic = clipped_scene(operations);
|
||
let size = UVec2::splat(120);
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
continue;
|
||
};
|
||
for (x, y) in [(40, 45), (80, 45)] {
|
||
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "with the Blend If {case}, the clipped square shows at ({x}, {y})");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn blend_ifs_in_a_clip_read_what_lies_beneath_them_only_inside_an_offscreen_render() {
|
||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY, Color as GraphicColor};
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::{Appearance, Coverage, Effect, EffectOperation, Effects, Graphic, MaskMode, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
let square = |color: GraphicColor, rect: Rect| {
|
||
let mut item = Vector::item_from_bezpath(&rect.to_path(0.1));
|
||
item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color))));
|
||
item
|
||
};
|
||
let blur = |radius: f64| EffectOperation::Blur {
|
||
radius_mask: Default::default(),
|
||
radius,
|
||
box_blur: false,
|
||
gamma: false,
|
||
};
|
||
|
||
// A white square at half opacity, then a gray one over it with a Blend If reading both sides before a blur that keeps it in a clip, or the same without the Blend If
|
||
let squares = |with_blend_if: bool| {
|
||
let mut ranges = BlendIfRanges::default();
|
||
ranges.underlying.gray = blend_range([0., 0., 64., 64.]);
|
||
ranges.content.gray = blend_range([0., 0., 200., 200.]);
|
||
let operations = match with_blend_if {
|
||
true => vec![EffectOperation::BlendIf(Box::new(ranges)), blur(2.)],
|
||
false => vec![blur(2.)],
|
||
};
|
||
|
||
let content = Rect::new(16., 16., 48., 48.);
|
||
let half_white = Item::new_from_element(Graphic::Vector(Box::new(square(GraphicColor::WHITE, content)))).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||
let gray = square(GraphicColor::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.), content).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations));
|
||
Graphic::GraphicList([half_white, Item::new_from_element(Graphic::Vector(Box::new(gray)))].into_iter().collect())
|
||
};
|
||
|
||
// The squares as the clipping base itself, then nested in a render of their own inside it: of a group with an effect kept in the clip, of a faded group, and of a mask's graphic
|
||
let bases = |with_blend_if: bool| {
|
||
let mut masked = square(GraphicColor::WHITE, Rect::new(0., 0., 64., 64.));
|
||
let mask = EffectOperation::Mask {
|
||
mask: squares(with_blend_if),
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
stamp_effect(&mut masked, Effect::new(&mask));
|
||
let faded = Item::new_from_element(squares(with_blend_if)).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||
|
||
[
|
||
("directly", Item::new_from_element(squares(with_blend_if))),
|
||
(
|
||
"in a group with a blur",
|
||
Item::new_from_element(squares(with_blend_if)).with_attribute(ATTR_EFFECTS, Effects::from_operations([blur(1.)])),
|
||
),
|
||
("in a faded group", Item::new_from_element(Graphic::GraphicList(List::new_from_item(faded)))),
|
||
("in a mask's graphic", Item::new_from_element(Graphic::Vector(Box::new(masked)))),
|
||
]
|
||
};
|
||
|
||
// The base is hidden by its opacity, which its clip doesn't take, so a red square clipped to it shows only as much as the clip covers
|
||
let clipped_scene = |base: Item<Graphic>| {
|
||
let red = square(GraphicColor::RED, Rect::new(0., 0., 64., 64.)).with_attribute(ATTR_CLIPPING_MASK, true);
|
||
let clipped = Item::new_from_element(Graphic::Vector(Box::new(red)));
|
||
Graphic::GraphicList([base.with_attribute(ATTR_OPACITY, 0_f64), clipped].into_iter().collect())
|
||
};
|
||
|
||
let size = UVec2::splat(64);
|
||
for ((case, base), (_, base_without_blend_if)) in bases(true).into_iter().zip(bases(false)) {
|
||
let nested = case != "directly";
|
||
|
||
// In SVG, the gray copies what lies beneath it where the base is drawn, and in the clip only where it's nested
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
clipped_scene(base.clone()).render_svg(&mut svg, &export);
|
||
let copies = svg.svg_defs.matches(r#"<mask id="blend-if-mask-"#).count();
|
||
assert_eq!(copies, 1 + nested as usize, "with the gray {case}, SVG copies what lies beneath it {copies} times");
|
||
|
||
// On the GPU, the half-white beneath the gray hides half of it where it's read
|
||
let clip_coverage = |base: Item<Graphic>| {
|
||
let graphic = clipped_scene(base);
|
||
render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())).map(|pixels| pixel(&pixels, size, 32, 32)[3])
|
||
};
|
||
let (Some(with_blend_if), Some(without_blend_if)) = (clip_coverage(base), clip_coverage(base_without_blend_if)) else {
|
||
continue;
|
||
};
|
||
let message = format!("with the gray {case}, the GPU's clip covers {with_blend_if} with its Blend If and {without_blend_if} without it");
|
||
match nested {
|
||
true => assert!(with_blend_if <= without_blend_if - 16, "{message}"),
|
||
false => assert!(with_blend_if.abs_diff(without_blend_if) <= 1, "{message}"),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Blend If's content ranges showing only grays of at least half.
|
||
fn blend_if_hiding_below_half() -> graphic_types::EffectOperation {
|
||
let mut ranges = graphic_types::blend_if::BlendIfRanges::default();
|
||
ranges.content.gray = blend_range([127.5, 127.5, 255., 255.]);
|
||
graphic_types::EffectOperation::BlendIf(Box::new(ranges))
|
||
}
|
||
|
||
/// A gradient from black to white, carrying `effects`.
|
||
fn black_to_white_gradient(effects: &[graphic_types::EffectOperation]) -> core_types::list::Item<graphic_types::vector_types::gradient::Gradient> {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use graphic_types::vector_types::gradient::Gradient;
|
||
|
||
let mut gradient = Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE]));
|
||
effects.iter().for_each(|operation| graphic_types::stamp_effect(&mut gradient, graphic_types::Effect::new(operation)));
|
||
gradient
|
||
}
|
||
|
||
#[test]
|
||
fn masked_radius_blurs_after_a_blend_if_blur_the_full_strength_content_alike_on_the_cpu_gpu_and_svg() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::Adjustment;
|
||
use graphic_types::effects::EffectCapture;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
// A black square hidden by a Blend If, blurred by a ramp, then painted red, which paints within the blurred square as through a fill of none
|
||
let operations = [
|
||
blend_if_hiding_below_half(),
|
||
EffectOperation::Blur {
|
||
radius_mask: Graphic::from(black_to_white_gradient(&[])),
|
||
radius: 8.,
|
||
box_blur: false,
|
||
gamma: false,
|
||
},
|
||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||
color: GraphicColor::RED,
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
}),
|
||
];
|
||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(40, 40, GraphicColor::BLACK)))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(24.)) * DAffine2::from_scale(DVec2::splat(40.)));
|
||
operations.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation)));
|
||
|
||
let size = UVec2::new(88, 88);
|
||
let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return };
|
||
assert!(worst <= 3, "the CPU and GPU differ by up to {worst} levels");
|
||
let graphic = Graphic::RasterCPU(Box::new(item.clone()));
|
||
let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&gpu, size, 44, 44), [255, 0, 0, 255], "the GPU paints the hidden square red");
|
||
|
||
// SVG takes both of the blur's results from the GPU as maps, rather than starting a fresh filter from the faded content alone
|
||
let mut svg = SvgRender::new();
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
..Default::default()
|
||
};
|
||
List::new_from_item(item).render_svg(&mut svg, &export);
|
||
assert!(!svg.svg_defs.contains("feGaussianBlur"), "{}", svg.svg_defs);
|
||
let map_of = |plane: usize| svg.effect_maps.iter().find(|map| map.capture == EffectCapture { index: 1, plane });
|
||
let (Some(full), Some(faded)) = (map_of(1), map_of(2)) else {
|
||
panic!("SVG takes no maps of the blur's results: {}", svg.svg_defs);
|
||
};
|
||
|
||
// The full-strength result covers the square the overlay paints within, and the faded one is empty, as on the GPU
|
||
let Some(executor) = executor() else { return };
|
||
let alpha_at_middle = |map: &rendering::deferred_image::EffectMap| {
|
||
let layout = map.layout(DAffine2::IDENTITY, size.as_dvec2(), 4096).expect("the map is in view");
|
||
let _turn = take_turn();
|
||
let texture = executor
|
||
.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout))
|
||
.expect("the map renders");
|
||
let pixels = executor.read_texture_pixels(&texture).expect("the map reads back");
|
||
let texel = layout.document_to_pixels.transform_point2(DVec2::splat(44.)).floor().as_uvec2();
|
||
pixels[((texel.y * layout.size.x + texel.x) * 4 + 3) as usize]
|
||
};
|
||
assert_eq!(alpha_at_middle(full), 255, "the full-strength result covers the middle");
|
||
assert_eq!(alpha_at_middle(faded), 0, "the faded result is empty there");
|
||
}
|
||
|
||
#[test]
|
||
fn color_and_gradient_paints_fade_by_their_own_blend_ifs_on_the_gpu() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::{ATTR_APPEARANCE, Item};
|
||
use graphic_types::{Appearance, Coverage, Effect, Graphic, Vector, stamp_effect};
|
||
use rendering::{Render, RenderParams};
|
||
use vello_gpu::kurbo::Shape;
|
||
|
||
// A square over white filled with black, which the Blend If hides, and with a ramp, which it hides up to its middle gray
|
||
let mut black = Item::new_from_element(GraphicColor::BLACK);
|
||
stamp_effect(&mut black, Effect::new(&blend_if_hiding_below_half()));
|
||
let filled_square = |paint: Graphic| {
|
||
let mut square = Vector::item_from_bezpath(&Rect::new(8., 8., 56., 56.).to_path(0.01));
|
||
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), paint));
|
||
Graphic::Vector(Box::new(square))
|
||
};
|
||
let size = UVec2::new(64, 64);
|
||
let render_over_white = |paint: Graphic| {
|
||
let square = filled_square(paint);
|
||
render(size, |scene| {
|
||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &Rect::new(0., 0., 64., 64.));
|
||
square.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||
})
|
||
};
|
||
|
||
let Some(hidden) = render_over_white(Graphic::Color(black)) else { return };
|
||
assert_eq!(pixel(&hidden, size, 32, 32), [255, 255, 255, 255], "the black fill is hidden");
|
||
|
||
// The ramp runs across the square, where its dark end shows without the Blend If
|
||
let across_square = DAffine2::from_translation(glam::DVec2::new(8., 0.)) * DAffine2::from_scale(glam::DVec2::splat(48.));
|
||
let ramp = |effects: &[graphic_types::EffectOperation]| Graphic::from(black_to_white_gradient(effects).with_attribute(core_types::ATTR_TRANSFORM, across_square));
|
||
let (Some(shown), Some(faded)) = (render_over_white(ramp(&[])), render_over_white(ramp(&[blend_if_hiding_below_half()]))) else {
|
||
return;
|
||
};
|
||
assert!(pixel(&shown, size, 12, 32)[0] <= 32, "without the Blend If, the dark end shows: {:?}", pixel(&shown, size, 12, 32));
|
||
assert_eq!(pixel(&faded, size, 12, 32), [255, 255, 255, 255], "the dark end of the ramp is hidden");
|
||
let light_end = pixel(&faded, size, 52, 32);
|
||
assert!(light_end[0] >= 200 && light_end[3] == 255, "the light end shows: {light_end:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn effect_paints_and_maps_fade_by_their_own_blend_ifs_on_the_cpu_like_on_the_gpu() {
|
||
use core_types::Color as GraphicColor;
|
||
use core_types::list::Item;
|
||
use graphic_types::vector_types::GradientSpread;
|
||
use graphic_types::{Effect, EffectOperation, Graphic, MaskMode, stamp_effect};
|
||
|
||
// A dark gray hidden by the Blend If, and a ramp hidden up to its middle gray
|
||
let mut hidden_gray = Item::new_from_element(GraphicColor::from_gamma_srgb_channels(0.3, 0.3, 0.3, 1.));
|
||
stamp_effect(&mut hidden_gray, Effect::new(&blend_if_hiding_below_half()));
|
||
let hidden_gray = Graphic::from(hidden_gray);
|
||
let ramp = Graphic::from(black_to_white_gradient(&[blend_if_hiding_below_half()]));
|
||
// Paints and maps that don't follow the content lie where they're placed, so this ramp is placed across it
|
||
let on_content = DAffine2::from_translation(glam::DVec2::splat(55.)) * DAffine2::from_scale(glam::DVec2::splat(50.));
|
||
let placed_ramp = Graphic::from(black_to_white_gradient(&[blend_if_hiding_below_half()]).with_attribute(core_types::ATTR_TRANSFORM, on_content));
|
||
|
||
let mask = |mask: Graphic, mode: MaskMode| EffectOperation::Mask {
|
||
mask,
|
||
mode,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
// The map moves the content across and down by its luminance
|
||
let displace = |map: Graphic| x_and_y_displacement((map.clone(), 25.6), (map, 12.8), GradientSpread::Repeat);
|
||
let cases = [
|
||
("color mask", mask(hidden_gray.clone(), MaskMode::Alpha)),
|
||
("gradient mask", mask(ramp, MaskMode::Alpha)),
|
||
(
|
||
"gradient paint overlay",
|
||
EffectOperation::PaintOverlay {
|
||
paint: placed_ramp.clone(),
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
},
|
||
),
|
||
("color displacement map", displace(hidden_gray)),
|
||
("gradient displacement map", displace(placed_ramp)),
|
||
];
|
||
|
||
let size = UVec2::new(160, 160);
|
||
for (name, operation) in cases {
|
||
let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[operation]), size) else { return };
|
||
assert!(worst <= 3, "the {name} differs between the CPU and GPU by up to {worst} levels");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn endless_layers_given_edges_by_a_mask_read_nothing_beneath_them_on_the_gpu_or_in_svg() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::Adjustment;
|
||
use graphic_types::blend_if::BlendIfRanges;
|
||
use graphic_types::generator::Generator;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::vector_types::gradient::Gradient;
|
||
use graphic_types::{Effect, EffectOperation, Graphic, MaskMode, stamp_effect};
|
||
use rendering::{Render, RenderParams, SvgRender};
|
||
|
||
// A red color, a red ramp, and noise masked to a square over opaque black, with a Blend If hiding them over grays darker than half
|
||
let square = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, GraphicColor::WHITE)))
|
||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(16.)) * DAffine2::from_scale(DVec2::splat(32.)));
|
||
let mask = EffectOperation::Mask {
|
||
mask: Graphic::from(square),
|
||
mode: MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
let mut ranges = BlendIfRanges::default();
|
||
(ranges.underlying.gray.falloff_start, ranges.underlying.gray.range_start) = (50., 50.);
|
||
let over_black = |operations: &[EffectOperation]| {
|
||
let mut color = Item::new_from_element(GraphicColor::RED);
|
||
let mut ramp = Item::new_from_element(Gradient::from(vec![GraphicColor::RED, GraphicColor::RED]));
|
||
let mut generator = Item::new_from_element(Generator::Noise);
|
||
for operation in operations {
|
||
stamp_effect(&mut color, Effect::new(operation));
|
||
stamp_effect(&mut ramp, Effect::new(operation));
|
||
stamp_effect(&mut generator, Effect::new(operation));
|
||
}
|
||
[("color", Graphic::from(color)), ("gradient", Graphic::from(ramp)), ("generator", Graphic::from(generator))].map(|(name, layer)| {
|
||
let black = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, GraphicColor::BLACK))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
|
||
let mut list = List::new_from_element(Graphic::from(black));
|
||
list.push(Item::new_from_element(layer));
|
||
(name, list)
|
||
})
|
||
};
|
||
|
||
// SVG draws the noise as an image of the area in view
|
||
let export = RenderParams {
|
||
for_export: true,
|
||
view: Some(core_types::transform::Footprint {
|
||
resolution: UVec2::splat(64),
|
||
..Default::default()
|
||
}),
|
||
..Default::default()
|
||
};
|
||
|
||
// Without bounds of its own, the content reads nothing beneath it in SVG's filters, nor in the image the GPU renders of it where no SVG filter carries out its effects
|
||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||
let desaturate = EffectOperation::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: -100. });
|
||
for (name, list) in over_black(&[mask.clone(), blend_if.clone()]) {
|
||
let mut svg = SvgRender::new();
|
||
list.render_svg(&mut svg, &export);
|
||
assert!(!svg.svg_defs.contains("blend-if-mask-"), "SVG fades the {name} by what lies beneath: {}", svg.svg_defs);
|
||
}
|
||
for (name, list) in over_black(&[mask.clone(), blend_if.clone(), desaturate]) {
|
||
let mut svg = SvgRender::new();
|
||
list.render_svg(&mut svg, &export);
|
||
let [deferred] = &svg.deferred_images[..] else {
|
||
panic!("the {name} isn't deferred: {}", svg.svg_defs);
|
||
};
|
||
assert!(
|
||
deferred.mask.is_none() && !svg.svg_defs.contains("blend-if-mask-"),
|
||
"SVG fades the {name}'s image by what lies beneath: {}",
|
||
svg.svg_defs
|
||
);
|
||
}
|
||
|
||
// So nothing hides the red layers, as on the GPU
|
||
let size = UVec2::new(64, 64);
|
||
let [color, gradient, _] = over_black(&[mask, blend_if]);
|
||
for (name, list) in [color, gradient] {
|
||
let Some(pixels) = render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&pixels, size, 32, 32), [255, 0, 0, 255], "the GPU shows the masked {name}");
|
||
assert_eq!(pixel(&pixels, size, 8, 8), [0, 0, 0, 255], "the GPU masks the {name}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_them_on_the_gpu_like_on_the_cpu() {
|
||
use core_types::list::{Item, List};
|
||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||
use glam::DVec2;
|
||
use graphic_types::adjustment::Adjustment;
|
||
use graphic_types::raster_types::{Image, Raster};
|
||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||
use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||
|
||
// White, or a ramp from black to white, painted blue and then scaled up, where a Blend If hiding grays below half reads the blue and hides it
|
||
let blue = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||
color: GraphicColor::BLUE,
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
});
|
||
|
||
// Each row is stamped while the item is scaled from its `placement` by the row's scale, so the ramp lies across the render
|
||
fn stamped<T>(mut item: Item<T>, placement: DAffine2, rows: &[(&EffectOperation, f64)]) -> Item<T> {
|
||
for (operation, scale) in rows {
|
||
item.set_attribute(ATTR_TRANSFORM, placement * DAffine2::from_scale(DVec2::splat(*scale)));
|
||
stamp_effect(&mut item, Effect::new(operation));
|
||
}
|
||
item
|
||
}
|
||
let blend_if = blend_if_hiding_below_half();
|
||
let layers = |scale: f64| {
|
||
let rows = [(&blue, 1.), (&blend_if, scale)];
|
||
let across = DAffine2::from_scale(DVec2::splat(32.));
|
||
[
|
||
("color", Graphic::from(stamped(Item::new_from_element(GraphicColor::WHITE), across, &rows))),
|
||
("gradient", Graphic::from(stamped(black_to_white_gradient(&[]), across, &rows))),
|
||
]
|
||
};
|
||
|
||
// SVG carries out the scaled layers' effects in filters over the area in view, rather than on their paints
|
||
let in_view = RenderParams {
|
||
view: Some(core_types::transform::Footprint {
|
||
resolution: UVec2::splat(32),
|
||
..Default::default()
|
||
}),
|
||
..Default::default()
|
||
};
|
||
for (name, scaled) in layers(2.) {
|
||
let mut svg = SvgRender::new();
|
||
List::new_from_element(scaled).render_svg(&mut svg, &in_view);
|
||
assert!(
|
||
svg.svg_defs.contains(r#"<filter id="effects-"#),
|
||
"SVG draws the scaled {name} without filters: {}",
|
||
svg.svg.to_svg_string()
|
||
);
|
||
}
|
||
|
||
// Over red, the scaled layers are hidden, while in one run the Blend If reads the content beneath the overlay, which paints over what it hides
|
||
let size = UVec2::new(32, 32);
|
||
let render_over_red = |layer: &Graphic| {
|
||
let red = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, GraphicColor::RED))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(32.)));
|
||
let mut list = List::new_from_element(Graphic::from(red));
|
||
list.push(Item::new_from_element(layer.clone()));
|
||
render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||
};
|
||
for ((name, scaled), (_, unscaled)) in layers(2.).into_iter().zip(layers(1.)) {
|
||
let (Some(scaled_pixels), Some(unscaled_pixels)) = (render_over_red(&scaled), render_over_red(&unscaled)) else {
|
||
return;
|
||
};
|
||
assert_eq!(pixel(&scaled_pixels, size, 16, 16), [255, 0, 0, 255], "the scaled {name} is hidden");
|
||
assert_eq!(pixel(&unscaled_pixels, size, 16, 16), [0, 0, 255, 255], "the {name} in one run is painted blue");
|
||
}
|
||
|
||
// As a mask, it hides everything, and as a paint overlay's paint, it paints nothing, which the CPU reads alike
|
||
let [(_, color), (_, gradient)] = layers(2.);
|
||
let mask = |mask: Graphic| EffectOperation::Mask {
|
||
mask,
|
||
mode: graphic_types::MaskMode::Alpha,
|
||
density: 100.,
|
||
feather: 0.,
|
||
invert: false,
|
||
};
|
||
let cases = [
|
||
("color mask", mask(color), 0),
|
||
("gradient mask", mask(gradient.clone()), 0),
|
||
(
|
||
"gradient paint overlay",
|
||
EffectOperation::PaintOverlay {
|
||
paint: gradient,
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 100.,
|
||
},
|
||
255,
|
||
),
|
||
];
|
||
let size = UVec2::new(160, 160);
|
||
for (name, operation, alpha) in cases {
|
||
let raster = checkered_raster(&[operation]);
|
||
let Some(worst) = gpu_and_cpu_difference(raster.clone(), size) else { return };
|
||
assert!(worst <= 3, "the {name} differs between the CPU and GPU by up to {worst} levels");
|
||
|
||
let graphic = Graphic::RasterCPU(Box::new(raster));
|
||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||
return;
|
||
};
|
||
let [_, _, blue, shown] = pixel(&pixels, size, 80, 80);
|
||
assert!(shown == alpha && blue < 255, "the {name} paints blue or doesn't hide: {:?}", pixel(&pixels, size, 80, 80));
|
||
}
|
||
|
||
// At half fill, half of the overlay paints over the faded white, and the next run's softer Blend If reads that mix, which shows about a third of it
|
||
let mut soft = graphic_types::blend_if::BlendIfRanges::default();
|
||
soft.content.gray = blend_range([63.75, 191.25, 255., 255.]);
|
||
let half_blue = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||
color: GraphicColor::BLUE,
|
||
blend_mode: BlendMode::Normal,
|
||
opacity: 50.,
|
||
});
|
||
let rows = [(&half_blue, 1.), (&EffectOperation::BlendIf(Box::new(soft)), 2.)];
|
||
let half_filled = stamped(Item::new_from_element(GraphicColor::WHITE), DAffine2::IDENTITY, &rows).with_attribute(core_types::ATTR_OPACITY_FILL, 0.5);
|
||
let Some(worst) = gpu_and_cpu_difference(checkered_raster(&[mask(Graphic::from(half_filled))]), size) else {
|
||
return;
|
||
};
|
||
assert!(worst <= 3, "the half-filled color mask differs between the CPU and GPU by up to {worst} levels");
|
||
}
|