feat(render): warped bitmaps drawn through their mesh in the oracle, GPU parity (M7)

This commit is contained in:
Tanish Manku committed 2026-11-12 19:52:31 -07:00
1 parent a9e48b1184
commit 7a89c79d4b
7 files changed
+302 -3

No files matched your search

+1
View File
@@ -444,6 +444,7 @@ impl GpuRenderer {
group: None,
image: None,
smooth: true,
warp: None,
};
let solid = |x: f32, c: Rgba| item(Path::rect(x, 2.0, 8.0, 16.0), Paint::Solid(c));
let mut bitmap = item(Path::rect(2.0, 18.0, 20.0, 2.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::scale(3.0, 1.0) });
+12 -1
View File
@@ -32,6 +32,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem {
group: None,
image: None,
smooth: true,
warp: None,
}
}
@@ -946,6 +947,16 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> {
let mut hard_tiled = bitmap_item(Path::ellipse(50.0, 40.0, 45.0, 35.0), &c, true, Affine::scale(4.0, 3.0));
hard_tiled.smooth = false;
out.push(("bitmaps without smoothing", list(vec![hard_tiled, hard]), view(100, 80, white)));
// Warped (ADR 0079): bent by three pins, folded a little, faded; the oracle's prepared image.
use anicraft_doc::warp::{Pin, PinId, Warp};
let pin = |id: u64, rest: (f32, f32), at: (f32, f32)| Pin { id: PinId(id), rest: Vec2::new(rest.0, rest.1), at: Vec2::new(at.0, at.1) };
let mut warp = Warp::new(Arc::new(Path::rect(0.0, 0.0, 40.0, 30.0)), 8);
warp.pins = vec![pin(1, (2.0, 15.0), (6.0, 20.0)), pin(2, (20.0, 15.0), (24.0, 14.0)), pin(3, (38.0, 15.0), (52.0, 40.0))];
let mut bent = bitmap_item(warp.outline().as_ref().clone(), &c, false, Affine::IDENTITY);
bent.warp = warp.mesh().map(Arc::new);
bent.transform = Affine::scale(1.4, 1.4);
bent.color = ColorTransform::alpha(0.8);
out.push(("warped bitmap", list(vec![bent]), view(90, 72, white)));
out
}
@@ -1100,7 +1111,7 @@ fn filtered_sample() -> anicraft_doc::Document {
}
}
}
let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero };
let shape = anicraft_doc::Shape { path: Arc::new(Path::rect(0.0, 0.0, 1280.0, 300.0)), merge: false, fill: Some(Paint::Bitmap { bitmap: anicraft_doc::BitmapId(77), repeat: true, matrix: Affine::scale(5.0, 5.0) }), stroke: None, fill_rule: FillRule::NonZero, warp: None };
let sky = anicraft_doc::Element { id: ElementId(9_100), name: "sky".into(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(shape) };
let frames = doc.frame_count();
let mut k = anicraft_doc::Keyframe::new(0, frames);
+19 -1
View File
@@ -12,6 +12,7 @@ pub mod hairline;
pub mod html;
pub mod lottie;
pub mod svg;
pub mod warp;
use anicraft_doc::{BlendMode, ColorTransform, DisplayItem, DisplayList, Document, MaskMode, Paint, Rgba, evaluate};
use anicraft_geom::{Affine, FillRule, Rect, Vec2};
@@ -876,7 +877,19 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect, soft: bool) -> Vec
});
if let Some(fill) = &item.fill {
let polys: Vec<Vec<Vec2>> = lines.into_iter().map(|l| l.points).collect();
push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref()).smoothed(item.smooth));
let shader = match (&item.warp, fill, &item.image) {
// A warped bitmap (ADR 0079): the image drawn through its mesh, prepared once over
// the fill's pixels and shown one image pixel per surface pixel.
(Some(mesh), Paint::Bitmap { repeat, matrix, .. }, Some(px)) => {
let prepared = pixel_bounds(&polys, surface).and_then(|b| Some((warp::texture(mesh, &m, matrix, *repeat, px, item.smooth, b)?, b)));
match prepared {
Some((tex, b)) => Shader::Bitmap { inv: Affine::translate(-(b.x0 as f32), -(b.y0 as f32)), pixels: tex, repeat: false, fx: item.color, smooth: false },
None => Shader::Solid([0.0; 4]),
}
}
_ => Shader::new(fill, &m, &item.color, item.image.as_ref()).smoothed(item.smooth),
};
push(polys, item.fill_rule, shader);
}
if let Some((polys, shader)) = stroke {
push(polys, FillRule::NonZero, shader);
@@ -965,6 +978,7 @@ mod tests {
group: None,
image: None,
smooth: true,
warp: None,
}
}
@@ -1497,3 +1511,7 @@ mod tests {
assert!((q[2] - 1.0).abs() < 1e-3, "outside the group unchanged: {q:?}");
}
}
#[cfg(test)]
#[path = "warp_tests.rs"]
mod warp_tests;
+1 -1
View File
@@ -171,7 +171,7 @@ impl Shader {
/// A sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), bilinear when
/// `smooth`, else the pixel `q` is in, with the colour effect applied and premultiplied.
/// Outside a non-repeating bitmap: transparent.
fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorTransform) -> Premul {
pub(crate) fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorTransform) -> Premul {
let (w, h) = (px.width as f32, px.height as f32);
if !(q.x.is_finite() && q.y.is_finite()) || w < 1.0 || h < 1.0 {
return [0.0; 4];
+2
View File
@@ -531,6 +531,7 @@ mod tests {
group: None,
image: None,
smooth: true,
warp: None,
}
}
@@ -719,6 +720,7 @@ mod group_tests {
group: g,
image: None,
smooth: true,
warp: 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 });
+138
View File
@@ -0,0 +1,138 @@
//! Warped bitmaps (ADR 0079): an image drawn through the triangles of its warp mesh.
//!
//! The oracle prepares a warped bitmap fill as an image of its own, in surface pixels over the
//! fill's bounds: each mesh triangle carries its pixels' centres back to the image as drawn
//! (the triangle's affine map, exact) and samples it there, bilinear with Allow Smoothing,
//! else the nearest pixel, exactly as an unwarped bitmap is sampled. Triangles are written in
//! mesh order, so where the mesh folds over itself the later one shows. A pixel at the
//! outline's edge whose centre falls in no triangle takes its neighbour's colour, so the
//! outline's antialiasing has a colour to fade. The fill then draws that image as a
//! [`Shader::Bitmap`](crate::paint::Shader) of one image pixel per surface pixel, nearest, with
//! the item's colour effect: the GPU stage takes the very same prepared fill, so the two agree.
//!
//! Every pixel is written by one task (rows in bands, in parallel), so the result is the same
//! whatever the thread count.
use crate::paint::sample;
use crate::raster::IRect;
use anicraft_doc::{ColorTransform, Pixels, warp::WarpMesh};
use anicraft_geom::{Affine, Vec2};
use rayon::prelude::*;
use std::sync::Arc;
/// Most pixels a warped bitmap's prepared image may have (256 MB of RGBA).
pub const MAX_TEXTURE_PIXELS: usize = 1 << 26;
/// Rows per parallel band.
const BAND: usize = 32;
/// One triangle in surface pixels: its corners, the map from a pixel back to the image, and
/// the rows it touches.
struct Tri {
p: [Vec2; 3],
to_image: Affine,
y0: i32,
y1: i32,
}
/// The image of the bitmap `px` (its fill matrix `matrix`, tiled when `repeat`) as `mesh`
/// bends it under `m` (local → surface pixels), over `b` (surface pixels): straight RGBA8,
/// `b`'s size, transparent where no triangle is. `None` when it can't be drawn (a collapsed
/// fill matrix, an empty or oversized area).
pub fn texture(mesh: &WarpMesh, m: &Affine, matrix: &Affine, repeat: bool, px: &Pixels, smooth: bool, b: IRect) -> Option<Arc<Pixels>> {
let (w, h) = (b.width(), b.height());
if w == 0 || h == 0 || w.checked_mul(h)? > MAX_TEXTURE_PIXELS {
return None;
}
let to_image = matrix.inverse()?;
let corner = |pts: &[Vec2], i: u32| pts.get(i as usize).copied();
let tris: Vec<Tri> = mesh
.tris
.iter()
.filter_map(|t| {
let [s0, s1, s2] = [corner(&mesh.shown, t[0])?, corner(&mesh.shown, t[1])?, corner(&mesh.shown, t[2])?].map(|v| m.apply(v));
let [r0, r1, r2] = [corner(&mesh.rest, t[0])?, corner(&mesh.rest, t[1])?, corner(&mesh.rest, t[2])?];
// Surface → local as drawn: R · S⁻¹ (S and R take the unit triangle to each).
let s = Affine { m: [s1.x - s0.x, s1.y - s0.y, s2.x - s0.x, s2.y - s0.y, s0.x, s0.y] };
let r = Affine { m: [r1.x - r0.x, r1.y - r0.y, r2.x - r0.x, r2.y - r0.y, r0.x, r0.y] };
let map = to_image.mul(&r.mul(&s.inverse()?));
if !map.is_finite() {
return None;
}
let (lo, hi) = (s0.y.min(s1.y).min(s2.y), s0.y.max(s1.y).max(s2.y));
if !(lo.is_finite() && hi.is_finite()) {
return None;
}
Some(Tri { p: [s0, s1, s2], to_image: map, y0: (lo.floor() as i32).max(b.y0), y1: (hi.ceil() as i32 + 1).min(b.y1) })
})
.filter(|t| t.y0 < t.y1)
.collect();
let fx = ColorTransform::default();
let mut rgba = vec![0u8; w * h * 4];
let mut set = vec![false; w * h];
rgba.par_chunks_mut(w * 4 * BAND).zip(set.par_chunks_mut(w * BAND)).enumerate().for_each(|(band, (out, seen))| {
let top = b.y0 + (band * BAND) as i32;
let rows = seen.len() / w;
let bottom = top + rows as i32;
for t in tris.iter().filter(|t| t.y0 < bottom && t.y1 > top) {
fill_tri(t, b, top, bottom, w, px, repeat, smooth, &fx, out, seen);
}
});
bleed(&mut rgba, &set, w, h);
Some(Arc::new(Pixels { width: w as u32, height: h as u32, rgba }))
}
/// Writes the pixels of rows `top..bottom` whose centres `t` holds.
#[allow(clippy::too_many_arguments)]
fn fill_tri(t: &Tri, b: IRect, top: i32, bottom: i32, w: usize, px: &Pixels, repeat: bool, smooth: bool, fx: &ColorTransform, out: &mut [u8], seen: &mut [bool]) {
let [a, p1, p2] = t.p;
let area = (p1 - a).cross(p2 - a);
if area.abs() <= 1e-9 || area.is_nan() {
return;
}
// Edge functions, oriented so the inside is positive; centres on an edge count (a hair of
// slack so the triangles of a cell leave no crack between them).
let sign = area.signum();
let edges = [(a, p1), (p1, p2), (p2, a)];
let slack = -1e-4 * area.abs();
let (xs0, xs1) = (a.x.min(p1.x).min(p2.x), a.x.max(p1.x).max(p2.x));
let x0 = (xs0.floor() as i32).max(b.x0);
let x1 = (xs1.ceil() as i32 + 1).min(b.x1);
for y in t.y0.max(top)..t.y1.min(bottom) {
let cy = y as f32 + 0.5;
let row = (y - top) as usize;
for x in x0..x1 {
let c = Vec2::new(x as f32 + 0.5, cy);
if edges.iter().any(|&(e0, e1)| sign * (e1 - e0).cross(c - e0) < slack) {
continue;
}
let i = row * w + (x - b.x0) as usize;
let s = sample(px, t.to_image.apply(c), repeat, smooth, fx);
let a = s[3];
let straight = |v: f32| if a > 0.0 { (v / a).clamp(0.0, 1.0) } else { 0.0 };
let q = |v: f32| (v * 255.0 + 0.5) as u8;
if let (Some(o), Some(flag)) = (out.get_mut(i * 4..i * 4 + 4), seen.get_mut(i)) {
o.copy_from_slice(&[q(straight(s[0])), q(straight(s[1])), q(straight(s[2])), q(a.clamp(0.0, 1.0))]);
*flag = true;
}
}
}
}
/// Gives each pixel no triangle wrote the colour of a written neighbour (left, right, up,
/// down, the first there is), so the outline's antialiased edge has a colour to fade.
fn bleed(rgba: &mut [u8], set: &[bool], w: usize, h: usize) {
let src = rgba.to_vec();
for y in 0..h {
for x in 0..w {
let i = y * w + x;
if set.get(i).copied().unwrap_or(true) {
continue;
}
let near = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)];
let Some(n) = near.into_iter().flatten().find(|&n| set.get(n).copied().unwrap_or(false)) else { continue };
if let (Some(from), Some(to)) = (src.get(n * 4..n * 4 + 4), rgba.get_mut(i * 4..i * 4 + 4)) {
to.copy_from_slice(from);
}
}
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Warped bitmaps in the oracle (ADR 0079): analytic checks against the same image moved by a
//! plain transform.
use super::*;
use anicraft_doc::warp::{Pin, PinId, Warp};
use anicraft_doc::{BitmapId, ElementId, LayerId, Pixels, Shape};
use anicraft_geom::Path;
use std::sync::Arc;
/// A 32 × 16 image: a horizontal red ramp, green rows, blue on every fourth column.
fn image() -> Arc<Pixels> {
let (w, h) = (32u32, 16u32);
let mut rgba = Vec::new();
for y in 0..h {
for x in 0..w {
rgba.extend_from_slice(&[(x * 8) as u8, (y * 16) as u8, if x % 4 == 0 { 255 } else { 0 }, 255]);
}
}
Arc::new(Pixels { width: w, height: h, rgba })
}
fn bitmap_shape() -> Shape {
Shape::filled(Path::rect(0.0, 0.0, 32.0, 16.0), Paint::Bitmap { bitmap: BitmapId(1), repeat: false, matrix: Affine::IDENTITY })
}
/// The display item of `shape` (its warp's mesh when it bends it), placed by `transform`.
fn item(shape: &Shape, transform: Affine, smooth: bool) -> DisplayItem {
DisplayItem {
path: shape.path.clone(),
transform,
fill: shape.fill.clone(),
stroke: None,
fill_rule: FillRule::NonZero,
color: ColorTransform::IDENTITY,
layer: LayerId(0),
element: ElementId(0),
outline: None,
clip: None,
masks: None,
guide: false,
group: None,
image: Some(image()),
smooth,
warp: shape.live_warp().filter(|w| !w.at_rest()).and_then(Warp::mesh).map(Arc::new),
}
}
fn draw(items: Vec<DisplayItem>, w: u32, h: u32) -> Pixmap {
let dl = DisplayList { items, ..Default::default() };
let view = View { transform: Affine::IDENTITY, width: w, height: h, background: None };
render(&dl, &view).map(|(p, _)| p).unwrap_or_else(|_| Pixmap { width: 0, height: 0, data: Vec::new() })
}
fn pin(id: u64, rest: (f32, f32), at: (f32, f32)) -> Pin {
Pin { id: PinId(id), rest: anicraft_geom::Vec2::new(rest.0, rest.1), at: anicraft_geom::Vec2::new(at.0, at.1) }
}
fn warped(pins: Vec<Pin>, resolution: u32) -> Shape {
let mut s = bitmap_shape();
let mut w = Warp::new(s.path.clone(), resolution);
w.pins = pins;
s.set_warp(w);
s
}
/// Largest channel difference over pixels both images cover fully (alpha 1 in `a`).
fn worst(a: &Pixmap, b: &Pixmap) -> f32 {
a.data.iter().zip(&b.data).filter(|(p, _)| p[3] > 0.999).map(|(p, q)| (0..4).map(|k| (p[k] - q[k]).abs()).fold(0.0, f32::max)).fold(0.0, f32::max)
}
#[test]
fn a_warp_that_only_moves_draws_the_image_moved() {
// One pin moved: the whole image moves with it, exactly as a translated bitmap draws.
let s = warped(vec![pin(1, (16.0, 8.0), (26.0, 13.0))], 8);
for smooth in [true, false] {
let got = draw(vec![item(&s, Affine::IDENTITY, smooth)], 64, 40);
let want = draw(vec![item(&bitmap_shape(), Affine::translate(10.0, 5.0), smooth)], 64, 40);
let covered = got.data.iter().filter(|p| p[3] > 0.999).count();
assert_eq!(covered, 32 * 16, "the image's pixels, no more and no fewer");
assert!(worst(&got, &want) <= 1.0 / 255.0 + 1e-6, "smooth {smooth}: {}", worst(&got, &want));
}
}
#[test]
fn a_warp_that_turns_draws_the_image_turned() {
// Two pins turned a quarter turn about the image's centre: every triangle turns with them.
let c = (16.0, 8.0);
let turn = |(x, y): (f32, f32)| (c.0 - (y - c.1) + 24.0, c.1 + (x - c.0) + 16.0);
let s = warped(vec![pin(1, (4.0, 8.0), turn((4.0, 8.0))), pin(2, (28.0, 8.0), turn((28.0, 8.0)))], 8);
let xf = Affine::translate(c.0 + 24.0, c.1 + 16.0).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)).mul(&Affine::translate(-c.0, -c.1));
let got = draw(vec![item(&s, Affine::IDENTITY, false)], 80, 64);
let want = draw(vec![item(&bitmap_shape(), xf, false)], 80, 64);
assert!(got.data.iter().filter(|p| p[3] > 0.999).count() >= 32 * 16 - 64);
assert!(worst(&got, &want) <= 1.0 / 255.0 + 1e-6, "{}", worst(&got, &want));
}
#[test]
fn a_bent_image_has_no_cracks_and_is_deterministic() {
let s = warped(vec![pin(1, (2.0, 8.0), (2.0, 8.0)), pin(2, (16.0, 8.0), (16.0, 8.0)), pin(3, (30.0, 8.0), (34.0, 20.0))], 12);
let a = draw(vec![item(&s, Affine::scale(3.0, 3.0), true)], 140, 110);
let b = draw(vec![item(&s, Affine::scale(3.0, 3.0), true)], 140, 110);
assert_eq!(a.data, b.data);
// Inside the bent outline every pixel is opaque: the triangles leave no seam.
let outline = s.path.clone();
let m = Affine::scale(3.0, 3.0);
let mut inside = 0;
for y in 0..110 {
for x in 0..140 {
let p = anicraft_geom::Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
if outline.contains(p, &m, FillRule::NonZero) && outline.distance_to_edge(p, &m) > 1.0 {
inside += 1;
let px = a.data[y * 140 + x];
assert!(px[3] > 0.999, "a crack at ({x}, {y}): {px:?}");
}
}
}
assert!(inside > 3000);
}
#[test]
fn the_gpu_stage_gets_the_same_prepared_fill() {
// `prepare_scene` hands the warped bitmap over as a plain image shader: what the GPU draws.
let s = warped(vec![pin(1, (16.0, 8.0), (20.0, 8.0)), pin(2, (2.0, 2.0), (2.0, 2.0))], 6);
let dl = DisplayList { items: vec![item(&s, Affine::IDENTITY, true)], ..Default::default() };
let view = View { transform: Affine::IDENTITY, width: 48, height: 24, background: None };
let (scene, _) = prepare_scene(&dl, &view).unwrap_or_else(|_| (Scene { fills: Vec::new(), clips: Vec::new(), groups: Vec::new(), layers: Vec::new() }, RenderStats::default()));
assert_eq!(scene.fills.len(), 1);
assert!(matches!(&scene.fills[0].shader, paint::Shader::Bitmap { smooth: false, repeat: false, .. }));
}