mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-22 18:41:44 +01:00
feat(render): soft masks: mask layers reveal by their artwork's opacity or luminance (M4)
This commit is contained in:
1 parent
34de21d1d1
commit
8cc0384bc1
9 files changed
+281
-52
No files matched your search
+31
-3
@@ -3,7 +3,7 @@
|
||||
use crate::camera::Camera;
|
||||
use crate::nine_slice::Slicing;
|
||||
use crate::player::PlayerState;
|
||||
use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
|
||||
use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, MaskMode, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
|
||||
use anicraft_geom::walk::PathWalk;
|
||||
use anicraft_geom::{Affine, FillRule, Path};
|
||||
use std::borrow::Cow;
|
||||
@@ -30,7 +30,9 @@ pub struct DisplayItem {
|
||||
pub outline: Option<Rgba>,
|
||||
/// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]).
|
||||
pub clip: Option<u32>,
|
||||
/// Mask artwork: not drawn; its fill area (strokes and opacity ignored) forms this clip.
|
||||
/// Mask artwork: not drawn; it forms this clip: its fill area (strokes and opacity
|
||||
/// ignored), or for a soft clip ([`DisplayList::clip_mode`]) its opacity or brightness as
|
||||
/// drawn.
|
||||
pub masks: Option<u32>,
|
||||
/// Guide artwork: shown while editing, never in output.
|
||||
pub guide: bool,
|
||||
@@ -51,6 +53,9 @@ pub struct DisplayList {
|
||||
/// One entry per clip: the enclosing clip it is intersected with. A parent always has a
|
||||
/// lower index than its children. A clip with no mask artwork hides everything in it.
|
||||
pub clip_parents: Vec<Option<u32>>,
|
||||
/// How each clip's artwork reveals (ADR 0070), by clip index. Sparse: a clip past its end
|
||||
/// is [`MaskMode::Coverage`], so lists that don't care leave it empty.
|
||||
pub clip_modes: Vec<MaskMode>,
|
||||
/// Groups that fade as one: a symbol instance with an opacity below 1 composites its
|
||||
/// items together, then blends the result at `alpha`, so overlapping parts don't show
|
||||
/// through each other. A group's items are one unbroken run of `items`, nested runs for
|
||||
@@ -72,6 +77,24 @@ pub struct Group {
|
||||
}
|
||||
|
||||
impl DisplayList {
|
||||
/// How clip `c`'s artwork reveals (coverage when unset).
|
||||
pub fn clip_mode(&self, c: u32) -> MaskMode {
|
||||
self.clip_modes.get(c as usize).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Sets clip `c`'s mode (only a soft mode is stored; coverage stays implicit).
|
||||
pub fn set_clip_mode(&mut self, c: u32, mode: MaskMode) {
|
||||
let i = c as usize;
|
||||
if mode.is_soft() && i < self.clip_parents.len() {
|
||||
if self.clip_modes.len() <= i {
|
||||
self.clip_modes.resize(i + 1, MaskMode::Coverage);
|
||||
}
|
||||
if let Some(m) = self.clip_modes.get_mut(i) {
|
||||
*m = mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity an item ends up with: its own times every group's it is in (what an item
|
||||
/// looks like when nothing overlaps it; also what picking and outlines use).
|
||||
pub fn effective_alpha(&self, item: &DisplayItem) -> f32 {
|
||||
@@ -107,6 +130,9 @@ impl DisplayList {
|
||||
let gbase = self.groups.len() as u32;
|
||||
let gshift = |g: Option<u32>| g.map(|g| g + gbase);
|
||||
self.clip_parents.extend(other.clip_parents.into_iter().map(shift));
|
||||
for (i, m) in other.clip_modes.into_iter().enumerate() {
|
||||
self.set_clip_mode(base + i as u32, m);
|
||||
}
|
||||
self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) }));
|
||||
self.items.extend(other.items.into_iter().map(|mut i| {
|
||||
i.clip = shift(i.clip);
|
||||
@@ -398,8 +424,10 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut
|
||||
let mut clips: Vec<(LayerId, u32)> = Vec::new();
|
||||
if cx.masks.is_none() {
|
||||
for layer in tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible) {
|
||||
clips.push((layer.id, out.clip_parents.len() as u32));
|
||||
let c = out.clip_parents.len() as u32;
|
||||
clips.push((layer.id, c));
|
||||
out.clip_parents.push(cx.clip);
|
||||
out.set_clip_mode(c, layer.mask_mode);
|
||||
}
|
||||
}
|
||||
let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c);
|
||||
|
||||
@@ -156,6 +156,27 @@ fn masks_inside_symbols_nest_in_the_instance_clip() {
|
||||
assert_eq!(inner, vec![(Some(0), None), (Some(1), None), (Some(1), None), (Some(0), Some(1))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soft_mask_layer_gives_its_clip_its_mode() {
|
||||
let mut d = mask_doc();
|
||||
assert_eq!((evaluate(&d, 0).clip_mode(0), evaluate(&d, 0).clip_modes.len()), (crate::MaskMode::Coverage, 0), "coverage stays implicit");
|
||||
Arc::make_mut(&mut d.timeline_mut(0).layers[0]).mask_mode = crate::MaskMode::Luminance;
|
||||
let dl = evaluate(&d, 0);
|
||||
assert_eq!(dl.clip_mode(0), crate::MaskMode::Luminance);
|
||||
// Appended lists keep their modes on their renumbered clips.
|
||||
let mut a = evaluate(&mask_doc(), 0);
|
||||
a.append(dl);
|
||||
assert_eq!((a.clip_mode(0), a.clip_mode(1)), (crate::MaskMode::Coverage, crate::MaskMode::Luminance));
|
||||
// The mode is saved only when it isn't coverage, and older files (without it) open as coverage.
|
||||
let json = serde_json::to_string(&*d.timeline(0).layers[0]).unwrap();
|
||||
assert!(json.contains("\"mask_mode\":\"luminance\""), "{json}");
|
||||
let plain = serde_json::to_string(&*mask_doc().timeline(0).layers[0]).unwrap();
|
||||
assert!(!plain.contains("mask_mode"));
|
||||
let back: Layer = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.mask_mode, crate::MaskMode::Luminance);
|
||||
assert_eq!(serde_json::from_str::<Layer>(&plain).unwrap().mask_mode, crate::MaskMode::Coverage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appending_lists_renumbers_clips() {
|
||||
let d = mask_doc();
|
||||
|
||||
@@ -820,8 +820,59 @@ pub struct Layer {
|
||||
/// An armature layer's bones (ADR 0043); `None` on every other kind of layer.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub armature: Option<Arc<Armature>>,
|
||||
/// How a mask layer's artwork reveals what it masks (ADR 0070): its fill area (Animate's
|
||||
/// masks), or its opacity or brightness (soft masks). Ignored on other kinds of layer.
|
||||
#[serde(default, skip_serializing_if = "MaskMode::is_coverage")]
|
||||
pub mask_mode: MaskMode,
|
||||
}
|
||||
|
||||
/// How a mask layer's artwork reveals the layers it masks (ADR 0070).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MaskMode {
|
||||
/// Its fills' area, fully opaque: colours, opacity and strokes don't matter (as in Animate).
|
||||
#[default]
|
||||
Coverage,
|
||||
/// Its artwork as drawn (fills, strokes, gradients, bitmaps, opacity): the artwork's
|
||||
/// opacity reveals (Animate users get this with alpha-gradient masks; SVG `mask-type: alpha`).
|
||||
Alpha,
|
||||
/// Its artwork's brightness times its opacity reveals: white shows, black hides (SVG's
|
||||
/// default `mask`). Luminance uses the sRGB coefficients 0.2125, 0.7154, 0.0721.
|
||||
Luminance,
|
||||
}
|
||||
|
||||
impl MaskMode {
|
||||
pub const ALL: [MaskMode; 3] = [MaskMode::Coverage, MaskMode::Alpha, MaskMode::Luminance];
|
||||
pub fn is_coverage(&self) -> bool {
|
||||
*self == MaskMode::Coverage
|
||||
}
|
||||
/// Whether the artwork's colours and opacity count (not just its area).
|
||||
pub fn is_soft(self) -> bool {
|
||||
self != MaskMode::Coverage
|
||||
}
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
MaskMode::Coverage => "coverage",
|
||||
MaskMode::Alpha => "alpha",
|
||||
MaskMode::Luminance => "luminance",
|
||||
}
|
||||
}
|
||||
pub fn from_key(k: &str) -> Option<MaskMode> {
|
||||
MaskMode::ALL.into_iter().find(|m| m.key() == k)
|
||||
}
|
||||
/// How much a premultiplied colour reveals in this mode, `0..=1`.
|
||||
pub fn reveal(self, premul: [f32; 4]) -> f32 {
|
||||
let v = match self {
|
||||
MaskMode::Coverage | MaskMode::Alpha => premul[3],
|
||||
MaskMode::Luminance => LUMA[0] * premul[0] + LUMA[1] * premul[1] + LUMA[2] * premul[2],
|
||||
};
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The luminance coefficients of a luminance mask (SVG's `luminanceToAlpha`, on sRGB values).
|
||||
pub const LUMA: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
|
||||
fn is_zero(v: &f32) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
@@ -892,6 +943,7 @@ impl Layer {
|
||||
volume: 1.0,
|
||||
muted: false,
|
||||
armature: None,
|
||||
mask_mode: MaskMode::Coverage,
|
||||
}
|
||||
}
|
||||
/// The row height in normal rows, `1..=MAX_LAYER_HEIGHT` whatever a file says.
|
||||
|
||||
@@ -308,6 +308,9 @@ fn interleave(tl: &Timeline, parts: Vec<DisplayList>) -> (DisplayList, Vec<usize
|
||||
let shift = move |c: Option<u32>| c.map(|c| c + base);
|
||||
let gshift = move |g: Option<u32>| g.map(|g| g + gbase);
|
||||
dl.clip_parents.extend(part.clip_parents.into_iter().map(shift));
|
||||
for (i, m) in part.clip_modes.into_iter().enumerate() {
|
||||
dl.set_clip_mode(base + i as u32, m);
|
||||
}
|
||||
dl.groups.extend(part.groups.into_iter().map(|g| anicraft_doc::Group { parent: gshift(g.parent), clip: shift(g.clip), ..g }));
|
||||
iters.push(
|
||||
part.items
|
||||
|
||||
@@ -452,7 +452,7 @@ impl GpuRenderer {
|
||||
blurred.group = Some(0);
|
||||
let filters = Arc::from(vec![Filter::Blur { blur_x: 3.0, blur_y: 2.0, quality: 2 }, Filter::AdjustColor { brightness: 10.0, contrast: 0.0, saturation: -50.0, hue: 30.0 }]);
|
||||
let groups = vec![Group { parent: None, alpha: 1.0, blend: anicraft_doc::BlendMode::Normal, filters, clip: None }];
|
||||
let dl = DisplayList { items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![solid(2.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), solid(14.0, Rgba::new(0.0, 0.0, 1.0, 0.5)), bitmap, blurred], groups, ..Default::default() };
|
||||
let view = View { transform: Affine::IDENTITY, width: 24, height: 20, background: Some(Rgba::WHITE) };
|
||||
let (oracle, _) = anicraft_render::render(&dl, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?;
|
||||
let oracle = oracle.to_premul_rgba8();
|
||||
@@ -473,7 +473,7 @@ impl GpuRenderer {
|
||||
check("through a texture", &self.read_texture(&t)?)?;
|
||||
// Binned on the GPU (the plain fills; the bitmap and the symbol bin on the CPU): if that
|
||||
// comes back wrong, only the binning stays on the CPU here.
|
||||
let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() };
|
||||
let plain = DisplayList { clip_modes: Vec::new(), items: dl.items.iter().take(3).cloned().collect(), ..Default::default() };
|
||||
let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?;
|
||||
let why = match self.render_with(&plain, &view, Output::Premul8, Binning::Gpu) {
|
||||
Ok(got) => match compare_premul8(&got.premul8, &want.to_premul_rgba8()) {
|
||||
|
||||
+18
-12
@@ -36,7 +36,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem {
|
||||
}
|
||||
|
||||
fn list(items: Vec<DisplayItem>) -> DisplayList {
|
||||
DisplayList { items, ..Default::default() }
|
||||
DisplayList { clip_modes: Vec::new(), items, ..Default::default() }
|
||||
}
|
||||
|
||||
fn view(w: u32, h: u32, bg: Option<Rgba>) -> View {
|
||||
@@ -170,6 +170,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let mut out = Vec::new();
|
||||
// A mask: a gradient seen through a circle, an unclipped shape over it, and one under it.
|
||||
let dl = DisplayList {
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))],
|
||||
clip_parents: vec![None],
|
||||
groups: Vec::new(),
|
||||
@@ -191,10 +192,11 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
}
|
||||
let mut items = stripes;
|
||||
items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]);
|
||||
out.push(("nested masks", DisplayList { items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0)))));
|
||||
out.push(("nested masks", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0)))));
|
||||
// Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles
|
||||
// and the render bands; a top-level shape between two groups.
|
||||
let dl = DisplayList {
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0),
|
||||
in_group(item(Path::ellipse(55.0, 40.0, 35.0, 30.0), grad()), 0),
|
||||
@@ -221,9 +223,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g));
|
||||
items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g));
|
||||
}
|
||||
out.push(("blend modes", DisplayList { items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8)))));
|
||||
out.push(("blend modes", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8)))));
|
||||
// Masks inside groups and groups inside masks, with a blend mode, on transparent.
|
||||
let dl = DisplayList {
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0),
|
||||
in_group(item(Path::ellipse(70.0, 40.0, 30.0, 30.0), Paint::Solid(blue)), 0),
|
||||
@@ -239,6 +242,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
// Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides
|
||||
// what it clips), a group whose parent is later (top-level), a clip index past the list.
|
||||
let dl = DisplayList {
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0),
|
||||
mask(Path::rect(0.0, 0.0, 30.0, 30.0), 0),
|
||||
@@ -569,6 +573,7 @@ fn binning_shapes_the_scene_into_tiles() {
|
||||
// A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In
|
||||
// the middle tile the mask has no artwork, so the clipped fill is left out there.
|
||||
let dl = DisplayList {
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0),
|
||||
clipped(item(Path::rect(0.0, 0.0, 40.0, 16.0), Paint::Solid(Rgba::BLACK)), 0),
|
||||
@@ -597,6 +602,7 @@ fn binning_shapes_the_scene_into_tiles() {
|
||||
#[test]
|
||||
fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() {
|
||||
let deep = |n: usize| DisplayList {
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)],
|
||||
clip_parents: Vec::new(),
|
||||
groups: (0..n).map(|i| group(i.checked_sub(1).map(|p| p as u32), 0.9, BlendMode::Normal)).collect(),
|
||||
@@ -608,7 +614,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() {
|
||||
let masks = |n: usize| {
|
||||
let mut items: Vec<DisplayItem> = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect();
|
||||
items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1));
|
||||
DisplayList { items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() }
|
||||
DisplayList { clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() }
|
||||
};
|
||||
assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok());
|
||||
assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips));
|
||||
@@ -779,7 +785,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() {
|
||||
.collect();
|
||||
let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1);
|
||||
it.color = ColorTransform::alpha(0.5);
|
||||
DisplayList { items: vec![it], clip_parents: Vec::new(), groups }
|
||||
DisplayList { clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups }
|
||||
};
|
||||
let deep = nested(MAX_FILTER_DEPTH + 1);
|
||||
assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters))));
|
||||
@@ -857,7 +863,7 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
// Inside a mask and a faded group, over a gradient.
|
||||
let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(80.0, 60.0), stops: stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]) });
|
||||
let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0);
|
||||
let dl = DisplayList { items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
out.push(("bitmap masked and multiplied", dl, view(80, 60, white)));
|
||||
// Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated.
|
||||
let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned);
|
||||
@@ -940,7 +946,7 @@ fn gpu_matches_the_oracle_on_every_filter() {
|
||||
for (name, f) in filters_to_test() {
|
||||
let mut items = vec![backdrop.clone()];
|
||||
items.extend(symbol_items(0));
|
||||
let dl = DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] };
|
||||
// At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface.
|
||||
for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] {
|
||||
let d = assert_parity(g, name, &dl, &v);
|
||||
@@ -965,7 +971,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() {
|
||||
(grp.alpha, grp.blend) = (0.7, BlendMode::Multiply);
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0));
|
||||
scenes.push(("filters in a row, faded and multiplied", DisplayList { items, clip_parents: Vec::new(), groups: vec![grp] }));
|
||||
scenes.push(("filters in a row, faded and multiplied", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] }));
|
||||
// A filtered symbol inside a filtered symbol, inside a faded one.
|
||||
let mut outer = filtered_group(vec![shadow.clone()]);
|
||||
outer.parent = Some(0);
|
||||
@@ -973,22 +979,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() {
|
||||
inner.parent = Some(1);
|
||||
let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)];
|
||||
items.extend(symbol_items(2));
|
||||
scenes.push(("nested filtered symbols", DisplayList { items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] }));
|
||||
scenes.push(("nested filtered symbols", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] }));
|
||||
// Masked from outside (after filtering) and inside (before).
|
||||
let mut clipped_grp = filtered_group(vec![glow.clone()]);
|
||||
clipped_grp.clip = Some(0);
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0)));
|
||||
items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0));
|
||||
scenes.push(("masked after filtering", DisplayList { items, clip_parents: vec![None], groups: vec![clipped_grp] }));
|
||||
scenes.push(("masked after filtering", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] }));
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0)));
|
||||
items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0));
|
||||
scenes.push(("masked inside the symbol", DisplayList { items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] }));
|
||||
scenes.push(("masked inside the symbol", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] }));
|
||||
// A bitmap inside a filtered symbol.
|
||||
let px = pixels(9, 7, 4);
|
||||
let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)];
|
||||
scenes.push(("filtered bitmap", DisplayList { items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] }));
|
||||
scenes.push(("filtered bitmap", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] }));
|
||||
for (name, dl) in scenes {
|
||||
for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] {
|
||||
let d = assert_parity(g, name, &dl, &v);
|
||||
|
||||
+145
-26
@@ -13,7 +13,7 @@ pub mod html;
|
||||
pub mod lottie;
|
||||
pub mod svg;
|
||||
|
||||
use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, Paint, Rgba, evaluate};
|
||||
use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, MaskMode, Paint, Rgba, evaluate};
|
||||
use anicraft_geom::{Affine, FillRule, Rect, Vec2};
|
||||
use paint::{Premul, Shader, premultiply};
|
||||
use raster::{Coverage, IRect};
|
||||
@@ -158,7 +158,7 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re
|
||||
|
||||
// Phase 1 (parallel over items): cull, flatten, stroke and build shaders. Output keeps
|
||||
// display-list order.
|
||||
let mut prepared: Vec<Vec<Prepared>> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface) }).collect();
|
||||
let mut prepared: Vec<Vec<Prepared>> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item)) }).collect();
|
||||
for r in &runs {
|
||||
if let (Some(op), Some(slot)) = (filtered_group(dl, r, view, surface)?, prepared.get_mut(r.start)) {
|
||||
slot.push(op);
|
||||
@@ -175,7 +175,7 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re
|
||||
if op.masks.is_some() { mask_ops.push(op) } else { ops.push(op) }
|
||||
}
|
||||
}
|
||||
let clips = Clips::new(&dl.clip_parents, mask_ops);
|
||||
let clips = Clips::new(&dl.clip_parents, &dl.clip_modes, mask_ops);
|
||||
// A clipped op can only touch its clip's area; an op whose clip is empty draws nothing.
|
||||
ops.retain_mut(|op| {
|
||||
let Some(c) = op.clip else { return true };
|
||||
@@ -329,7 +329,11 @@ pub struct ClipLayer {
|
||||
/// The clip this one is inside (always an earlier one; a malformed link is already `None`
|
||||
/// and its bounds empty, as [`render`] treats it).
|
||||
pub parent: Option<u32>,
|
||||
/// The mask artwork: solid fill areas whose coverages unite (`a + b − ab`).
|
||||
/// How the artwork reveals (ADR 0070). Coverage: `art` is solid fill areas whose coverages
|
||||
/// unite (`a + b − ab`). Alpha or luminance: `art` is painted fills (their strokes too)
|
||||
/// composited src-over onto transparent, and the result's opacity, or its luminance
|
||||
/// ([`MaskMode::reveal`]), is the clip's coverage.
|
||||
pub mode: MaskMode,
|
||||
pub art: Vec<Fill>,
|
||||
/// Where the clip, and so anything drawn inside it, can be non-zero.
|
||||
pub bounds: IRect,
|
||||
@@ -366,7 +370,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat
|
||||
let surface = IRect { x0: 0, y0: 0, x1: view.width as i32, y1: view.height as i32 };
|
||||
let runs = filtered_runs(dl);
|
||||
let in_run = in_runs(dl, &runs);
|
||||
let mut prepared: Vec<Vec<Prepared>> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface) }).collect();
|
||||
let mut prepared: Vec<Vec<Prepared>> = dl.items.par_iter().zip(&in_run).map(|(item, &skip)| if skip { Vec::new() } else { prepare(item, &view.transform, surface, soft_art(dl, item)) }).collect();
|
||||
let mut layers = Vec::new();
|
||||
for r in &runs {
|
||||
if let (Some(setup), Some(slot)) = (filter_setup(dl, r, view, surface), prepared.get_mut(r.start)) {
|
||||
@@ -388,7 +392,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat
|
||||
}
|
||||
}
|
||||
// The same clips, bounds and culling of clipped fills as `render`.
|
||||
let clips = Clips::new(&dl.clip_parents, mask_ops);
|
||||
let clips = Clips::new(&dl.clip_parents, &dl.clip_modes, mask_ops);
|
||||
ops.retain_mut(|op| {
|
||||
let Some(c) = op.clip else { return true };
|
||||
op.bounds = op.bounds.intersect(&clips.bounds(c));
|
||||
@@ -402,8 +406,8 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat
|
||||
fills.push(fill(op));
|
||||
}
|
||||
stats.drawn = fills.len();
|
||||
let Clips { parents, art, bounds } = clips;
|
||||
let clips = parents.into_iter().zip(art).zip(bounds).map(|((parent, art), bounds)| ClipLayer { parent, art: art.into_iter().map(fill).collect(), bounds }).collect();
|
||||
let Clips { parents, modes, art, bounds } = clips;
|
||||
let clips = parents.into_iter().zip(modes).zip(art).zip(bounds).map(|(((parent, mode), art), bounds)| ClipLayer { parent, mode, art: art.into_iter().map(fill).collect(), bounds }).collect();
|
||||
let groups = group_chains(&dl.groups)
|
||||
.into_iter()
|
||||
.zip(&dl.groups)
|
||||
@@ -528,6 +532,7 @@ fn filter_setup(dl: &DisplayList, run: &FilteredRun, view: &View, surface: IRect
|
||||
let list = DisplayList {
|
||||
items: items.iter().map(|i| DisplayItem { clip: i.clip.filter(|c| inner.contains(c)), ..i.clone() }).collect(),
|
||||
clip_parents: dl.clip_parents.iter().map(|p| p.filter(|c| inner.contains(c))).collect(),
|
||||
clip_modes: dl.clip_modes.clone(),
|
||||
groups,
|
||||
};
|
||||
let sub_view = View { transform: Affine::translate(-b.x0 as f32, -b.y0 as f32).mul(&view.transform), width: b.width() as u32, height: b.height() as u32, background: None };
|
||||
@@ -675,6 +680,7 @@ struct Prepared {
|
||||
/// The clips of a display list: their mask artwork and where each can be non-zero.
|
||||
struct Clips {
|
||||
parents: Vec<Option<u32>>,
|
||||
modes: Vec<MaskMode>,
|
||||
/// Mask artwork, grouped by clip.
|
||||
art: Vec<Vec<Prepared>>,
|
||||
bounds: Vec<IRect>,
|
||||
@@ -683,8 +689,9 @@ struct Clips {
|
||||
const NO_PIXELS: IRect = IRect { x0: 0, y0: 0, x1: 0, y1: 0 };
|
||||
|
||||
impl Clips {
|
||||
fn new(parents: &[Option<u32>], mask_ops: Vec<Prepared>) -> Clips {
|
||||
fn new(parents: &[Option<u32>], modes: &[MaskMode], mask_ops: Vec<Prepared>) -> Clips {
|
||||
let n = parents.len();
|
||||
let modes = (0..n).map(|i| modes.get(i).copied().unwrap_or_default()).collect();
|
||||
let mut art: Vec<Vec<Prepared>> = (0..n).map(|_| Vec::new()).collect();
|
||||
for op in mask_ops {
|
||||
if let Some(a) = op.masks.and_then(|c| art.get_mut(c as usize)) {
|
||||
@@ -705,7 +712,7 @@ impl Clips {
|
||||
bounds.push(b);
|
||||
clean.push(parent.filter(|&p| (p as usize) < i));
|
||||
}
|
||||
Clips { parents: clean, art, bounds }
|
||||
Clips { parents: clean, modes, art, bounds }
|
||||
}
|
||||
|
||||
fn bounds(&self, c: u32) -> IRect {
|
||||
@@ -730,8 +737,28 @@ impl BandClips {
|
||||
}
|
||||
let parent = clips.parents.get(i).copied().flatten().map(|p| self.get(clips, p, band, w, cov, row));
|
||||
let mut buf = vec![0.0f32; w * band.height()];
|
||||
let mode = clips.modes.get(i).copied().unwrap_or_default();
|
||||
if mode.is_soft() {
|
||||
// A soft mask: its artwork painted onto transparent, then each pixel's opacity or
|
||||
// luminance.
|
||||
let mut px: Vec<Premul> = vec![[0.0; 4]; w * band.height()];
|
||||
for op in clips.art.get(i).into_iter().flatten() {
|
||||
let b = op.bounds.intersect(&band);
|
||||
if b.is_empty() {
|
||||
continue;
|
||||
}
|
||||
cov.reset(b);
|
||||
for poly in &op.polys {
|
||||
cov.add_polygon(poly);
|
||||
}
|
||||
composite(cov, op, b, band.y0, w, &mut px, row, None);
|
||||
}
|
||||
for (d, p) in buf.iter_mut().zip(&px) {
|
||||
*d = mode.reveal(*p);
|
||||
}
|
||||
}
|
||||
// Union of the artwork's coverage (a ∪ b = a + b − ab), anti-aliased like any fill.
|
||||
for op in clips.art.get(i).into_iter().flatten() {
|
||||
for op in clips.art.get(i).into_iter().flatten().filter(|_| !mode.is_soft()) {
|
||||
let b = op.bounds.intersect(&band);
|
||||
if b.is_empty() {
|
||||
continue;
|
||||
@@ -765,8 +792,15 @@ impl BandClips {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns a display item into fill operations (fill, then stroke), or none when culled.
|
||||
fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
/// Whether `item` is artwork of a soft mask (drawn with its paint, ADR 0070).
|
||||
fn soft_art(dl: &DisplayList, item: &DisplayItem) -> bool {
|
||||
item.masks.is_some_and(|c| dl.clip_mode(c).is_soft())
|
||||
}
|
||||
|
||||
/// Turns a display item into fill operations (fill, then stroke), or none when culled. `soft`:
|
||||
/// the item is a soft mask's artwork, prepared with its paints like any artwork (still marked
|
||||
/// as mask artwork).
|
||||
fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec<Prepared> {
|
||||
let mut out = Vec::new();
|
||||
let m = view.mul(&item.transform);
|
||||
if !m.is_finite() {
|
||||
@@ -776,8 +810,9 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
if item.guide {
|
||||
return out;
|
||||
}
|
||||
// Mask artwork is its fill area only: no strokes, no opacity (as animators expect).
|
||||
let is_mask = item.masks.is_some();
|
||||
// Mask artwork is its fill area only: no strokes, no opacity (as animators expect); a soft
|
||||
// mask's artwork is drawn as it looks.
|
||||
let is_mask = item.masks.is_some() && !soft;
|
||||
if is_mask && item.fill.is_none() {
|
||||
return out;
|
||||
}
|
||||
@@ -794,7 +829,7 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec<Prepared> {
|
||||
}
|
||||
let (clip, masks, group) = (item.clip, item.masks, item.group);
|
||||
// (Mask artwork is never outlined: it draws nothing of its own.)
|
||||
if let Some(color) = item.outline.filter(|_| !is_mask) {
|
||||
if let Some(color) = item.outline.filter(|_| item.masks.is_none()) {
|
||||
// Outline mode: a hairline in the layer colour, no fill (ADR 0048).
|
||||
let shader = Shader::Solid(premultiply(color));
|
||||
if shader.is_solid().is_some_and(|c| c[3] <= 0.0) {
|
||||
@@ -934,7 +969,90 @@ mod tests {
|
||||
}
|
||||
|
||||
fn list(items: Vec<DisplayItem>) -> DisplayList {
|
||||
DisplayList { items, clip_parents: Vec::new(), groups: Vec::new() }
|
||||
DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() }
|
||||
}
|
||||
|
||||
/// A 40 × 40 opaque blue square masked by `art` in `mode`, on transparent.
|
||||
fn soft(mode: MaskMode, art: Vec<DisplayItem>) -> Pixmap {
|
||||
let mut square = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
square.clip = Some(0);
|
||||
let mut items = vec![square];
|
||||
items.extend(art.into_iter().map(|mut a| {
|
||||
a.masks = Some(0);
|
||||
a
|
||||
}));
|
||||
let mut dl = DisplayList { items, clip_parents: vec![None], ..Default::default() };
|
||||
dl.set_clip_mode(0, mode);
|
||||
render(&dl, &view(40, 40)).unwrap().0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_masks_reveal_by_opacity_or_luminance() {
|
||||
let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
|
||||
let half_red = || item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.5)));
|
||||
// Alpha: the artwork's opacity is the coverage; its colour doesn't matter.
|
||||
let pm = soft(MaskMode::Alpha, vec![half_red()]);
|
||||
assert!(close(pm.pixel(20, 20).unwrap()[3], 0.5) && close(pm.pixel(20, 20).unwrap()[2], 0.5), "{:?}", pm.pixel(20, 20));
|
||||
// Coverage (today's masks): the same artwork reveals fully.
|
||||
assert_eq!(soft(MaskMode::Coverage, vec![half_red()]).pixel(20, 20).unwrap(), [0.0, 0.0, 1.0, 1.0]);
|
||||
// Luminance: 0.2125 r + 0.7154 g + 0.0721 b, times the opacity.
|
||||
let pm = soft(MaskMode::Luminance, vec![half_red()]);
|
||||
assert!(close(pm.pixel(20, 20).unwrap()[3], 0.2125 * 0.5), "{:?}", pm.pixel(20, 20));
|
||||
for (c, want) in [(Rgba::WHITE, 1.0), (Rgba::BLACK, 0.0), (Rgba::new(0.0, 1.0, 0.0, 1.0), 0.7154), (Rgba::new(0.5, 0.5, 0.5, 1.0), 0.5)] {
|
||||
let pm = soft(MaskMode::Luminance, vec![item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(c))]);
|
||||
assert!(close(pm.pixel(5, 5).unwrap()[3], want), "{c:?}: {:?}", pm.pixel(5, 5));
|
||||
}
|
||||
// Overlapping artwork composites (src-over) before it masks: two 0.5 layers give 0.75.
|
||||
let pm = soft(MaskMode::Alpha, vec![half_red(), half_red()]);
|
||||
assert!(close(pm.pixel(20, 20).unwrap()[3], 0.75));
|
||||
// The artwork's colour effect (an instance's alpha) counts.
|
||||
let mut faded = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::WHITE));
|
||||
faded.color = ColorTransform::alpha(0.25);
|
||||
assert!(close(soft(MaskMode::Alpha, vec![faded]).pixel(20, 20).unwrap()[3], 0.25));
|
||||
// Strokes count in a soft mask (not in a coverage one).
|
||||
let mut ring = item(Path::rect(10.0, 10.0, 20.0, 20.0), Paint::Solid(Rgba::TRANSPARENT));
|
||||
ring.stroke = Some(anicraft_doc::Stroke::new(Rgba::WHITE, 4.0));
|
||||
assert!(close(soft(MaskMode::Alpha, vec![ring.clone()]).pixel(10, 20).unwrap()[3], 1.0));
|
||||
assert_eq!(soft(MaskMode::Coverage, vec![ring]).pixel(10, 1).unwrap()[3], 0.0);
|
||||
// Outside the artwork nothing shows.
|
||||
let small = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::WHITE));
|
||||
assert_eq!(soft(MaskMode::Alpha, vec![small]).pixel(30, 30).unwrap()[3], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alpha_gradient_mask_fades_linearly() {
|
||||
// Transparent at x = 0 to opaque at x = 40: pixel x reveals (x + 0.5) / 40.
|
||||
let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: Rgba::new(1.0, 1.0, 1.0, 0.0) }, anicraft_doc::GradientStop { offset: 1.0, color: Rgba::WHITE }];
|
||||
let grad = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(40.0, 0.0), stops });
|
||||
let pm = soft(MaskMode::Alpha, vec![grad.clone()]);
|
||||
for x in [0u32, 10, 20, 30, 39] {
|
||||
let a = pm.pixel(x, 20).unwrap()[3];
|
||||
// The gradient table has 256 steps: within one step.
|
||||
assert!((a - (x as f32 + 0.5) / 40.0).abs() < 1.0 / 255.0 + 1e-3, "x {x}: {a}");
|
||||
}
|
||||
// White to transparent as luminance: the same ramp (white's luminance is 1).
|
||||
let lum = soft(MaskMode::Luminance, vec![grad]);
|
||||
assert!(pm.data.iter().zip(&lum.data).all(|(a, b)| (a[3] - b[3]).abs() < 1e-4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soft_mask_inside_another_mask_multiplies() {
|
||||
// Clip 1 (alpha, 0.5) inside clip 0 (coverage, left half): right half hidden, left at 0.5.
|
||||
let mut square = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
square.clip = Some(1);
|
||||
let mut outer = item(Path::rect(0.0, 0.0, 20.0, 40.0), Paint::Solid(Rgba::WHITE));
|
||||
outer.masks = Some(0);
|
||||
let mut inner = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(Rgba::new(1.0, 1.0, 1.0, 0.5)));
|
||||
inner.masks = Some(1);
|
||||
inner.clip = Some(0);
|
||||
let mut dl = DisplayList { items: vec![square, outer, inner], clip_parents: vec![None, Some(0)], ..Default::default() };
|
||||
dl.set_clip_mode(1, MaskMode::Alpha);
|
||||
let (pm, _) = render(&dl, &view(40, 40)).unwrap();
|
||||
assert!((pm.pixel(5, 5).unwrap()[3] - 0.5).abs() < 1e-4);
|
||||
assert_eq!(pm.pixel(30, 5).unwrap()[3], 0.0);
|
||||
// And the scene a GPU renderer gets carries the mode.
|
||||
let (scene, _) = prepare_scene(&dl, &view(40, 40)).unwrap();
|
||||
assert_eq!(scene.clips.iter().map(|c| c.mode).collect::<Vec<_>>(), vec![MaskMode::Coverage, MaskMode::Alpha]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -946,7 +1064,7 @@ mod tests {
|
||||
let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2)));
|
||||
mask.masks = Some(0);
|
||||
mask.stroke = Some(anicraft_doc::Stroke::new(Rgba::BLACK, 8.0));
|
||||
let dl = DisplayList { items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() };
|
||||
let (pm, _) = render(&dl, &view(40, 40)).unwrap();
|
||||
// Pixel for pixel, the same as the circle drawn in the square's colour.
|
||||
let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
@@ -1014,7 +1132,7 @@ mod tests {
|
||||
let mut blue = item(Path::rect(4.0, 0.0, 8.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
red.group = Some(0);
|
||||
blue.group = Some(0);
|
||||
let grouped = DisplayList { items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let grouped = DisplayList { clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let (pm, _) = render(&grouped, &white).unwrap();
|
||||
let near = |p: Premul, q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4);
|
||||
// In the overlap only the top square shows through: half blue, half white, no red.
|
||||
@@ -1031,6 +1149,7 @@ mod tests {
|
||||
let mut inner = item(Path::rect(0.0, 0.0, 12.0, 4.0), Paint::Solid(Rgba::BLACK));
|
||||
inner.group = Some(1);
|
||||
let nested = DisplayList {
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![inner],
|
||||
clip_parents: vec![],
|
||||
groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, anicraft_doc::Group { parent: Some(0), alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }],
|
||||
@@ -1044,7 +1163,7 @@ mod tests {
|
||||
// Spanning several render bands changes nothing.
|
||||
let mut tall = item(Path::rect(0.0, 0.0, 4.0, 100.0), Paint::Solid(Rgba::BLACK));
|
||||
tall.group = Some(0);
|
||||
let (t, _) = render(&DisplayList { items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap();
|
||||
let (t, _) = render(&DisplayList { clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap();
|
||||
assert!((0..100).all(|y| near(t.pixel(1, y).unwrap(), [0.75, 0.75, 0.75, 1.0])));
|
||||
}
|
||||
|
||||
@@ -1074,7 +1193,7 @@ mod tests {
|
||||
inner.masks = Some(1);
|
||||
let mut lost = clipped.clone();
|
||||
lost.clip = Some(2);
|
||||
let dl = DisplayList { items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() };
|
||||
let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
let (_, rst) = render(&dl, &view(16, 16)).unwrap();
|
||||
assert_eq!((st.drawn, st.edges, st.pixels_touched), (rst.drawn, rst.edges, rst.pixels_touched));
|
||||
@@ -1087,7 +1206,7 @@ mod tests {
|
||||
let mut grouped = sq.clone();
|
||||
grouped.group = Some(1);
|
||||
let g = |parent, alpha| anicraft_doc::Group { parent, alpha, blend: BlendMode::Multiply, filters: Default::default(), clip: None };
|
||||
let dl = DisplayList { items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] };
|
||||
let (scene, _) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
assert!(scene.fills.iter().all(|f| f.group == Some(1)));
|
||||
assert_eq!((scene.groups[1].chain.clone(), scene.groups[0].alpha, scene.groups[1].alpha, scene.groups[1].blend), (vec![0, 1], 1.0, 1.0, BlendMode::Multiply));
|
||||
@@ -1129,7 +1248,7 @@ mod tests {
|
||||
let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
|
||||
clipped.clip = Some(0);
|
||||
let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK));
|
||||
let (pm, st) = render(&DisplayList { items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap();
|
||||
let (pm, st) = render(&DisplayList { clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap();
|
||||
assert_eq!(st.drawn, 1);
|
||||
assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0);
|
||||
}
|
||||
@@ -1144,11 +1263,11 @@ mod tests {
|
||||
inner.masks = Some(1);
|
||||
let items = vec![fill, outer, inner];
|
||||
// Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives.
|
||||
let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm));
|
||||
// A parent link pointing forward (malformed) or out of range masks everything out.
|
||||
for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] {
|
||||
let (pm, _) = render(&DisplayList { items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
assert_eq!(alpha_sum(&pm), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -1370,7 +1489,7 @@ mod tests {
|
||||
let bg = item(Path::rect(0.0, 0.0, 20.0, 10.0), Paint::Solid(Rgba::new(0.5, 0.5, 1.0, 1.0)));
|
||||
let mut top = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0)));
|
||||
top.group = Some(0);
|
||||
let dl = DisplayList { items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] };
|
||||
let (pm, _) = render(&dl, &View { background: Some(Rgba::WHITE), ..view(20, 10) }).unwrap();
|
||||
let p = pm.pixel(5, 5).unwrap();
|
||||
assert!((p[0] - 0.5).abs() < 1e-3 && p[1].abs() < 1e-3 && p[2].abs() < 1e-3, "red × lavender: {p:?}");
|
||||
|
||||
@@ -656,7 +656,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa
|
||||
items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() });
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(DisplayList { items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() })
|
||||
std::borrow::Cow::Owned(DisplayList { clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -477,10 +477,10 @@ mod tests {
|
||||
let mut b = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::IDENTITY }));
|
||||
b.image = Some(px);
|
||||
b.color = ColorTransform::alpha(0.5);
|
||||
let svg = to_svg(&DisplayList { items: vec![b.clone()], ..Default::default() }, &stage());
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![b.clone()], ..Default::default() }, &stage());
|
||||
assert!(svg.contains("fill-opacity=\"0.5\"") && !svg.contains("feColorMatrix"), "{svg}");
|
||||
b.color = ColorTransform { mul: [-1.0, 0.5, 1.0, 0.8], add: [1.0, 0.25, 0.0, 0.1] };
|
||||
let svg = to_svg(&DisplayList { items: vec![b], ..Default::default() }, &stage());
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![b], ..Default::default() }, &stage());
|
||||
assert!(svg.contains("<feColorMatrix type=\"matrix\" values=\"-1 0 0 0 1 0 0.5 0 0 0.25 0 0 1 0 0 0 0 0 0.8 0.1\"/>"), "{svg}");
|
||||
assert!(svg.contains("filter=\"url(#cm") && !svg.contains("fill-opacity"), "{svg}");
|
||||
}
|
||||
@@ -492,7 +492,7 @@ mod tests {
|
||||
a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0));
|
||||
a.color = ColorTransform::alpha(0.5);
|
||||
a.fill_rule = FillRule::EvenOdd;
|
||||
let svg = to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(svg.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\" viewBox=\"0 0 100 50\">"));
|
||||
assert!(svg.contains("<rect width=\"100\" height=\"50\" fill=\"#ffffff\"/>"), "background");
|
||||
assert!(svg.contains("d=\"M5 7L25 7L25 27L5 27Z\" fill=\"#ff0000\" fill-opacity=\"0.5\" fill-rule=\"evenodd\""), "{svg}");
|
||||
@@ -507,7 +507,7 @@ mod tests {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None);
|
||||
a.transform = Affine::scale(2.0, 2.0);
|
||||
a.stroke = Some(st);
|
||||
to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage())
|
||||
to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage())
|
||||
};
|
||||
// The default style is written as before: round, no dashes.
|
||||
let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0));
|
||||
@@ -527,7 +527,7 @@ mod tests {
|
||||
fn variable_width_strokes_are_written_as_filled_outlines() {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000))));
|
||||
a.stroke = Some(Stroke::new(Rgba::hex(0x0000ff), 6.0).with_profile(anicraft_doc::ProfilePreset::TaperBoth.profile()));
|
||||
let svg = to_svg(&DisplayList { items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(!svg.contains("stroke-width"), "no SVG stroke: {svg}");
|
||||
assert!(svg.contains("fill=\"#0000ff\""), "the outline is filled in the stroke colour");
|
||||
assert!(svg.contains("fill=\"#ff0000\""), "the shape's own fill stays");
|
||||
@@ -544,7 +544,7 @@ mod tests {
|
||||
outer.masks = Some(0);
|
||||
let mut inner = item(Path::ellipse(25.0, 25.0, 10.0, 10.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
inner.masks = Some(1);
|
||||
let svg = to_svg(&DisplayList { items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage());
|
||||
assert!(svg.contains("gradientTransform=\"matrix(1 0 0 1 20 0)\" x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\""), "{svg}");
|
||||
assert!(svg.contains("<stop offset=\"1\" stop-color=\"#ffffff\" stop-opacity=\"0.25\"/>"));
|
||||
assert!(svg.contains("<clipPath id=\"c1\" clipPathUnits=\"userSpaceOnUse\" clip-path=\"url(#c0)\">"), "nested clip");
|
||||
@@ -566,7 +566,7 @@ mod tests {
|
||||
let clear = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::TRANSPARENT)));
|
||||
let mut lost = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
lost.clip = Some(7);
|
||||
let svg = to_svg(&DisplayList { items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage());
|
||||
assert_eq!(svg.matches("<path").count(), 1, "{svg}");
|
||||
assert!(svg.contains("<clipPath id=\"c0\" clipPathUnits=\"userSpaceOnUse\"></clipPath>"), "a malformed clip clips everything");
|
||||
assert!(!svg.contains("NaN") && !svg.contains("inf"));
|
||||
@@ -599,7 +599,7 @@ mod group_tests {
|
||||
image: None,
|
||||
smooth: true,
|
||||
};
|
||||
let dl = DisplayList { items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let svg = to_svg(&dl, &Stage { width: 4, height: 4, fps: 24.0, background: Rgba::WHITE });
|
||||
assert!(svg.contains("<g opacity=\"0.5\">") && svg.contains("<g opacity=\"0.25\">"), "{svg}");
|
||||
assert_eq!(svg.matches("<g ").count(), svg.matches("</g>").count(), "balanced");
|
||||
|
||||
Reference in new issue
Block a user