Files
photocraft/crates/engine/tests/it/paint_in_adjust_params.rs

359 lines
19 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Tests that run paint commands, moved from the engine-core `adjust_params` tests: 11 test(s).
/// Mirrors `adjust_params::MAX_FITTED_POINTS`.
const MAX_FITTED_POINTS: usize = 16;
use photocraft_color::ColorMode;
use photocraft_doc::Adjustment;
use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, ToneSpace};
use photocraft_engine::EngineError;
use photocraft_engine::Session;
use photocraft_engine::adjust_params::*;
use serde_json::Value;
use serde_json::json;
const KINDS: [&str; 15] = [
"invert",
"brightnessContrast",
"threshold",
"posterize",
"exposure",
"vibrance",
"hueSaturation",
"levels",
"curves",
"colorBalance",
"blackWhite",
"photoFilter",
"channelMixer",
"gradientMap",
"selectiveColor",
];
/// A non-default parameter set per kind (RGB channel keys for Levels/Curves).
pub(crate) fn sample(kind: &str) -> Value {
match kind {
"brightnessContrast" => json!({"brightness": 20, "contrast": -10, "legacy": true}),
"threshold" => json!({"level": 100}),
"posterize" => json!({"levels": 7}),
"exposure" => json!({"exposure": 1.5, "offset": 0.1, "gamma": 1.4}),
"vibrance" => json!({"vibrance": 30, "saturation": -20}),
"hueSaturation" => {
json!({"hue": 25, "saturation": -20, "lightness": 10, "reds": {"hue": 10, "saturation": -30, "lightness": 5, "range": [300, 340, 20, 50]}})
}
"levels" => json!({"inBlack": 10, "inWhite": 240, "outBlack": 5, "outWhite": 250, "gamma": 1.2, "red": {"inBlack": 3, "gamma": 0.8}}),
"curves" => json!({"points": [[0, 0], [128, 150], [255, 255]], "blue": [[0, 20], [255, 235]]}),
"colorBalance" => json!({"shadows": [10, -5, 0], "midtones": [0, 20, -30], "highlights": [5, 5, 5], "preserveLuminosity": false}),
"blackWhite" => json!({"reds": 120, "blues": -40, "tint": true, "tintColor": "#d0a070"}),
"photoFilter" => json!({"color": "#3366cc", "density": 40, "preserveLuminosity": false}),
"channelMixer" => json!({"red": [80, 30, -10, 5], "blue": [0, 10, 90, 0]}),
"gradientMap" => json!({"stops": [[0, "#000000"], [0.5, "#ff0000"], [1, [1, 1, 1]]], "reverse": true, "dither": true}),
"selectiveColor" => json!({"method": "absolute", "reds": [10, 0, -20, 5]}),
_ => json!({}),
}
}
fn curves_parts(a: &Adjustment) -> (&[CurvePoint], &[Vec<CurvePoint>; 3]) {
match a {
Adjustment::Curves { master, per_channel, .. } => (master, per_channel),
_ => panic!("expected curves"),
}
}
fn tone_output(adjustment: &Adjustment, sample: [f32; 3]) -> [f32; 3] {
let luts = photocraft_compose::adjust::tone_luts(adjustment);
std::array::from_fn(|channel| {
let row = &luts[channel];
let position = sample[channel].clamp(0.0, 1.0) * (row.len().saturating_sub(1)) as f32;
let lower = position.floor() as usize;
let upper = lower.saturating_add(1).min(row.len().saturating_sub(1));
let fraction = position - lower as f32;
row.get(lower).copied().unwrap_or(0.0) * (1.0 - fraction) + row.get(upper).copied().unwrap_or(0.0) * fraction
})
}
#[test]
fn curves_eyedropper_param_drives_the_command() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap();
let px: Vec<f32> = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap();
assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}");
s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap();
let px: Vec<f32> = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap();
assert!(px.iter().take(3).all(|v| *v < 0.01), "the given colour becomes black: {px:?}");
for bad in [
json!("black"),
json!({"point": "nope", "at": [1, 1]}),
json!({"point": "black"}),
json!({"point": "black", "at": [99, 1]}),
json!({"point": "black", "at": [-1, 1]}),
json!({"point": "black", "at": [1]}),
json!({"point": "gray", "at": [f64::MAX, 1]}),
json!({"point": "black", "color": "red"}),
] {
assert!(s.execute("image.adjustments.curves", json!({"eyedropper": bad})).is_err(), "{bad}");
}
}
/// The Properties panel's pickers on a Curves adjustment layer (UI-217-15): one undoable step
/// that samples the image below the layer, so a repeated click keeps the same curve.
#[test]
fn layer_eyedropper_samples_below_the_curves_layer() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap();
let steps = s.active().unwrap().history.past_len();
let pick = json!({"eyedropper": {"point": "white", "at": [2, 2], "size": 3}});
s.execute("layer.setAdjustment", pick.clone()).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
let px: Vec<f32> = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap();
assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}");
let curve = s.active().unwrap().doc.clone();
s.execute("layer.setAdjustment", pick).unwrap();
let same = |a: &photocraft_doc::Document, b: &photocraft_doc::Document| a.layers.last().map(|l| &l.content) == b.layers.last().map(|l| &l.content);
assert!(same(&curve, &s.active().unwrap().doc), "sampled below the layer, not through it");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), steps);
for bad in [json!({"point": "black", "at": [99, 1]}), json!({"point": "black", "at": [1, 1], "size": 2}), json!({"point": "x", "at": [1, 1]})] {
assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}");
}
s.execute("layer.newAdjustmentLayer.hueSaturation", json!({})).unwrap();
assert!(s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "white", "at": [1, 1]}})).is_err(), "Levels and Curves only");
}
/// #3127: on a smart object the eyedropper param records the adjustment it resolved to as
/// the smart filter, not the raw sample (which re-rendered as an identity).
#[test]
fn eyedropper_on_a_smart_object_records_the_resolved_adjustment() {
for kind in ["curves", "levels"] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
s.execute(&format!("image.adjustments.{kind}"), json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap();
let px: Vec<f32> = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap();
assert!(px.iter().take(3).all(|v| *v > 0.99), "{kind}: {px:?}");
}
}
/// Levels' Set White/Neutral Gray Point (#3116): the white point maps the sampled colour to
/// white at 8 and 16 bit, the gray point neutralises a tinted grey at its luma on a Levels
/// layer as one undoable step, and bad picks fail.
#[test]
fn levels_eyedroppers_set_white_and_neutral_gray() {
let pixel =
|s: &mut photocraft_engine::Session| -> Vec<f32> { serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap() };
for depth in [8, 16] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap();
let px = pixel(&mut s);
assert!(px.iter().take(3).all(|v| *v > 0.995), "{depth}-bit: the sample becomes white: {px:?}");
}
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
let before = pixel(&mut s);
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
let steps = s.active().unwrap().history.past_len();
s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "gray", "at": [2, 2]}})).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
let px = pixel(&mut s);
let (lo, hi) = px.iter().take(3).fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
assert!(hi - lo < 2.5 / 255.0, "neutral: {px:?}");
let luma = |c: &[f32]| c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722;
assert!((luma(&px) - luma(&before)).abs() < 2.0 / 255.0, "keeps the luma: {px:?} vs {before:?}");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(pixel(&mut s), before);
for bad in [json!({"point": "gray", "at": [99, 1]}), json!({"point": "x", "at": [1, 1]}), json!({"point": "white", "color": [f64::NAN, 0, 0]})] {
assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}");
assert!(s.execute("image.adjustments.levels", json!({"eyedropper": bad})).is_err(), "{bad}");
}
s.execute("file.new", json!({"width": 8, "height": 8, "mode": "grayscale"})).unwrap();
assert!(s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "gray", "at": [1, 1]}})).is_err(), "no gray picker in Grayscale");
s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap();
}
/// A colourful 16×16 document (`mode`, `depth`) for command tests.
fn colourful(mode: &str, depth: u32) -> photocraft_engine::Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth})).unwrap();
for (i, c) in ["#c83c28", "#3c8c50", "#2850b4", "#d2b464"].iter().enumerate() {
s.execute("select.rect", json!({"x": (i % 2) * 8, "y": (i / 2) * 8, "width": 8, "height": 8})).unwrap();
s.execute("edit.fill", json!({"color": c})).unwrap();
}
s.execute("select.deselect", json!({})).unwrap();
s
}
fn pixels(s: &photocraft_engine::Session) -> Vec<Vec<f32>> {
let d = s.active().unwrap();
let bg = d.doc.layers[0].surface().unwrap();
[(2, 2), (10, 2), (2, 10), (10, 10)].iter().map(|&(x, y)| bg.pixel(x, y)).collect()
}
#[test]
fn destructive_commands_apply_their_params_at_every_depth() {
for depth in [8, 16, 32] {
for kind in KINDS.iter().filter(|k| **k != "invert") {
let mut s = colourful("rgb", depth);
let before = pixels(&s);
let steps = s.active().unwrap().history.past_len();
s.execute(&format!("image.adjustments.{kind}"), sample(kind)).unwrap_or_else(|e| panic!("{kind} @{depth}: {e}"));
assert_ne!(pixels(&s), before, "{kind} @{depth} changed nothing");
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{kind}: one history step");
// Identity params leave the pixels alone (within one 8-bit step).
let mut s = colourful("rgb", depth);
s.execute(&format!("image.adjustments.{kind}"), to_params(&default_for(kind, ColorMode::Rgb).unwrap())).unwrap();
if !matches!(*kind, "threshold" | "posterize" | "blackWhite" | "gradientMap" | "photoFilter") {
for (a, b) in pixels(&s).iter().zip(&before) {
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1.0 / 255.0 + 1e-4), "{kind} @{depth}: {a:?} vs {b:?}");
}
}
}
}
}
#[test]
fn curves_pencil_maps_draw_smooth_and_convert_back() {
// A drawn inversion: 256 output levels.
let inverted: Vec<f32> = (0..256).rev().map(|k| k as f32).collect();
let a = from_params("curves", &json!({"pencil": true, "points": inverted}), None, ColorMode::Rgb).unwrap();
assert!(matches!(&a, Adjustment::Curves { pencil: true, master, .. } if master.len() == CURVE_MAP_LEN));
assert!((tone_output(&a, [0.25; 3])[0] - 0.75).abs() < 1e-3);
assert_eq!(from_params("curves", &to_params(&a), None, ColorMode::Rgb).unwrap(), a);
// Smooth evens out a hard step but keeps the endpoints.
let step: Vec<f32> = (0..256).map(|k| if k < 128 { 0.0 } else { 255.0 }).collect();
let s = from_params("curves", &json!({"red": step, "smooth": 2}), Some(&a), ColorMode::Rgb).unwrap();
let (_, chans) = curves_parts(&s);
assert!(chans[0][127].output > 0.2 && chans[0][128].output < 0.8, "{:?}", &chans[0][120..136]);
assert_eq!((chans[0][0].output, chans[0][255].output), (0.0, 1.0));
// Edit points: the map is fitted with a point curve that still inverts.
let pts = from_params("curves", &json!({"pencil": false}), Some(&a), ColorMode::Rgb).unwrap();
let (master, _) = curves_parts(&pts);
assert!(matches!(&pts, Adjustment::Curves { pencil: false, .. }) && master.len() <= MAX_FITTED_POINTS, "{master:?}");
assert!((tone_output(&pts, [0.25; 3])[0] - 0.75).abs() < 2.0 / 255.0);
// The command draws it at every depth.
for depth in [8, 16, 32] {
let mut s = colourful("rgb", depth);
let before = pixels(&s);
s.execute("image.adjustments.curves", to_params(&a)).unwrap();
let after = pixels(&s);
assert!((after[0][0] - (1.0 - before[0][0])).abs() < 2.0 / 255.0, "@{depth}: {after:?} vs {before:?}");
}
}
#[test]
fn destructive_levels_dont_clip_in_32_bit() {
// Input 15..230, gamma 1.3, output 10..245: integer documents stop at the output range,
// while float documents preserve the curve's signed and HDR values beyond it (the
// compose-side `levels_dont_clip_in_32_bit` pins the same curve, #2592).
let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245});
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap();
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("image.adjustments.levels", params.clone()).unwrap();
let px = pixels(&s);
if depth == 32 {
assert!(px[0][0].is_finite() && px[0][0] < 0.0, "float black keeps its signed result: {:?}", px[0]);
assert!(px[1][0].is_finite() && px[1][0] > 1.0, "float white keeps its HDR result: {:?}", px[1]);
} else {
assert!((px[0][0] * 255.0 - 10.0).abs() < 0.6, "black @{depth}: {:?}", px[0]);
assert!((px[1][0] * 255.0 - 245.0).abs() < 0.6, "white @{depth}: {:?}", px[1]);
}
}
}
#[test]
fn cmyk_and_lab_documents_use_their_channels() {
let mut s = colourful("cmyk", 8);
let before = pixels(&s);
// More black ink darkens every patch.
s.execute("image.adjustments.curves", json!({"black": [[0, 0], [255, 180]]})).unwrap();
let after = pixels(&s);
assert!(after.iter().zip(&before).all(|(a, b)| a[3] > b[3] + 0.05), "{after:?} vs {before:?}");
let mut s = colourful("lab", 16);
let before = pixels(&s);
s.execute("image.adjustments.levels", json!({"lightness": {"outBlack": 60}})).unwrap();
let after = pixels(&s);
assert!(after.iter().zip(&before).all(|(a, b)| a[0] >= b[0]), "lightness lifted {after:?} vs {before:?}");
// The adjustment layer of a CMYK document defaults to ink channels.
let mut s = colourful("cmyk", 8);
s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
let l = s.active().unwrap().doc.layer(id).unwrap().clone();
assert!(matches!(l.content, photocraft_doc::LayerContent::Adjustment(Adjustment::Curves { space: ToneSpace::Cmyk, .. })));
}
#[test]
fn set_adjustment_merges_and_resets() {
let mut s = colourful("rgb", 8);
s.execute("layer.newAdjustmentLayer.colorBalance", json!({"midtones": [30, 0, 0]})).unwrap();
s.execute("layer.setAdjustment", json!({"highlights": [0, 0, -20]})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
let adj = |s: &photocraft_engine::Session| match &s.active().unwrap().doc.layer(id).unwrap().content {
photocraft_doc::LayerContent::Adjustment(a) => a.clone(),
_ => panic!(),
};
assert!(matches!(adj(&s), Adjustment::ColorBalance { midtones: [30.0, 0.0, 0.0], highlights: [0.0, 0.0, -20.0], .. }));
s.execute("layer.setAdjustment", json!({"layer": id.0})).unwrap();
assert_eq!(adj(&s), default_for("colorBalance", ColorMode::Rgb).unwrap());
// Bad params are errors and leave the layer alone.
s.execute("layer.setAdjustment", json!({"midtones": [10, 10, 10]})).unwrap();
let kept = adj(&s);
for bad in [json!({"midtones": "x"}), json!({"preserveLuminosity": 3}), json!({"shadows": [1]})] {
assert!(s.execute("layer.setAdjustment", bad.clone()).is_err(), "{bad}");
assert_eq!(adj(&s), kept);
}
}
#[test]
fn commands_reject_bad_params_gracefully() {
let mut s = colourful("rgb", 8);
for (kind, p) in [
("curves", json!({"points": [[0, 0]]})),
("levels", json!({"red": "dark"})),
("gradientMap", json!({"stops": [[0, 1, 2]]})),
("photoFilter", json!({"filter": 3})),
("channelMixer", json!({"gray": [1, 2]})),
("hueSaturation", json!({"reds": 4})),
("blackWhite", json!({"tint": "yes"})),
] {
for prefix in ["image.adjustments.", "layer.newAdjustmentLayer."] {
let r = s.execute(&format!("{prefix}{kind}"), p.clone());
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{prefix}{kind} {p}: {r:?}");
}
}
}
#[test]
fn destructive_levels_match_independent_signed_hdr_endpoints() {
// Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in
// integer documents. Float32 keeps HDR values outside 0..1, as the compositor's real-file
// Levels oracle does. These independently calculated endpoints use the signed-power
// curve at black and white, not display-clipped values.
let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245});
for (depth, low, high, tolerance) in [(8, 10.0, 245.0, 0.6), (16, 10.0, 245.0, 0.6), (32, -20.308_89, 265.750_3, 0.01)] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap();
s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("image.adjustments.levels", params.clone()).unwrap();
let px = pixels(&s);
assert!((px[0][0] * 255.0 - low).abs() < tolerance, "black @{depth}: {:?}", px[0]);
assert!((px[1][0] * 255.0 - high).abs() < tolerance, "white @{depth}: {:?}", px[1]);
if depth == 32 {
assert!(px[0][0] < 0.0 && px[1][0] > 1.0, "HDR endpoints must remain unclipped");
}
}
}