diff --git a/crates/effects/src/migrate.rs b/crates/effects/src/migrate.rs index 146660353..9db9495d0 100644 --- a/crates/effects/src/migrate.rs +++ b/crates/effects/src/migrate.rs @@ -171,6 +171,8 @@ pub fn legacy_default(effect: &str, param: &str) -> Option { // Utility: Cineon Converter version 1, where Gamma 1.7 gave linear output // (`crate::utility::cineon_gamma`). ("ec.utility.cineon", "version") => Value::Scalar(1.0), + // Distort: Puppet rigs keep the solve and drawing they were made with (#2866). + ("ec.distort.puppet", "solverVersion") => Value::Enum(crate::puppet::SOLVER_ORIGINAL), _ => return None, }) } diff --git a/crates/effects/src/puppet.rs b/crates/effects/src/puppet.rs index 6ec2ce5ba..9f3babaf9 100644 --- a/crates/effects/src/puppet.rs +++ b/crates/effects/src/puppet.rs @@ -9,15 +9,23 @@ //! In Front, Extent; hidden pin type and rest position) //! ``` //! -//! Each frame the mesh is built from the effect's input alpha (see [`mesh`]; cached by content), -//! pins are attached to their nearest mesh vertices at rest, the as-rigid-as-possible solver -//! ([`arap`]) moves the vertices, and the input is texture-mapped through the deformed -//! triangles (bilinear sampling, 2×2 coverage anti-aliasing on the outline, Overlap pins' -//! In Front deciding which triangles draw on top). +//! Each frame the mesh is built from the effect's input alpha (see [`mesh`]; cached by content). +//! A moving pin holds the very point under it at rest, a point inside a triangle of the mesh (see +//! [`held_point`]); a pin on a vertex holds that vertex, and one off the mesh its nearest vertex at +//! the same offset. Advanced and Bend pins also turn and scale the edges at their nearest vertex. +//! The as-rigid-as-possible solver ([`arap`]) moves the vertices (one solve, cached, serves both +//! drawing and the overlay), and the input is texture-mapped through the deformed mesh, split +//! finer along a smooth interpolation of the solve (bilinear sampling, averaged where the mesh +//! squeezes the image; 16 coverage samples per pixel for the outline; Overlap pins' In Front +//! deciding which triangles draw on top). +//! +//! Instances saved with the first solve keep it ([`SOLVER_VERSION`], [`legacy`]). pub mod arap; +mod legacy; pub mod mesh; +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use effectcraft_keyframe::Value; @@ -32,6 +40,20 @@ pub use mesh::{Mesh, MeshOpts}; /// Effect id of the Puppet effect. pub const ID: &str = "ec.distort.puppet"; +/// The hidden parameter saving which solve and drawing an instance uses, so a rig keeps its look +/// when the solver changes. Instances saved before it existed open with [`SOLVER_ORIGINAL`] +/// (`migrate::legacy_default`); new ones get [`SOLVER_CURRENT`]. +pub const SOLVER_VERSION: &str = "solverVersion"; +/// The first solve: pins hold their nearest vertex, straight triangles (see [`legacy`]). +pub const SOLVER_ORIGINAL: u32 = 1; +/// Pins hold the point under them, the area-keeping solve, smooth drawing. +pub const SOLVER_CURRENT: u32 = 2; + +/// Whether `params` are of an instance on the first solve. +fn original(params: &Params) -> bool { + params.get(SOLVER_VERSION).map(Value::as_enum) == Some(SOLVER_ORIGINAL) +} + /// Puppet pin types (the five Puppet tools). #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum PinKind { @@ -90,7 +112,10 @@ pub fn specs() -> Vec { id: ID, name: "Puppet", category: "Distort", - params: vec![p("refinement", "Mesh Rotation Refinement", Value::Scalar(20.0), slider(0.0, 100.0, 0.0, 100.0, 0))], + params: vec![ + p("refinement", "Mesh Rotation Refinement", Value::Scalar(20.0), slider(0.0, 100.0, 0.0, 100.0, 0)), + p(SOLVER_VERSION, "Solver Version", Value::Enum(SOLVER_CURRENT), ParamUi::Hidden), + ], render, gpu: false, float: true, @@ -314,8 +339,43 @@ fn centroid(mesh: &Mesh, t: &[usize; 3]) -> [f64; 2] { [(v[t[0]][0] + v[t[1]][0] + v[t[2]][0]) / 3.0, (v[t[0]][1] + v[t[1]][1] + v[t[2]][1]) / 3.0] } +/// Solver rounds for the Mesh Rotation Refinement parameter. The default of 20 converges to +/// about 1 % of the mesh's edge length on a far drag. +fn refinement_rounds(params: &Params) -> usize { + (params.get("refinement").map(Value::as_f64).unwrap_or(20.0) * 2.0).round().clamp(0.0, 200.0) as usize +} + /// Solve the deformation of `mesh` for `pins` (layer space). Returns deformed vertices. pub fn solve(mesh: &Mesh, pins: &[Pin], refine: usize) -> Vec<[f64; 2]> { + solve_with(mesh, pins, refine, arap::LIMITS) +} + +/// Solves made lately: (mesh, pins, rounds, deformed vertices). Drawing a frame and its overlay +/// (the Puppet tools, `puppet.info`, adding a pin) ask for the same one. +type Solved = (Arc, Vec, usize, Arc>); +static SOLVES: Mutex> = Mutex::new(Vec::new()); +const SOLVES_KEPT: usize = 8; + +/// [`solve`], made once for the same mesh, pins and rounds. +pub fn solve_shared(mesh: &Arc, pins: &[Pin], refine: usize) -> Arc> { + let same = |s: &Solved| (Arc::ptr_eq(&s.0, mesh) || *s.0 == **mesh) && s.1 == pins && s.2 == refine; + if let Ok(c) = SOLVES.lock() + && let Some(s) = c.iter().find(|s| same(s)) + { + return s.3.clone(); + } + let def = Arc::new(solve(mesh, pins, refine)); + if let Ok(mut c) = SOLVES.lock() { + c.retain(|s| !same(s)); + c.push((mesh.clone(), pins.to_vec(), refine, def.clone())); + if c.len() > SOLVES_KEPT { + c.remove(0); + } + } + def +} + +fn solve_with(mesh: &Mesh, pins: &[Pin], refine: usize, limits: arap::Limits) -> Vec<[f64; 2]> { let mut h = arap::Handles::default(); let mut adj: Vec> = vec![vec![]; mesh.verts.len()]; for t in &mesh.tris { @@ -332,8 +392,17 @@ pub fn solve(mesh: &Mesh, pins: &[Pin], refine: usize) -> Vec<[f64; 2]> { for p in pins { let Some(v) = nearest(&mesh.verts, p.rest) else { continue }; let r = mesh.verts[v]; - if p.kind.moves() && used.insert(v) { - h.fixed.push((v, [p.position[0] + r[0] - p.rest[0], p.position[1] + r[1] - p.rest[1]])); + if p.kind.moves() { + // The pin holds the very point under it. A pin on a vertex holds that vertex, and one + // off the mesh its nearest vertex at the same offset. + match held_point(mesh, p.rest) { + Some((verts, bary)) => h.points.push(arap::PointTarget { verts, bary, position: p.position }), + None => { + if used.insert(v) { + h.fixed.push((v, [p.position[0] + r[0] - p.rest[0], p.position[1] + r[1] - p.rest[1]])); + } + } + } } if matches!(p.kind, PinKind::Advanced | PinKind::Bend) { let (s, c) = p.rotation.to_radians().sin_cos(); @@ -344,11 +413,13 @@ pub fn solve(mesh: &Mesh, pins: &[Pin], refine: usize) -> Vec<[f64; 2]> { } } } - if h.fixed.is_empty() && h.edges.is_empty() { - return mesh.verts.clone(); + if h.fixed.is_empty() && h.points.is_empty() { + // A Bend pin with nothing held turns the mesh about itself. + let Some(e) = h.edges.first() else { return mesh.verts.clone() }; + h.fixed.push((e.i, mesh.verts[e.i])); } let w = starch_weights(mesh, pins); - arap::deform(&mesh.verts, &mesh.tris, &w, &h, refine) + arap::deform_with(&mesh.verts, &mesh.tris, &w, &h, refine, limits) } /// Per-triangle depth from Overlap pins (higher draws in front). @@ -369,6 +440,24 @@ pub fn depths(mesh: &Mesh, pins: &[Pin]) -> Vec { .collect() } +/// The triangle of the rest mesh over `p`, with `p`'s barycentric coordinates in it. +fn locate(mesh: &Mesh, p: [f64; 2]) -> Option<([usize; 3], [f64; 3])> { + let v = &mesh.verts; + mesh.tris.iter().find_map(|t| bary(v[t[0]], v[t[1]], v[t[2]], p).filter(|l| l.iter().all(|x| *x >= -1e-9)).map(|l| (*t, l))) +} + +/// The point a moving pin at `rest` holds, as a triangle and barycentric coordinates. `None` when it +/// holds a vertex instead: it's on one, or off the mesh. +pub fn held_point(mesh: &Mesh, rest: [f64; 2]) -> Option<([usize; 3], [f64; 3])> { + locate(mesh, rest).filter(|(_, bary)| bary.iter().all(|l| *l < 1.0 - 1e-6)) +} + +/// [`held_point`] for an instance with `params`: on the first solve every moving pin holds its +/// nearest vertex, so `None`. +pub fn held_point_in(params: &Params, mesh: &Mesh, rest: [f64; 2]) -> Option<([usize; 3], [f64; 3])> { + if original(params) { None } else { held_point(mesh, rest) } +} + /// Map a point of the deformed mesh back to rest space (barycentric through the triangle that /// contains it, or the nearest vertex's offset). pub fn unmap(mesh: &Mesh, deformed: &[[f64; 2]], p: [f64; 2]) -> [f64; 2] { @@ -407,102 +496,630 @@ fn bary(a: [f64; 2], b: [f64; 2], c: [f64; 2], p: [f64; 2]) -> Option<[f64; 3]> } fn render(ctx: &EffectCtx, buf: Buf) -> Buf { + if original(ctx.params) { + return legacy::render(ctx, buf); + } let meshes = parse(ctx.params); if meshes.is_empty() { return buf; } - let refine = (ctx.params.get("refinement").map(Value::as_f64).unwrap_or(20.0) / 10.0).round().clamp(0.0, 10.0) as usize; - // Triangles of every mesh in pixel space: (rest px, deformed px, depth). - let mut tris: Vec<([[f64; 2]; 3], [[f64; 2]; 3], f64)> = vec![]; + let refine = refinement_rounds(ctx.params); + // Triangles of every mesh in pixel space: (rest px, deformed px, draw order). + let mut tris: Vec<([[f64; 2]; 3], [[f64; 2]; 3], (f64, f64))> = vec![]; let px = |q: [f64; 2]| [q[0] * buf.scale + buf.offset[0], q[1] * buf.scale + buf.offset[1]]; for m in &meshes { let mesh = mesh_for(&buf, m); if mesh.tris.is_empty() { continue; } - let def = solve(&mesh, &m.pins, refine); + let def = solve_shared(&mesh, &m.pins, refine); let dep = depths(&mesh, &m.pins); - for (k, t) in mesh.tris.iter().enumerate() { - let r = [px(mesh.verts[t[0]]), px(mesh.verts[t[1]]), px(mesh.verts[t[2]])]; - let d = [px(def[t[0]]), px(def[t[1]]), px(def[t[2]])]; - tris.push((r, d, dep[k])); + // Sheets of one mesh that come to overlap stack by how far they were moved, so the sheet + // dragged over the rest stays whole instead of interleaving by triangle number. + let moved: Vec = mesh + .tris + .iter() + .map(|t| { + let (c, e) = (centroid(&mesh, t), [(def[t[0]][0] + def[t[1]][0] + def[t[2]][0]) / 3.0, (def[t[0]][1] + def[t[1]][1] + def[t[2]][1]) / 3.0]); + (c[0] - e[0]).hypot(c[1] - e[1]) + }) + .collect(); + let smooth = smooth_mesh_holding(&mesh, &def, buf.scale, &held_points(&mesh, &m.pins)); + for (t, k) in smooth.tris.iter().zip(&smooth.parent) { + let r = [px(smooth.rest[t[0]]), px(smooth.rest[t[1]]), px(smooth.rest[t[2]])]; + let d = [px(smooth.deformed[t[0]]), px(smooth.deformed[t[1]]), px(smooth.deformed[t[2]])]; + tris.push((r, d, (dep[*k], moved[*k]))); } } if tris.is_empty() { return buf; } // Stable sort: back to front. - tris.sort_by(|a, b| a.2.total_cmp(&b.2)); + tris.sort_by(|a, b| a.2.0.total_cmp(&b.2.0).then(a.2.1.total_cmp(&b.2.1))); + let tris: Vec<_> = tris.into_iter().map(|(r, d, _)| (r, d)).collect(); rasterize(&buf, &tris) } -/// Texture-map `buf` through triangles (rest px → deformed px), back to front. -fn rasterize(buf: &Buf, tris: &[([[f64; 2]; 3], [[f64; 2]; 3], f64)]) -> Buf { - let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for (_, d, _) in tris { - for p in d { - x0 = x0.min(p[0]); - y0 = y0.min(p[1]); - x1 = x1.max(p[0]); - y1 = y1.max(p[1]); +/// The deformed mesh tessellated for drawing (see [`smooth_mesh`]). `parent` is the triangle of the +/// solver's mesh each small triangle came from. +#[derive(Clone, Debug, PartialEq)] +pub struct SmoothMesh { + pub rest: Vec<[f64; 2]>, + pub deformed: Vec<[f64; 2]>, + pub tris: Vec<[usize; 3]>, + pub parent: Vec, +} + +/// Longest the tessellated curve may stray from the true one, in buffer pixels. +const SMOOTH_TOLERANCE: f64 = 0.125; +/// Most small triangles a triangle of the mesh splits along an edge, and in all for one mesh. +const SMOOTH_MAX_SPLIT: usize = 16; +const SMOOTH_MAX_TRIS: usize = 100_000; + +/// Each vertex's deformation gradient: the area-weighted mean of its triangles'. +fn vertex_gradients(mesh: &Mesh, def: &[[f64; 2]]) -> Vec<[f64; 4]> { + let mut sum = vec![([0.0; 4], 0.0); mesh.verts.len()]; + for t in &mesh.tris { + let v = &mesh.verts; + let (e1, e2) = ([v[t[1]][0] - v[t[0]][0], v[t[1]][1] - v[t[0]][1]], [v[t[2]][0] - v[t[0]][0], v[t[2]][1] - v[t[0]][1]]); + let (f1, f2) = ([def[t[1]][0] - def[t[0]][0], def[t[1]][1] - def[t[0]][1]], [def[t[2]][0] - def[t[0]][0], def[t[2]][1] - def[t[0]][1]]); + let det = e1[0] * e2[1] - e2[0] * e1[1]; + if det.abs() < 1e-12 { + continue; } + let g = [ + (f1[0] * e2[1] - f2[0] * e1[1]) / det, + (f2[0] * e1[0] - f1[0] * e2[0]) / det, + (f1[1] * e2[1] - f2[1] * e1[1]) / det, + (f2[1] * e1[0] - f1[1] * e2[0]) / det, + ]; + let area = det.abs() * 0.5; + for i in t { + for (a, b) in sum[*i].0.iter_mut().zip(g) { + *a += area * b; + } + sum[*i].1 += area; + } + } + sum.into_iter().map(|(g, a)| if a > 0.0 { g.map(|x| x / a) } else { [1.0, 0.0, 0.0, 1.0] }).collect() +} + +/// The points the moving pins hold inside triangles (see [`held_point`]), for +/// [`smooth_mesh_holding`]. +fn held_points(mesh: &Mesh, pins: &[Pin]) -> Vec<([usize; 3], [f64; 3])> { + pins.iter().filter(|p| p.kind.moves()).filter_map(|p| held_point(mesh, p.rest)).collect() +} + +/// Most held points [`hold_points`] solves together exactly. The system over them is dense, so this +/// bounds one solve to `HOLD_EXACT_MAX²` values and about `HOLD_EXACT_MAX³` steps, however many +/// pins a rig has. +const HOLD_EXACT_MAX: usize = 128; +/// Passes over the points of a group too large to solve exactly (see [`hold_points`]). +const HOLD_SWEEPS: usize = 32; + +/// One held point's row of `A` (see [`hold_points`]): its triangle's vertices, their coefficients +/// `l_k (q − r_k)` (the same for x and y), and the offset to cancel. +type HoldRow = ([usize; 3], [[f64; 2]; 3], [f64; 2]); + +/// `a_i · a_j` for two rows of `A`: rows meet only through the vertices they share. +fn rows_meet(i: &HoldRow, j: &HoldRow) -> f64 { + let mut d = 0.0; + for (ki, vi) in i.0.iter().enumerate() { + for (kj, vj) in j.0.iter().enumerate() { + if vi == vj { + d += i.1[ki][0] * j.1[kj][0] + i.1[ki][1] * j.1[kj][1]; + } + } + } + d +} + +/// Bend the vertex gradients so the smoothed map takes each held point where the solve did: the +/// least change to the gradients that cancels the curve's offset from the linear map at every held +/// point at once. A point's offset is linear in its triangle's three gradients, so the change is +/// `Aᵀ y` with `A Aᵀ y` the offsets (points that share a vertex pull on the same gradient, and are +/// solved together rather than one after another). Points meet only through shared vertices, so +/// the system splits into groups of points linked that way, each solved on its own; a group of up +/// to [`HOLD_EXACT_MAX`] points exactly, a larger one by [`HOLD_SWEEPS`] passes that correct one +/// point at a time (each pass takes every point nearer its spot, towards the same answer), so the +/// work grows only linearly with the pin count. The map along an edge still depends only on its +/// two vertices, so the change leaves no cracks. +fn hold_points(mesh: &Mesh, grads: &mut [[f64; 4]], held: &[([usize; 3], [f64; 3])]) { + hold_points_within(mesh, grads, held, HOLD_EXACT_MAX); +} + +/// [`hold_points`] with groups of up to `max_exact` points solved exactly. Returns the most points +/// one dense system held. +fn hold_points_within(mesh: &Mesh, grads: &mut [[f64; 4]], held: &[([usize; 3], [f64; 3])], max_exact: usize) -> usize { + let rows: Vec = held + .iter() + .filter_map(|(t, l)| { + let v = [*mesh.verts.get(t[0])?, *mesh.verts.get(t[1])?, *mesh.verts.get(t[2])?]; + let g = [*grads.get(t[0])?, *grads.get(t[1])?, *grads.get(t[2])?]; + let q = [0, 1].map(|c| l[0] * v[0][c] + l[1] * v[1][c] + l[2] * v[2][c]); + let a = [0, 1, 2].map(|k| [l[k] * (q[0] - v[k][0]), l[k] * (q[1] - v[k][1])]); + let o = [0, 1].map(|c| -(0..3).map(|k| a[k][0] * g[k][2 * c] + a[k][1] * g[k][2 * c + 1]).sum::()); + let norm: f64 = a.iter().map(|x| x[0] * x[0] + x[1] * x[1]).sum(); + (norm >= 1e-12 && o.iter().all(|x| x.is_finite())).then_some((*t, a, o)) + }) + .collect(); + // Groups of points linked through shared vertices: union-find, each link pointing to a lower + // point, with each vertex's first point. + fn find(root: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = root.get(i) + && p != i + { + let up = root.get(p).copied().unwrap_or(p); + if let Some(r) = root.get_mut(i) { + *r = up; + } + i = up; + } + i + } + let mut root: Vec = (0..rows.len()).collect(); + let mut first: HashMap = HashMap::new(); + for (i, (t, _, _)) in rows.iter().enumerate() { + for v in t { + let j = *first.entry(*v).or_insert(i); + let (a, b) = (find(&mut root, i), find(&mut root, j)); + if let Some(r) = root.get_mut(a.max(b)) { + *r = a.min(b); + } + } + } + let mut groups: Vec> = vec![vec![]; rows.len()]; + for (i, row) in rows.iter().enumerate() { + let r = find(&mut root, i); + if let Some(g) = groups.get_mut(r) { + g.push(row); + } + } + // Groups share no vertex, so each changes gradients no other group reads. + let mut largest = 0; + for group in groups.iter().filter(|g| !g.is_empty()) { + if group.len() <= max_exact { + hold_exactly(grads, group); + largest = largest.max(group.len()); + } else { + hold_by_sweeps(grads, group); + } + } + largest +} + +/// Add `y_x`, `y_y` times a row of `A` to the gradients it reads. +fn step_gradients(grads: &mut [[f64; 4]], (t, a, _): &HoldRow, y: [f64; 2]) { + for k in 0..3 { + let step = [y[0] * a[k][0], y[0] * a[k][1], y[1] * a[k][0], y[1] * a[k][1]]; + if let Some(gk) = grads.get_mut(t[k]) + && step.iter().all(|x| x.is_finite()) + { + for (g, d) in gk.iter_mut().zip(step) { + *g += d; + } + } + } +} + +/// One group's `A Aᵀ y = o`, solved exactly (dense, so only for small groups). +fn hold_exactly(grads: &mut [[f64; 4]], group: &[&HoldRow]) { + let n = group.len(); + let mut m: Vec> = group + .iter() + .map(|ri| { + let mut r: Vec = group.iter().map(|rj| rows_meet(ri, rj)).collect(); + r.extend(ri.2); + r + }) + .collect(); + let Some(y) = solve_dense(&mut m, n) else { return }; + for (row, y) in group.iter().zip(y) { + step_gradients(grads, row, y); + } +} + +/// One group's points held by cyclic projection: each step makes one point's offset zero by the +/// least change to its gradients. The passes converge on the exact answer, slowly where points +/// pull nearly the same way; a fixed number of them bounds the work. +fn hold_by_sweeps(grads: &mut [[f64; 4]], group: &[&HoldRow]) { + let own: Vec = group.iter().map(|r| rows_meet(r, r)).collect(); + for _ in 0..HOLD_SWEEPS { + for (row, own) in group.iter().zip(&own) { + let (t, a, _) = row; + let Some(g) = t.iter().map(|v| grads.get(*v).copied()).collect::>>().filter(|_| *own >= 1e-12) else { continue }; + let off = [0, 1].map(|c| (0..3).map(|k| a[k][0] * g[k][2 * c] + a[k][1] * g[k][2 * c + 1]).sum::()); + step_gradients(grads, row, off.map(|o| -o / own)); + } + } +} + +/// Solve `n` equations, each row of `m` its `n` coefficients and then two right-hand sides, by +/// elimination with partial pivoting. A variable with no usable pivot (points that hold the same +/// spot twice, say) stays 0, which the others then cover. +fn solve_dense(m: &mut [Vec], n: usize) -> Option> { + let scale = (0..n).map(|i| m.get(i).and_then(|r| r.get(i)).copied().unwrap_or(0.0).abs()).fold(0.0, f64::max); + if m.len() != n || m.iter().any(|r| r.len() != n + 2) || !scale.is_finite() || scale <= 0.0 { + return None; + } + let tiny = scale * 1e-12; + let mut pivots = vec![None; n]; + let mut row = 0; + for col in 0..n { + let Some(p) = (row..n).max_by(|a, b| m[*a][col].abs().total_cmp(&m[*b][col].abs())) else { break }; + if m[p][col].abs() <= tiny { + continue; + } + m.swap(row, p); + for r in 0..n { + if r != row { + let f = m[r][col] / m[row][col]; + if f != 0.0 { + for c in col..n + 2 { + m[r][c] -= f * m[row][c]; + } + } + } + } + pivots[col] = Some(row); + row += 1; + } + let y: Vec<[f64; 2]> = pivots.iter().enumerate().map(|(col, p)| p.map_or([0.0; 2], |r| [m[r][n] / m[r][col], m[r][n + 1] / m[r][col]])).collect(); + y.iter().flatten().all(|x| x.is_finite()).then_some(y) +} + +/// Smooth the piecewise-linear solve for drawing: Phong deformation (James, "Phong Deformation: A +/// Better C0 Interpolation for Embedded Deformation", SIGGRAPH 2020). A point at barycentric `l` +/// goes to `Σ l_i (d_i + F_i (q − r_i))` instead of `Σ l_i d_i`, with `F_i` the gradients at the +/// vertices. It agrees at the vertices and reproduces any affine map, so pins on vertices and +/// rigid parts stay exact; between them, straight lines in the image bend along a curve where a +/// linear map creases at every mesh edge. The map is quadratic, and the same along an edge from +/// both sides, so a uniform split of every triangle follows it within [`SMOOTH_TOLERANCE`] with +/// no cracks. +pub fn smooth_mesh(mesh: &Mesh, def: &[[f64; 2]], scale: f64) -> SmoothMesh { + smooth_mesh_holding(mesh, def, scale, &[]) +} + +/// [`smooth_mesh`] that also takes each of `held` (a triangle and barycentric coordinates, the +/// points pins hold inside triangles) where the linear solve put it, so the image under a pin +/// stays under it. +pub fn smooth_mesh_holding(mesh: &Mesh, def: &[[f64; 2]], scale: f64, held: &[([usize; 3], [f64; 3])]) -> SmoothMesh { + let n = mesh.tris.len(); + let plain = || SmoothMesh { rest: mesh.verts.clone(), deformed: def.to_vec(), tris: mesh.tris.clone(), parent: (0..n).collect() }; + if def.len() != mesh.verts.len() || n == 0 { + return plain(); + } + let mut grads = vertex_gradients(mesh, def); + hold_points(mesh, &mut grads, held); + let grads = grads; + let v = &mesh.verts; + let phong = |t: &[usize; 3], l: [f64; 3]| { + let q = [l[0] * v[t[0]][0] + l[1] * v[t[1]][0] + l[2] * v[t[2]][0], l[0] * v[t[0]][1] + l[1] * v[t[1]][1] + l[2] * v[t[2]][1]]; + let mut p = [0.0, 0.0]; + for (k, w) in l.iter().enumerate() { + let (i, g) = (t[k], grads[t[k]]); + let e = [q[0] - v[i][0], q[1] - v[i][1]]; + p[0] += w * (def[i][0] + g[0] * e[0] + g[1] * e[1]); + p[1] += w * (def[i][1] + g[2] * e[0] + g[3] * e[1]); + } + (q, p) + }; + // The bow of the curve over the chord, largest over the mesh, sets the split. + let mut bow: f64 = 0.0; + for t in &mesh.tris { + for l in [[0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0]] { + let (_, p) = phong(t, l); + let chord = [l[0] * def[t[0]][0] + l[1] * def[t[1]][0] + l[2] * def[t[2]][0], l[0] * def[t[0]][1] + l[1] * def[t[1]][1] + l[2] * def[t[2]][1]]; + bow = bow.max((p[0] - chord[0]).hypot(p[1] - chord[1])); + } + } + let budget = ((SMOOTH_MAX_TRIS / n) as f64).sqrt() as usize; + let k = ((bow * scale / SMOOTH_TOLERANCE).sqrt().ceil() as usize).clamp(1, SMOOTH_MAX_SPLIT.min(budget.max(1))); + if k <= 1 { + return plain(); + } + let mut rest = mesh.verts.clone(); + let mut deformed = def.to_vec(); + let mut tris = Vec::with_capacity(n * k * k); + let mut parent = Vec::with_capacity(n * k * k); + // Points on an edge, shared with the triangle across it: (low vertex, high vertex, step from low). + let mut on_edge: HashMap<(usize, usize, usize), usize> = HashMap::with_capacity(n * k); + let mut grid = vec![0usize; (k + 1) * (k + 1)]; + for (pk, t) in mesh.tris.iter().enumerate() { + for i in 0..=k { + for j in 0..=k - i { + // Weights of corners 0, 1, 2 in k-ths. + let c = [k - i - j, i, j]; + let id = if let Some(corner) = c.iter().position(|x| *x == k) { + t[corner] + } else if let Some(zero) = c.iter().position(|x| *x == 0) { + let (a, b) = ((zero + 1) % 3, (zero + 2) % 3); + let (lo, hi, step) = if t[a] < t[b] { (a, b, c[b]) } else { (b, a, c[a]) }; + *on_edge.entry((t[lo], t[hi], step)).or_insert_with(|| { + let mut l = [0.0; 3]; + l[hi] = step as f64 / k as f64; + l[lo] = 1.0 - l[hi]; + let (q, p) = phong(t, l); + rest.push(q); + deformed.push(p); + rest.len() - 1 + }) + } else { + let (q, p) = phong(t, c.map(|x| x as f64 / k as f64)); + rest.push(q); + deformed.push(p); + rest.len() - 1 + }; + grid[i * (k + 1) + j] = id; + } + } + for i in 0..k { + for j in 0..k - i { + let at = |a: usize, b: usize| grid[a * (k + 1) + b]; + tris.push([at(i, j), at(i + 1, j), at(i, j + 1)]); + parent.push(pk); + if i + j + 1 < k { + tris.push([at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]); + parent.push(pk); + } + } + } + } + SmoothMesh { rest, deformed, tris, parent } +} + +/// A triangle ready to rasterize: its edge functions (`a x + b y + c >= 0` inside), the affine map +/// from output pixels back to the source and how many samples per axis that map needs. +struct RasterTri { + edges: [[f64; 3]; 3], + /// Source `x = m[0] X + m[1] Y + m[2]`, `y = m[3] X + m[4] Y + m[5]`. + map: [f64; 6], + samples: u8, + bounds: [f64; 4], +} + +impl RasterTri { + fn new(r: &[[f64; 2]; 3], d: &[[f64; 2]; 3]) -> Option { + let area = (d[1][0] - d[0][0]) * (d[2][1] - d[0][1]) - (d[1][1] - d[0][1]) * (d[2][0] - d[0][0]); + if !area.is_finite() || area.abs() < 1e-9 { + return None; + } + let sign = area.signum(); + let edge = |p: [f64; 2], q: [f64; 2]| { + let (a, b) = (sign * (p[1] - q[1]), sign * (q[0] - p[0])); + [a, b, -(a * p[0] + b * p[1])] + }; + // The barycentric gradients give the affine map directly. + let e = [edge(d[1], d[2]), edge(d[2], d[0]), edge(d[0], d[1])]; + let inv = 1.0 / area.abs(); + let at = |c: usize, k: usize| inv * (e[0][k] * r[0][c] + e[1][k] * r[1][c] + e[2][k] * r[2][c]); + let map = [at(0, 0), at(0, 1), at(0, 2), at(1, 0), at(1, 1), at(1, 2)]; + // Largest source distance one output pixel covers: past it, one sample would skip texels. + let (p, q) = ((map[0] * map[0] + map[3] * map[3]).sqrt(), (map[1] * map[1] + map[4] * map[4]).sqrt()); + let samples = match p.max(q) { + t if t <= 1.25 => 1, + t if t <= 2.5 => 2, + _ => 4, + }; + let bounds = + [d[0][0].min(d[1][0]).min(d[2][0]), d[0][1].min(d[1][1]).min(d[2][1]), d[0][0].max(d[1][0]).max(d[2][0]), d[0][1].max(d[1][1]).max(d[2][1])]; + Some(RasterTri { edges: e, map, samples, bounds }) + } + + #[inline] + fn source(&self, x: f64, y: f64) -> [f64; 2] { + let m = &self.map; + [m[0] * x + m[1] * y + m[2], m[3] * x + m[4] * y + m[5]] + } + + /// Coverage of the pixel at (x, y): bit `i + 4 j` is the sample at `((i + 0.5) / 4, (j + 0.5) / 4)`. + #[inline] + fn coverage(&self, x: f64, y: f64) -> u16 { + let mut all = true; + for [a, b, c] in &self.edges { + let v = a * x + b * y + c; + if v + a.max(0.0) + b.max(0.0) < -1e-9 { + return 0; + } + all &= v + a.min(0.0) + b.min(0.0) >= -1e-9; + } + if all { + return u16::MAX; + } + let mut mask = 0; + for j in 0..4 { + for i in 0..4 { + let (sx, sy) = (x + (i as f64 + 0.5) / 4.0, y + (j as f64 + 0.5) / 4.0); + if self.edges.iter().all(|[a, b, c]| a * sx + b * sy + c >= -1e-9) { + mask |= 1 << (i + 4 * j); + } + } + } + mask + } +} + +/// No triangle over this sample. +const NO_TRI: u32 = u32::MAX; + +/// Texture-map `buf` through triangles (rest px → deformed px), back to front. Each pixel has 16 +/// coverage samples remembering their top triangle, so the outline gets a smooth ramp and +/// triangles that share an edge leave no seam; a pixel inside the mesh reads the source once +/// unless the triangle under it is minified or two sheets of the mesh meet there, where it +/// averages 4 or 16 reads. +fn rasterize(buf: &Buf, tris: &[([[f64; 2]; 3], [[f64; 2]; 3])]) -> Buf { + let tris: Vec = tris.iter().filter_map(|(r, d)| RasterTri::new(r, d)).collect(); + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for t in &tris { + x0 = x0.min(t.bounds[0]); + y0 = y0.min(t.bounds[1]); + x1 = x1.max(t.bounds[2]); + y1 = y1.max(t.bounds[3]); + } + if tris.is_empty() { + return Buf { img: Image::new(1, 1), offset: buf.offset, scale: buf.scale }; } let ox = x0.floor() as i64 - 1; let oy = y0.floor() as i64 - 1; - let w = ((x1.ceil() as i64 + 1 - ox).max(1) as u32).min(16384); - let h = ((y1.ceil() as i64 + 1 - oy).max(1) as u32).min(16384); + let w = (x1.ceil() as i64).saturating_add(1).saturating_sub(ox).clamp(1, 16384) as u32; + let h = (y1.ceil() as i64).saturating_add(1).saturating_sub(oy).clamp(1, 16384) as u32; let mut out = Image::new(w, h); - // Triangle y-ranges for row bucketing. - let ranges: Vec<(f64, f64)> = tris.iter().map(|(_, d, _)| (d[0][1].min(d[1][1]).min(d[2][1]), d[0][1].max(d[1][1]).max(d[2][1]))).collect(); - const SUB: [[f64; 2]; 4] = [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]]; + // The triangles over each row, in draw order. + let row_range = |t: &RasterTri| { + let a = ((t.bounds[1].floor() as i64 - oy).max(0) as usize).min(h as usize); + let b = ((t.bounds[3].floor() as i64 - oy + 1).max(0) as usize).min(h as usize); + (a, b) + }; + let mut starts = vec![0usize; h as usize + 1]; + for t in &tris { + let (a, b) = row_range(t); + for n in &mut starts[a..b] { + *n += 1; + } + } + let mut total = 0; + for n in starts.iter_mut() { + let c = *n; + *n = total; + total += c; + } + let mut bucket = vec![0u32; total]; + let mut fill = starts.clone(); + for (k, t) in tris.iter().enumerate() { + let (a, b) = row_range(t); + for f in &mut fill[a..b] { + bucket[*f] = k as u32; + *f += 1; + } + } out.rows_mut().for_each(|(row, line)| { let y = (oy + row as i64) as f64; let n = line.len(); - let mut cover = vec![0u8; n]; - let mut center: Vec> = vec![None; n]; - let mut any: Vec> = vec![None; n]; - for (k, (_, d, _)) in tris.iter().enumerate() { - let (ya, yb) = ranges[k]; - if yb < y || ya > y + 1.0 { - continue; - } - let xa = (d[0][0].min(d[1][0]).min(d[2][0]).floor() as i64 - ox).max(0) as usize; - let xb = ((d[0][0].max(d[1][0]).max(d[2][0]).ceil() as i64 - ox + 1).max(0) as usize).min(n); - for (i, ((cv, ce), an)) in cover.iter_mut().zip(center.iter_mut()).zip(any.iter_mut()).enumerate().take(xb).skip(xa) { - let x = (ox + i as i64) as f64; - for (s, o) in SUB.iter().enumerate() { - if let Some(l) = bary(d[0], d[1], d[2], [x + o[0], y + o[1]]) - && l.iter().all(|v| *v >= -1e-9) - { - *cv |= 1 << s; - *an = Some(k); - } + let mut owners = vec![NO_TRI; n * 16]; + let mut touched = vec![false; n]; + for &k in &bucket[starts[row]..starts[row + 1]] { + let t = &tris[k as usize]; + let xa = ((t.bounds[0].floor() as i64 - ox).max(0) as usize).min(n); + let xb = ((t.bounds[2].floor() as i64 - ox + 1).max(0) as usize).min(n); + for i in xa..xb { + let mask = t.coverage((ox + i as i64) as f64, y); + if mask == 0 { + continue; } - if let Some(l) = bary(d[0], d[1], d[2], [x + 0.5, y + 0.5]) - && l.iter().all(|v| *v >= -1e-9) - { - *ce = Some(k); + touched[i] = true; + let px = &mut owners[i * 16..(i + 1) * 16]; + if mask == u16::MAX { + px.fill(k); + } else { + for (s, o) in px.iter_mut().enumerate() { + if mask & (1 << s) != 0 { + *o = k; + } + } } } } for (i, px) in line.iter_mut().enumerate() { - let c = cover[i].count_ones(); - let Some(k) = center[i].or(any[i]) else { continue }; - if c == 0 && center[i].is_none() { - continue; + if touched[i] { + *px = resolve(buf, &tris, &owners[i * 16..(i + 1) * 16], (ox + i as i64) as f64, y); } - let (r, d, _) = &tris[k]; - let p = [(ox + i as i64) as f64 + 0.5, y + 0.5]; - let Some(l) = bary(d[0], d[1], d[2], p) else { continue }; - let src = [l[0] * r[0][0] + l[1] * r[1][0] + l[2] * r[2][0], l[0] * r[0][1] + l[1] * r[1][1] + l[2] * r[2][1]]; - let s = buf.img.sample_bilinear(src[0], src[1]); - let cov = if center[i].is_some() && c == 4 { 1.0 } else { c.max(1) as f32 / 4.0 }; - *px = [s[0] * cov, s[1] * cov, s[2] * cov, s[3] * cov]; } }); Buf { img: out, offset: [buf.offset[0] - ox as f64, buf.offset[1] - oy as f64], scale: buf.scale } } +/// The colour of the pixel at (x, y) from its 16 samples' triangles: premultiplied source reads, +/// weighted by the samples they stand for, so uncovered samples count as transparent. +fn resolve(buf: &Buf, tris: &[RasterTri], owners: &[u32], x: f64, y: f64) -> [f32; 4] { + // A sample by the pixel's centre decides the read count for pixels inside the mesh. + let center = [5usize, 6, 9, 10].into_iter().find_map(|s| tris.get(*owners.get(s)? as usize)); + let full = owners.iter().all(|o| *o != NO_TRI); + let mut grid = 2; + if full && let Some(c) = center { + grid = c.samples as usize; + let first = owners[0]; + if grid == 1 && owners.iter().any(|o| *o != first) { + // Neighbouring triangles agree on the source along their shared edge: only sheets + // of the mesh that overlap here disagree by more than a pixel or so. + let sc = c.source(x + 0.5, y + 0.5); + // Every sheet among the samples, not just the corners': a narrow one can own a + // column or row that no corner shows. + let apart = owners.iter().enumerate().any(|(i, o)| { + !owners[..i].contains(o) + && tris.get(*o as usize).is_some_and(|t| { + let q = t.source(x + 0.5, y + 0.5); + (q[0] - sc[0]).abs().max((q[1] - sc[1]).abs()) > 2.0 + }) + }); + if apart { + grid = 2; + } + } + if grid == 1 { + let src = c.source(x + 0.5, y + 0.5); + return buf.img.sample_bilinear(src[0], src[1]); + } + } + let grid = grid.max(2); + let cell = 4 / grid; + let mut sum = [0.0f32; 4]; + for gy in 0..grid { + for gx in 0..grid { + // Covered samples in this cell by triangle, in scan order: (triangle, first sample, count). + let mut groups = [(NO_TRI, 0usize, 0usize, 0.0f32); 16]; + let mut found = 0; + let mut count = 0.0f32; + for sy in 0..cell { + for sx in 0..cell { + let (i, j) = (gx * cell + sx, gy * cell + sy); + let Some(&o) = owners.get(i + 4 * j) else { continue }; + if o == NO_TRI { + continue; + } + count += 1.0; + if let Some(g) = groups[..found].iter_mut().find(|g| g.0 == o) { + g.3 += 1.0; + } else if let Some(g) = groups.get_mut(found) { + *g = (o, i, j, 1.0); + found += 1; + } + } + } + let Some(&(o, i, j, _)) = groups[..found].first() else { continue }; + let Some(t) = tris.get(o as usize) else { continue }; + // A fully covered cell reads its centre; a partial one, a sample known to be inside. + let (fx, fy) = if count as usize == cell * cell { + (gx as f64 + 0.5, gy as f64 + 0.5) + } else { + ((i as f64 + 0.5) * grid as f64 / 4.0, (j as f64 + 0.5) * grid as f64 / 4.0) + }; + let (px, py) = (x + fx / grid as f64, y + fy / grid as f64); + let src = t.source(px, py); + // Triangles of the same sheet agree on the source and read with the first; another sheet + // overlapping in the cell reads its own colour at its own first sample. + let mut weight = count; + for &(o2, i2, j2, n2) in groups[..found].iter().skip(1) { + let Some(u) = tris.get(o2 as usize) else { continue }; + let q = u.source(px, py); + if (q[0] - src[0]).abs().max((q[1] - src[1]).abs()) <= 2.0 { + continue; + } + weight -= n2; + let s = u.source(x + (i2 as f64 + 0.5) / 4.0, y + (j2 as f64 + 0.5) / 4.0); + let c = buf.img.sample_bilinear(s[0], s[1]); + for (a, b) in sum.iter_mut().zip(c) { + *a += b * n2 / 16.0; + } + } + let c = buf.img.sample_bilinear(src[0], src[1]); + for (a, b) in sum.iter_mut().zip(c) { + *a += b * weight / 16.0; + } + } + } + sum +} + /// Count of nodes in a group tree (for tests and readouts). pub fn pin_count(fx: &PropGroup) -> usize { meshes(fx).map(|m| pins(m).count()).sum() @@ -510,12 +1127,13 @@ pub fn pin_count(fx: &PropGroup) -> usize { /// The deformed mesh for overlays: mesh, deformed vertices (layer space) per mesh group uid. pub fn overlay(buf: &Buf, params: &Params) -> Vec<(u64, Arc, Vec<[f64; 2]>, Vec)> { - let refine = (params.get("refinement").map(Value::as_f64).unwrap_or(20.0) / 10.0).round().clamp(0.0, 10.0) as usize; + let first = original(params); + let refine = if first { legacy::rounds(params) } else { refinement_rounds(params) }; parse(params) .into_iter() .map(|m| { let mesh = mesh_for(buf, &m); - let def = solve(&mesh, &m.pins, refine); + let def = if first { legacy::solve(&mesh, &m.pins, refine) } else { solve_shared(&mesh, &m.pins, refine).to_vec() }; (m.uid, mesh, def, m.pins) }) .collect() diff --git a/crates/effects/src/puppet/arap.rs b/crates/effects/src/puppet/arap.rs index 19a875946..86f0d11ff 100644 --- a/crates/effects/src/puppet/arap.rs +++ b/crates/effects/src/puppet/arap.rs @@ -7,15 +7,40 @@ //! edge's local frame, `v_k = v_i + x·(v_j − v_i) + y·R90(v_j − v_i)`. Minimising the error of //! that relation over all three edges of every triangle, with the pinned vertices fixed, //! gives a deformation that is locally a similarity (rotation + uniform scale). -//! 2. **Scale-adjustment step.** Each triangle of the step-1 result is fitted with a rigid copy -//! of its rest shape (2D Procrustes: best rotation about the centroid). The final positions -//! minimise the difference between every triangle's edge vectors and its fitted edge vectors. +//! 2. **Fit.** Each triangle of the step-1 result is fitted with a target: its rest shape turned, and +//! changed towards keeping its area (see [`fit_triangle`]); the positions then minimise the difference between every triangle's edge vectors and +//! its fitted edge vectors. Repeating this is the local/global iteration of Liu et al., "A +//! Local/Global Approach to Mesh Parameterization" (2008), with its cotangent edge weights, +//! so the energy is the area integral of `|F - R|²` and doesn't depend on how the mesh happens +//! to be triangulated. //! -//! Optional extra iterations repeat step 2 on its own result (rotation refinement). Triangle -//! weights stiffen regions (Starch); edge-vector targets implement Bend/Advanced pin rotation -//! and scale. Both systems are symmetric positive definite (a tiny regulariser towards the -//! initial guess keeps under-constrained meshes well-posed) and are solved with Jacobi- -//! preconditioned conjugate gradients on a sparse matrix. +//! Rigidity alone concentrates a pin's pull: the strain of a point load goes as 1/r, so the mesh +//! around a pin stretches hard. Step 2 therefore also minimises a bending energy, `λ ∫ |∇F|²`, the +//! squared jump of the deformation gradient across each inner edge (Bergou et al., "A Quadratic +//! Bending Model for Inextensible Surfaces", 2006, flat case), which bounds the strain at a point. +//! Bending costs nothing for an affine map, though, so on its own it extends a pull's stretch across +//! the whole shape, and the shape grows. A pull towards where the pins as a whole put the mesh (their +//! best rigid fit), which sets in away from the pins, makes the deformation die out instead: `μ(x) +//! |v − T(x)|²`. All the lengths go with the mesh's size, so adding a pin doesn't change them. +//! +//! Material should also keep its volume, like rubber, so the fit's target gives way to a change of +//! shape at constant area and pushes back against a change of area (see [`fit_triangle`]). +//! +//! Nothing stiffens a triangle as it nears collapse: every round is the same linear solve, so the +//! result follows the pins smoothly even where they ask for more than the mesh can give, as two +//! pins pulled far apart from close together do. (Stiffening each triangle from the shape the +//! last solve gave it, again and again, kept hard pushes from folding, but there it swung from +//! pass to pass and settled somewhere new at every small move.) Pins are hard to the end: pins +//! dragged through each other still land, with whatever folds that takes. +//! +//! Triangle weights stiffen regions (Starch); edge-vector targets implement Bend/Advanced pin +//! rotation and scale. Both systems are symmetric positive definite (a tiny regulariser towards +//! the initial guess keeps under-constrained meshes well-posed). The matrices don't change +//! between rounds, so each is factored once (banded Cholesky in reverse Cuthill-McKee order) and a +//! round is two +//! back-substitutions; if a factor can't be built, or would be too large ([`MAX_FACTOR`]), +//! Jacobi-preconditioned conjugate gradients solve the same system. The rounds stop early once +//! one moves nothing visibly ([`SETTLED`]). use std::collections::BTreeMap; @@ -28,24 +53,35 @@ pub struct EdgeTarget { pub weight: f64, } +/// A stiff soft target for the point at barycentric `bary` in the triangle `verts`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PointTarget { + pub verts: [usize; 3], + pub bary: [f64; 3], + pub position: [f64; 2], +} + /// Constraints for one solve. #[derive(Clone, Debug, Default, PartialEq)] pub struct Handles { /// Hard position constraints (vertex, position). pub fixed: Vec<(usize, [f64; 2])>, + /// Points inside triangles held at positions. + pub points: Vec, pub edges: Vec, } /// Sparse symmetric matrix in row maps (assembly), then CSR for the solve. -struct Sparse { +#[derive(Clone)] +pub(super) struct Sparse { rows: Vec>, } impl Sparse { - fn new(n: usize) -> Sparse { + pub(super) fn new(n: usize) -> Sparse { Sparse { rows: vec![BTreeMap::new(); n] } } - fn add(&mut self, i: usize, j: usize, v: f64) { + pub(super) fn add(&mut self, i: usize, j: usize, v: f64) { *self.rows[i].entry(j).or_insert(0.0) += v; } } @@ -71,7 +107,7 @@ impl Csr { /// Solve `A x = b` restricted to the free unknowns (`free[i]`), with the fixed unknowns at /// their values in `x`. Jacobi-preconditioned conjugate gradients, starting from `x`. -fn solve(a: &Sparse, b: &[f64], x: &mut [f64], free: &[bool]) { +pub(super) fn solve(a: &Sparse, b: &[f64], x: &mut [f64], free: &[bool]) { let n = b.len(); let idx: Vec = (0..n).filter(|i| free[*i]).collect(); if idx.is_empty() { @@ -143,12 +179,229 @@ fn solve(a: &Sparse, b: &[f64], x: &mut [f64], free: &[bool]) { } } +/// The reduced system `A_ff x_f = b_f − A_fc x_c` as a banded Cholesky factor, in reverse +/// Cuthill-McKee order of the free unknowns. +struct Factor { + /// Factor row → unknown. + idx: Vec, + /// Unknown → factor row (`usize::MAX` for fixed unknowns). + pos: Vec, + /// Half bandwidth. + p: usize, + /// Row `i` holds `L[i][i - p ..= i]`. + l: Vec, + /// Couplings to fixed unknowns: (factor row, fixed unknown, value). + fixed: Vec<(usize, usize, f64)>, +} + +/// Largest factor kept in memory, in values (64 MB). The densest mesh the Puppet tool builds (a +/// target of 20,000 triangles) needs about 4.7 million, for the similarity step; past this the +/// solve uses conjugate gradients instead. +const MAX_FACTOR: usize = 8_000_000; + +impl Factor { + /// `None` when the band would be larger than `max_values` or the matrix isn't numerically + /// positive definite. + fn new(a: &Sparse, free: &[bool], max_values: usize) -> Option { + let n = a.rows.len(); + let degree = |i: usize| a.rows[i].keys().filter(|j| free[**j]).count(); + let mut seen = vec![false; n]; + let mut idx = Vec::with_capacity(n); + let mut starts: Vec = (0..n).filter(|i| free[*i]).collect(); + starts.sort_by_key(|i| degree(*i)); + for s in starts { + if seen[s] { + continue; + } + seen[s] = true; + let mut head = idx.len(); + idx.push(s); + while let Some(&v) = idx.get(head) { + head += 1; + let mut next: Vec = a.rows[v].keys().copied().filter(|j| free[*j] && !seen[*j]).collect(); + next.sort_by_key(|j| degree(*j)); + for j in next { + seen[j] = true; + idx.push(j); + } + } + } + idx.reverse(); + let m = idx.len(); + let mut pos = vec![usize::MAX; n]; + for (k, i) in idx.iter().enumerate() { + pos[*i] = k; + } + let mut p = 0; + for (k, &i) in idx.iter().enumerate() { + for j in a.rows[i].keys() { + if free[*j] { + p = p.max(k.abs_diff(pos[*j])); + } + } + } + let len = m.checked_mul(p + 1)?; + if len > max_values { + return None; + } + let mut f = Factor { idx, pos, p, l: vec![0.0; len], fixed: vec![] }; + f.factor(a, free).then_some(f) + } + + /// Factor `a` into this factor's storage, in its order. `a` must couple no unknowns further + /// apart than the band the order was made for (any matrix with the same sparsity does). False + /// when it does, or when it isn't numerically positive definite. + fn factor(&mut self, a: &Sparse, free: &[bool]) -> bool { + let (m, p, w) = (self.idx.len(), self.p, self.p + 1); + let l = &mut self.l; + l.fill(0.0); + self.fixed.clear(); + for (k, &i) in self.idx.iter().enumerate() { + let Some(row) = a.rows.get(i) else { return false }; + for (&j, &v) in row { + if !free.get(j).copied().unwrap_or(false) { + self.fixed.push((k, j, v)); + continue; + } + let Some(&pj) = self.pos.get(j) else { return false }; + if pj > k { + continue; + } + // Row k, column pj: offset pj + p - k, in the band only if k - pj <= p. + let Some(slot) = (pj + p).checked_sub(k).and_then(|o| l.get_mut(k * w + o)) else { return false }; + *slot = v; + } + } + for i in 0..m { + let lo = i.saturating_sub(p); + for j in lo..=i { + // L[i][j] less the sum over k in lo..j of L[i][k] L[j][k], k rising. + let mut s = l[i * w + j + p - i]; + for (u, v) in l[i * w + lo + p - i..i * w + j + p - i].iter().zip(&l[j * w + lo + p - j..j * w + p]) { + s -= u * v; + } + if i == j { + if s <= 0.0 || !s.is_finite() { + return false; + } + l[i * w + p] = s.sqrt(); + } else { + l[i * w + j + p - i] = s / l[j * w + p]; + } + } + } + true + } + + fn solve(&self, b: &[f64], x: &mut [f64]) { + let (m, p, w) = (self.idx.len(), self.p, self.p + 1); + let mut y: Vec = self.idx.iter().map(|i| b[*i]).collect(); + for &(k, j, v) in &self.fixed { + y[k] -= v * x[j]; + } + for i in 0..m { + let lo = i.saturating_sub(p); + let mut s = y[i]; + for (u, v) in self.l[i * w + lo + p - i..i * w + p].iter().zip(&y[lo..i]) { + s -= u * v; + } + y[i] = s / self.l[i * w + p]; + } + for i in (0..m).rev() { + let mut s = y[i]; + for k in i + 1..(i + w).min(m) { + s -= self.l[k * w + i + p - k] * y[k]; + } + y[i] = s / self.l[i * w + p]; + } + for (k, i) in self.idx.iter().enumerate() { + x[*i] = y[k]; + } + } +} + +/// One system of the solve: the factor if it could be built, else conjugate gradients. +struct System { + a: Sparse, + free: Vec, + factor: Option, +} + +impl System { + fn new(a: Sparse, free: Vec, max_factor: usize) -> System { + let factor = Factor::new(&a, &free, max_factor); + System { a, free, factor } + } + + fn solve(&self, b: &[f64], x: &mut [f64]) { + match &self.factor { + Some(f) => f.solve(b, x), + None => solve(&self.a, b, x, &self.free), + } + } +} + +/// Half the cotangents of a triangle's angles: `[k]` weighs the edge opposite corner `k`. +/// Degenerate triangles weigh nothing. +fn cot_weights(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> [f64; 3] { + let cross = ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])).abs(); + if cross <= 1e-12 { + return [0.0; 3]; + } + let half_cot = |o: [f64; 2], u: [f64; 2], v: [f64; 2]| 0.5 * ((u[0] - o[0]) * (v[0] - o[0]) + (u[1] - o[1]) * (v[1] - o[1])) / cross; + [half_cot(a, b, c), half_cot(b, c, a), half_cot(c, a, b)] +} + const REG: f64 = 1e-9; +/// How far bending carries a pin's pull, against the mesh's size. Higher is smoother at the pins +/// and spreads further; lower folds the mesh at the pins. +const BEND_LENGTH: f64 = 0.0675; +/// How fast displacement dies out beyond the pins, against the mesh's size. Higher lets the shape +/// grow and drift; lower squeezes the mesh between the pins and the outline until it folds. +const SETTLE_LENGTH: f64 = 0.12; +/// How far from the pins that sets in, against the mesh's size. +const SETTLE_FROM: f64 = 0.28; + +/// How far a triangle's target gives way towards its current shape at its rest area (1 would offer no +/// resistance to shear), and how hard its target pushes back against a change of area. +const FIT_GIVE: f64 = 0.75; +const FIT_PRESSURE: f64 = 0.5; +/// Bounds on what the fit reads from a triangle, so a collapsed one can't throw its target far. +const FIT_SMALLEST: f64 = 0.05; +const FIT_MOST_SHAPE: f64 = 25.0; +/// Stiffness of a point held inside a triangle, against the mesh's own (Laplacian and bending). +const POINT_STIFFNESS: f64 = 1e5; + +/// A refinement round that moves no vertex further than this (layer pixels) ends the refinement. +/// On the stress tests, running the rounds left would move no vertex a ten-thousandth of a pixel. +const SETTLED: f64 = 1e-4; + +/// Bounds on the solve's work. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Limits { + /// Largest factor, in values, before conjugate gradients take over (see [`MAX_FACTOR`]). + pub(crate) max_factor: usize, + /// See [`SETTLED`]; 0 runs every round. + pub(crate) settled: f64, +} + +pub(crate) const LIMITS: Limits = Limits { max_factor: MAX_FACTOR, settled: SETTLED }; + +fn point_at(p: &[[f64; 2]], q: &PointTarget) -> [f64; 2] { + let [a, b, c] = q.verts; + let [l0, l1, l2] = q.bary; + [l0 * p[a][0] + l1 * p[b][0] + l2 * p[c][0], l0 * p[a][1] + l1 * p[b][1] + l2 * p[c][1]] +} + /// Deform a mesh: `rest` vertices, CCW `tris` with per-triangle `weights` (1 = normal, -/// larger = stiffer), constraints, and `refine` extra rigid-fit iterations. Returns the -/// deformed vertex positions. +/// larger = stiffer), constraints, and up to `refine` extra rigid-fit iterations (fewer once a +/// round moves nothing visibly, see [`SETTLED`]). Returns the deformed vertex positions. pub fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handles, refine: usize) -> Vec<[f64; 2]> { + deform_with(rest, tris, weights, h, refine, LIMITS) +} + +pub(crate) fn deform_with(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handles, refine: usize, limits: Limits) -> Vec<[f64; 2]> { let n = rest.len(); if n == 0 { return vec![]; @@ -159,15 +412,21 @@ pub fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handl t[0] += p[0] - rest[*i][0]; t[1] += p[1] - rest[*i][1]; } - if !h.fixed.is_empty() { - t[0] /= h.fixed.len() as f64; - t[1] /= h.fixed.len() as f64; + for q in &h.points { + let r = point_at(rest, q); + t[0] += q.position[0] - r[0]; + t[1] += q.position[1] - r[1]; + } + let handles = h.fixed.len() + h.points.len(); + if handles > 0 { + t[0] /= handles as f64; + t[1] /= handles as f64; } let x0: Vec<[f64; 2]> = rest.iter().map(|p| [p[0] + t[0], p[1] + t[1]]).collect(); // One pin and no edge targets: every rotation and scale about the pin costs nothing, and // the regulariser that picks the translation is too weak to stop CG turning round-off // into a visible rotation (#313). The translation is the exact solution. - if h.fixed.len() == 1 && h.edges.is_empty() { + if handles == 1 && h.edges.is_empty() { return x0; } let mut fixed = vec![false; n]; @@ -224,6 +483,16 @@ pub fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handl b[2 * e.i + c] -= ww * e.vec[c]; } } + // Stiff enough to land within a small fraction of a pixel, against either system's diagonal. + let area: f64 = tris.iter().map(|t| tri_area(rest, t)).sum(); + let mut pins_from: Vec<[f64; 2]> = h.fixed.iter().map(|(i, _)| rest[*i]).collect(); + let mut pins_to: Vec<[f64; 2]> = h.fixed.iter().map(|(_, p)| *p).collect(); + pins_from.extend(h.points.iter().map(|q| point_at(rest, q))); + pins_to.extend(h.points.iter().map(|q| q.position)); + let size = extent(rest); + let bend = (BEND_LENGTH * size).powi(2); + let hold = POINT_STIFFNESS * (1.0 + bend / (area / tris.len().max(1) as f64)); + add_points_interleaved(&mut a, &mut b, &h.points, hold); let reg = REG * scale2.recip().min(1.0); for i in 0..n { for c in 0..2 { @@ -237,43 +506,55 @@ pub fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handl x[2 * i + 1] = p[1]; } let free2: Vec = (0..2 * n).map(|k| !fixed[k / 2]).collect(); - solve(&a, &b, &mut x, &free2); + System::new(a, free2, limits.max_factor).solve(&b, &mut x); let mut cur: Vec<[f64; 2]> = (0..n).map(|i| [x[2 * i], x[2 * i + 1]]).collect(); - // ---- Step 2: fit rigid triangles, then match edge vectors (x and y separately). - let mut l = Sparse::new(n); - for (k, t) in tris.iter().enumerate() { - let wk = w(k); - for (i, j) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { - l.add(i, i, wk); - l.add(j, j, wk); - l.add(i, j, -wk); - l.add(j, i, -wk); - } - } + // ---- Step 2: fit rotations, then match edge vectors (x and y separately). + let cots: Vec<[f64; 3]> = tris.iter().map(|t| cot_weights(rest[t[0]], rest[t[1]], rest[t[2]])).collect(); + // Corners of an edge of a triangle, and the corner opposite it. + const EDGES: [(usize, usize, usize); 3] = [(1, 2, 0), (2, 0, 1), (0, 1, 2)]; + let mut base = Sparse::new(n); for e in &h.edges { - l.add(e.i, e.i, e.weight); - l.add(e.j, e.j, e.weight); - l.add(e.i, e.j, -e.weight); - l.add(e.j, e.i, -e.weight); + base.add(e.i, e.i, e.weight); + base.add(e.j, e.j, e.weight); + base.add(e.i, e.j, -e.weight); + base.add(e.j, e.i, -e.weight); } for i in 0..n { - l.add(i, i, reg); + base.add(i, i, reg); } - let free1: Vec = (0..n).map(|i| !fixed[i]).collect(); - for _ in 0..=refine { + add_bending(&mut base, rest, tris, bend); + let settle = settling(rest, tris, &pins_from, &pins_to, size); + for (i, (weight, _)) in settle.iter().enumerate() { + base.add(i, i, *weight); + } + add_points(&mut base, &h.points, hold); + let free: Vec = (0..n).map(|i| !fixed[i]).collect(); + let assemble = |tw: &[f64]| { + let mut l = base.clone(); + for (k, t) in tris.iter().enumerate() { + for (a2, b2, o) in EDGES { + let (i, j, c) = (t[a2], t[b2], tw[k] * cots[k][o]); + l.add(i, i, c); + l.add(j, j, c); + l.add(i, j, -c); + l.add(j, i, -c); + } + } + l + }; + let round = |system: &System, tw: &[f64], cur: &[[f64; 2]]| -> Vec<[f64; 2]> { let mut bx = vec![0.0; n]; let mut by = vec![0.0; n]; for (k, t) in tris.iter().enumerate() { - let wk = w(k); - let f = fit_rigid([rest[t[0]], rest[t[1]], rest[t[2]]], [cur[t[0]], cur[t[1]], cur[t[2]]]); - for (a2, b2) in [(0, 1), (1, 2), (2, 0)] { - let (i, j) = (t[a2], t[b2]); + let f = fit_triangle([rest[t[0]], rest[t[1]], rest[t[2]]], [cur[t[0]], cur[t[1]], cur[t[2]]], w(k)); + for (a2, b2, o) in EDGES { + let (i, j, c) = (t[a2], t[b2], tw[k] * cots[k][o]); let d = [f[b2][0] - f[a2][0], f[b2][1] - f[a2][1]]; - bx[j] += wk * d[0]; - bx[i] -= wk * d[0]; - by[j] += wk * d[1]; - by[i] -= wk * d[1]; + bx[j] += c * d[0]; + bx[i] -= c * d[0]; + by[j] += c * d[1]; + by[i] -= c * d[1]; } } for e in &h.edges { @@ -282,9 +563,10 @@ pub fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handl by[e.j] += e.weight * e.vec[1]; by[e.i] -= e.weight * e.vec[1]; } + add_points_rhs(&mut bx, &mut by, &h.points, hold); for i in 0..n { - bx[i] += reg * x0[i][0]; - by[i] += reg * x0[i][1]; + bx[i] += reg * x0[i][0] + settle[i].0 * settle[i].1[0]; + by[i] += reg * x0[i][1] + settle[i].0 * settle[i].1[1]; } let mut xs: Vec = cur.iter().map(|p| p[0]).collect(); let mut ys: Vec = cur.iter().map(|p| p[1]).collect(); @@ -292,14 +574,158 @@ pub fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handl xs[*i] = p[0]; ys[*i] = p[1]; } - solve(&l, &bx, &mut xs, &free1); - solve(&l, &by, &mut ys, &free1); - cur = (0..n).map(|i| [xs[i], ys[i]]).collect(); + system.solve(&bx, &mut xs); + system.solve(&by, &mut ys); + (0..n).map(|i| [xs[i], ys[i]]).collect() + }; + let tw: Vec = (0..tris.len()).map(w).collect(); + let system = System::new(assemble(&tw), free, limits.max_factor); + for _ in 0..=refine { + let next = round(&system, &tw, &cur); + let step = next.iter().zip(&cur).map(|(a, b)| (a[0] - b[0]).hypot(a[1] - b[1])).fold(0.0, f64::max); + cur = next; + if step < limits.settled { + break; + } } cur } -fn mean_edge2(rest: &[[f64; 2]], tris: &[[usize; 3]]) -> f64 { +/// The longer side of the mesh's bounding box. +fn extent(rest: &[[f64; 2]]) -> f64 { + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for p in rest { + x0 = x0.min(p[0]); + y0 = y0.min(p[1]); + x1 = x1.max(p[0]); + y1 = y1.max(p[1]); + } + (x1 - x0).max(y1 - y0).max(1e-9) +} + +/// For each vertex, the weight of the pull towards the pins' best rigid fit, and where that fit puts +/// the vertex. The weight is the vertex's share of the mesh's area over the settling length squared, +/// fading to nothing at the pins. +fn settling(rest: &[[f64; 2]], tris: &[[usize; 3]], from: &[[f64; 2]], to: &[[f64; 2]], size: f64) -> Vec<(f64, [f64; 2])> { + let mut out = vec![(0.0, [0.0, 0.0]); rest.len()]; + if from.is_empty() { + return out; + } + let k = from.len() as f64; + let cf = from.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0] / k, a[1] + p[1] / k]); + let ct = to.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0] / k, a[1] + p[1] / k]); + let (mut sd, mut sc) = (0.0, 0.0); + for (p, q) in from.iter().zip(to) { + let (u, v) = ([p[0] - cf[0], p[1] - cf[1]], [q[0] - ct[0], q[1] - ct[1]]); + sd += u[0] * v[0] + u[1] * v[1]; + sc += u[0] * v[1] - u[1] * v[0]; + } + let (sn, cs) = if f64::hypot(sd, sc) > 1e-9 { f64::atan2(sc, sd).sin_cos() } else { (0.0, 1.0) }; + let mu = (SETTLE_LENGTH * size).powi(-2); + for t in tris { + let share = mu * tri_area(rest, t) / 3.0; + for i in t { + out[*i].0 += share; + } + } + let far = SETTLE_FROM * size; + for (o, r) in out.iter_mut().zip(rest) { + let u = [r[0] - cf[0], r[1] - cf[1]]; + o.1 = [ct[0] + cs * u[0] - sn * u[1], ct[1] + sn * u[0] + cs * u[1]]; + let d = from.iter().map(|p| (p[0] - r[0]).hypot(p[1] - r[1])).fold(f64::MAX, f64::min); + o.0 *= 1.0 - (-(d / far).powi(2)).exp(); + } + out +} + +/// The held points' terms in the system over (x0, y0, x1, y1, …). +fn add_points_interleaved(a: &mut Sparse, b: &mut [f64], points: &[PointTarget], hold: f64) { + for q in points { + for (u, lu) in q.verts.iter().zip(q.bary) { + for c in 0..2 { + for (v, lv) in q.verts.iter().zip(q.bary) { + a.add(2 * u + c, 2 * v + c, hold * lu * lv); + } + b[2 * u + c] += hold * lu * q.position[c]; + } + } + } +} + +/// The held points' terms in a per-axis matrix. +fn add_points(a: &mut Sparse, points: &[PointTarget], hold: f64) { + for q in points { + for (u, lu) in q.verts.iter().zip(q.bary) { + for (v, lv) in q.verts.iter().zip(q.bary) { + a.add(*u, *v, hold * lu * lv); + } + } + } +} + +/// The held points' terms in the per-axis right-hand sides. +fn add_points_rhs(bx: &mut [f64], by: &mut [f64], points: &[PointTarget], hold: f64) { + for q in points { + for (u, lu) in q.verts.iter().zip(q.bary) { + bx[*u] += hold * lu * q.position[0]; + by[*u] += hold * lu * q.position[1]; + } + } +} + +fn tri_area(rest: &[[f64; 2]], t: &[usize; 3]) -> f64 { + 0.5 * ((rest[t[1]][0] - rest[t[0]][0]) * (rest[t[2]][1] - rest[t[0]][1]) - (rest[t[1]][1] - rest[t[0]][1]) * (rest[t[2]][0] - rest[t[0]][0])).abs() +} + +/// Add `lambda` times the bending energy to a per-axis system. Across an inner edge of length `l` +/// the gradient of a piecewise-linear map jumps by `j` along the edge's normal, and the energy of +/// the edge is `3 l² / (A1 + A2) |j|²`. +fn add_bending(a: &mut Sparse, rest: &[[f64; 2]], tris: &[[usize; 3]], lambda: f64) { + let mut by_edge: BTreeMap<(usize, usize), Vec> = BTreeMap::new(); + for (k, t) in tris.iter().enumerate() { + for (i, j) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + by_edge.entry((i.min(j), i.max(j))).or_default().push(k); + } + } + // The gradient of the linear function that is 1 at corner `k` and 0 at the others. + let corner_gradient = |t: &[usize; 3], k: usize| { + let (o, p, q) = (rest[t[k]], rest[t[(k + 1) % 3]], rest[t[(k + 2) % 3]]); + let n = [p[1] - q[1], q[0] - p[0]]; + let at = n[0] * (o[0] - p[0]) + n[1] * (o[1] - p[1]); + if at.abs() < 1e-12 { [0.0, 0.0] } else { [n[0] / at, n[1] / at] } + }; + for ((i, j), sides) in &by_edge { + let [ka, kb] = sides[..] else { continue }; + let (ta, tb) = (&tris[ka], &tris[kb]); + let e = [rest[*j][0] - rest[*i][0], rest[*j][1] - rest[*i][1]]; + let len = e[0].hypot(e[1]); + let both = tri_area(rest, ta) + tri_area(rest, tb); + if len < 1e-12 || both < 1e-12 { + continue; + } + let normal = [-e[1] / len, e[0] / len]; + let w = lambda * 3.0 * len * len / both; + // The jump as a sum over the four vertices of the diamond. + let mut jump: Vec<(usize, f64)> = Vec::with_capacity(4); + for (t, sign) in [(ta, 1.0), (tb, -1.0)] { + for k in 0..3 { + let g = corner_gradient(t, k); + let c = sign * (g[0] * normal[0] + g[1] * normal[1]); + match jump.iter_mut().find(|s| s.0 == t[k]) { + Some(s) => s.1 += c, + None => jump.push((t[k], c)), + } + } + } + for (u, cu) in &jump { + for (v, cv) in &jump { + a.add(*u, *v, w * cu * cv); + } + } + } +} + +pub(super) fn mean_edge2(rest: &[[f64; 2]], tris: &[[usize; 3]]) -> f64 { if tris.is_empty() { return 1.0; } @@ -311,23 +737,143 @@ fn mean_edge2(rest: &[[f64; 2]], tris: &[[usize; 3]]) -> f64 { s / tris.len() as f64 } -/// Best rigid copy of triangle `rest` over triangle `cur` (rotation about the centroids). -pub fn fit_rigid(rest: [[f64; 2]; 3], cur: [[f64; 2]; 3]) -> [[f64; 2]; 3] { +/// The target for triangle `cur`: its rest shape about the centroid, turned by the rotation of its +/// deformation gradient `F`, with singular values `s1 >= s2`. A rotation alone resists a squeeze and a +/// bulge alike, so nothing makes material squeezed one way spread the other. So the target gives way +/// towards the shape it has now at the same area (`t1 t2 = 1`, with `t1 / t2` a power of `s1 / s2`), +/// and takes on a pressure against the area it has lost or gained (a power of `s1 s2`). Stiffer +/// triangles (`weight`, Starch) give less. +pub fn fit_triangle(rest: [[f64; 2]; 3], cur: [[f64; 2]; 3], weight: f64) -> [[f64; 2]; 3] { let cr = [(rest[0][0] + rest[1][0] + rest[2][0]) / 3.0, (rest[0][1] + rest[1][1] + rest[2][1]) / 3.0]; let cc = [(cur[0][0] + cur[1][0] + cur[2][0]) / 3.0, (cur[0][1] + cur[1][1] + cur[2][1]) / 3.0]; - let (mut sd, mut sc) = (0.0, 0.0); - for k in 0..3 { - let p = [rest[k][0] - cr[0], rest[k][1] - cr[1]]; - let q = [cur[k][0] - cc[0], cur[k][1] - cc[1]]; - sd += p[0] * q[0] + p[1] * q[1]; - sc += p[0] * q[1] - p[1] * q[0]; - } - let ang = sc.atan2(sd); - let (s, c) = ang.sin_cos(); + let [fa, fb, fc, fd] = gradient(rest, cur); + // F = q Rot(a2) + r Reflect(a1), with s1 = q + r and s2 = |q - r|. + let (q, r) = (f64::hypot(fa + fd, fc - fb) / 2.0, f64::hypot(fa - fd, fc + fb) / 2.0); + let (a2, a1) = (f64::atan2(fc - fb, fa + fd), f64::atan2(fc + fb, fa - fd)); + let (s1, s2) = (q + r, (q - r).abs().max(FIT_SMALLEST)); + let t1 = (s1 / s2).clamp(1.0, FIT_MOST_SHAPE).powf(FIT_GIVE / 2.0 / weight.max(1.0)); + let pressure = (s1 * s2).clamp(FIT_MOST_SHAPE.recip(), FIT_MOST_SHAPE).powf(-FIT_PRESSURE / 2.0); + let (qt, rt) = (pressure * (t1 + t1.recip()) / 2.0, pressure * (t1 - t1.recip()) / 2.0); + let (sn2, cs2) = a2.sin_cos(); + let (sn1, cs1) = a1.sin_cos(); + let t = [qt * cs2 + rt * cs1, rt * sn1 - qt * sn2, qt * sn2 + rt * sn1, qt * cs2 - rt * cs1]; let mut out = [[0.0; 2]; 3]; for k in 0..3 { let p = [rest[k][0] - cr[0], rest[k][1] - cr[1]]; - out[k] = [cc[0] + p[0] * c - p[1] * s, cc[1] + p[0] * s + p[1] * c]; + out[k] = [cc[0] + t[0] * p[0] + t[1] * p[1], cc[1] + t[2] * p[0] + t[3] * p[1]]; } out } + +/// A triangle's deformation gradient, row by row; the identity for a degenerate rest triangle. +fn gradient(rest: [[f64; 2]; 3], cur: [[f64; 2]; 3]) -> [f64; 4] { + let (e1, e2) = ([rest[1][0] - rest[0][0], rest[1][1] - rest[0][1]], [rest[2][0] - rest[0][0], rest[2][1] - rest[0][1]]); + let (f1, f2) = ([cur[1][0] - cur[0][0], cur[1][1] - cur[0][1]], [cur[2][0] - cur[0][0], cur[2][1] - cur[0][1]]); + let det = e1[0] * e2[1] - e2[0] * e1[1]; + if det.abs() < 1e-12 { + return [1.0, 0.0, 0.0, 1.0]; + } + [(f1[0] * e2[1] - f2[0] * e1[1]) / det, (f2[0] * e1[0] - f1[0] * e2[0]) / det, (f1[1] * e2[1] - f2[1] * e1[1]) / det, (f2[1] * e1[0] - f1[1] * e2[0]) / det] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bending_costs_nothing_for_an_affine_map() { + // Two triangles of different shapes sharing an edge. + let rest = [[0.0, 0.0], [10.0, 1.0], [4.0, 9.0], [7.0, -8.0]]; + let tris = [[0, 1, 2], [1, 0, 3]]; + let mut a = Sparse::new(4); + add_bending(&mut a, &rest, &tris, 1.0); + let mapped = rest.map(|p| [1.3 * p[0] - 0.4 * p[1] + 5.0, 0.2 * p[0] + 0.9 * p[1] - 2.0]); + for c in 0..2 { + let x: Vec = mapped.iter().map(|p| p[c]).collect(); + for r in &a.rows { + let y: f64 = r.iter().map(|(j, v)| v * x[*j]).sum(); + assert!(y.abs() < 1e-9, "{y}"); + } + } + // A crease does cost: lift the far vertex off the plane of the map. + let x = [0.0, 10.0, 4.0, 12.0]; + let e: f64 = a.rows.iter().enumerate().map(|(i, r)| x[i] * r.iter().map(|(j, v)| v * x[*j]).sum::()).sum(); + assert!(e > 1e-3, "{e}"); + } + + #[test] + fn the_factor_solves_what_conjugate_gradients_solve() { + // A path of springs with one end held. + let n = 40; + let mut a = Sparse::new(n); + for i in 0..n - 1 { + a.add(i, i, 2.0); + a.add(i + 1, i + 1, 2.0); + a.add(i, i + 1, -2.0); + a.add(i + 1, i, -2.0); + } + let b: Vec = (0..n).map(|i| (i as f64 * 0.7).sin()).collect(); + let free: Vec = (0..n).map(|i| i != 7).collect(); + let (mut x, mut y) = (vec![0.0; n], vec![0.0; n]); + x[7] = 3.0; + y[7] = 3.0; + let f = Factor::new(&a, &free, MAX_FACTOR).unwrap(); + f.solve(&b, &mut x); + solve(&a, &b, &mut y, &free); + assert_eq!(x[7], 3.0); + for (p, q) in x.iter().zip(&y) { + assert!((p - q).abs() < 1e-8, "{p} vs {q}"); + } + } + + #[test] + fn a_singular_matrix_has_no_factor_and_the_solve_still_runs() { + let mut a = Sparse::new(2); + a.add(0, 0, 1.0); + a.add(1, 1, 1.0); + a.add(0, 1, -1.0); + a.add(1, 0, -1.0); + let s = System::new(a, vec![true, true], MAX_FACTOR); + assert!(s.factor.is_none()); + let mut x = vec![1.0, 1.0]; + s.solve(&[0.0, 0.0], &mut x); + assert!(x.iter().all(|v| v.is_finite())); + } + + /// Springs between unknowns `k` apart along a path of `n`, with stiffness `s(i)`, and a little + /// to the ground so nothing is loose. + fn springs(n: usize, k: usize, s: impl Fn(usize) -> f64) -> Sparse { + let mut a = Sparse::new(n); + for i in 0..n { + a.add(i, i, 0.01); + } + for i in 0..n - k { + a.add(i, i, s(i)); + a.add(i + k, i + k, s(i)); + a.add(i, i + k, -s(i)); + a.add(i + k, i, -s(i)); + } + a + } + + fn solved(s: &System, n: usize) -> Vec { + let b: Vec = (0..n).map(|i| (i as f64 * 0.7).sin()).collect(); + let mut x = vec![0.0; n]; + x[3] = 2.0; + s.solve(&b, &mut x); + x + } + + #[test] + fn a_factor_over_the_limit_hands_over_to_conjugate_gradients() { + let n = 60; + let free: Vec = (0..n).map(|i| i != 3).collect(); + let factored = System::new(springs(n, 1, |_| 2.0), free.clone(), MAX_FACTOR); + assert!(factored.factor.is_some()); + let capped = System::new(springs(n, 1, |_| 2.0), free, 10); + assert!(capped.factor.is_none()); + for (p, q) in solved(&factored, n).iter().zip(&solved(&capped, n)) { + assert!((p - q).abs() < 1e-8, "{p} vs {q}"); + } + } +} diff --git a/crates/effects/src/puppet/legacy.rs b/crates/effects/src/puppet/legacy.rs new file mode 100644 index 000000000..22effc6c8 --- /dev/null +++ b/crates/effects/src/puppet/legacy.rs @@ -0,0 +1,343 @@ +//! The first Puppet solve and drawing, kept so rigs saved with it look the same when opened. +//! +//! Instances saved before the Solver Version parameter existed (see [`super::SOLVER_ORIGINAL`] and +//! `migrate::legacy_default`) render here: each moving pin holds its nearest mesh vertex, Mesh +//! Rotation Refinement gives up to 10 extra rigid-fit rounds (`refinement / 10`), the +//! two-step solve of Igarashi et al. fits rigid triangles, and the deformed triangles are drawn +//! straight with 2×2 coverage samples per pixel. New instances use the current solve. + +use effectcraft_keyframe::Value; +use effectcraft_raster::Image; +use rayon::prelude::*; + +use super::arap::{self, EdgeTarget, Handles, Sparse}; +use super::{Mesh, Pin, PinKind, bary, depths, mesh_for, nearest, parse, starch_weights}; +use crate::{Buf, EffectCtx, Params}; + +/// Extra rigid-fit rounds for the Mesh Rotation Refinement parameter. +pub(super) fn rounds(params: &Params) -> usize { + (params.get("refinement").map(Value::as_f64).unwrap_or(20.0) / 10.0).round().clamp(0.0, 10.0) as usize +} + +/// Solve the deformation of `mesh` for `pins`, each moving pin holding its nearest vertex. +pub(super) fn solve(mesh: &Mesh, pins: &[Pin], refine: usize) -> Vec<[f64; 2]> { + let mut h = Handles::default(); + let mut adj: Vec> = vec![vec![]; mesh.verts.len()]; + for t in &mesh.tris { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + if !adj[a].contains(&b) { + adj[a].push(b); + } + if !adj[b].contains(&a) { + adj[b].push(a); + } + } + } + let mut used = std::collections::HashSet::new(); + for p in pins { + let Some(v) = nearest(&mesh.verts, p.rest) else { continue }; + let r = mesh.verts[v]; + if p.kind.moves() && used.insert(v) { + h.fixed.push((v, [p.position[0] + r[0] - p.rest[0], p.position[1] + r[1] - p.rest[1]])); + } + if matches!(p.kind, PinKind::Advanced | PinKind::Bend) { + let (s, c) = p.rotation.to_radians().sin_cos(); + for &j in &adj[v] { + let e = [mesh.verts[j][0] - r[0], mesh.verts[j][1] - r[1]]; + let vec = [p.scale * (e[0] * c - e[1] * s), p.scale * (e[0] * s + e[1] * c)]; + h.edges.push(EdgeTarget { i: v, j, vec, weight: 10.0 }); + } + } + } + if h.fixed.is_empty() && h.edges.is_empty() { + return mesh.verts.clone(); + } + let w = starch_weights(mesh, pins); + deform(&mesh.verts, &mesh.tris, &w, &h, refine) +} + +const REG: f64 = 1e-9; + +/// Deform a mesh: `rest` vertices, CCW `tris` with per-triangle `weights` (1 = normal, larger = +/// stiffer), constraints (`h.points` unused), and `refine` extra rigid-fit iterations. +/// +/// 1. **Similarity step.** Each triangle edge `(i, j)` expresses the third vertex `k` in the edge's +/// local frame; minimising the error of that relation over every triangle, with the pinned +/// vertices fixed, gives a deformation that is locally a similarity. +/// 2. **Scale-adjustment step.** Each triangle of the result is fitted with a rigid copy of its +/// rest shape ([`fit_rigid`]), and the positions minimise the difference between every +/// triangle's edge vectors and its fitted ones; extra rounds repeat this on its own result. +fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handles, refine: usize) -> Vec<[f64; 2]> { + let n = rest.len(); + if n == 0 { + return vec![]; + } + // Initial guess: rest translated by the mean handle displacement. + let mut t = [0.0, 0.0]; + for (i, p) in &h.fixed { + t[0] += p[0] - rest[*i][0]; + t[1] += p[1] - rest[*i][1]; + } + if !h.fixed.is_empty() { + t[0] /= h.fixed.len() as f64; + t[1] /= h.fixed.len() as f64; + } + let x0: Vec<[f64; 2]> = rest.iter().map(|p| [p[0] + t[0], p[1] + t[1]]).collect(); + // One pin and no edge targets: every rotation and scale about the pin costs nothing, and the + // regulariser that picks the translation is too weak to stop CG turning round-off into a + // visible rotation (#313). The translation is the exact solution. + if h.fixed.len() == 1 && h.edges.is_empty() { + return x0; + } + let mut fixed = vec![false; n]; + for (i, _) in &h.fixed { + fixed[*i] = true; + } + let w = |k: usize| weights.get(k).copied().unwrap_or(1.0); + let scale2 = arap::mean_edge2(rest, tris).max(1e-12); + + // ---- Step 1: similarity-invariant energy over 2n unknowns (x0, y0, x1, y1, …). + let mut a = Sparse::new(2 * n); + let mut b = vec![0.0; 2 * n]; + for (k, t) in tris.iter().enumerate() { + let wk = w(k); + for (i, j, l) in [(t[0], t[1], t[2]), (t[1], t[2], t[0]), (t[2], t[0], t[1])] { + let e = [rest[j][0] - rest[i][0], rest[j][1] - rest[i][1]]; + let d = [rest[l][0] - rest[i][0], rest[l][1] - rest[i][1]]; + let ee = e[0] * e[0] + e[1] * e[1]; + if ee <= 1e-18 { + continue; + } + // R90(u) = (-u.y, u.x). + let r90 = [-e[1], e[0]]; + let x = (d[0] * e[0] + d[1] * e[1]) / ee; + let y = (d[0] * r90[0] + d[1] * r90[1]) / ee; + // residual = B_l v_l + B_i v_i + B_j v_j with 2x2 blocks; R = [[0,-1],[1,0]]. + let bl = [[1.0, 0.0], [0.0, 1.0]]; + let bi = [[x - 1.0, -y], [y, x - 1.0]]; + let bj = [[-x, y], [-y, -x]]; + let blocks = [(l, bl), (i, bi), (j, bj)]; + for (va, ba) in &blocks { + for (vb, bb) in &blocks { + // ba^T bb + for r in 0..2 { + for c in 0..2 { + let v = ba[0][r] * bb[0][c] + ba[1][r] * bb[1][c]; + if v != 0.0 { + a.add(2 * va + r, 2 * vb + c, wk * v); + } + } + } + } + } + } + } + for e in &h.edges { + let ww = e.weight; + for c in 0..2 { + a.add(2 * e.i + c, 2 * e.i + c, ww); + a.add(2 * e.j + c, 2 * e.j + c, ww); + a.add(2 * e.i + c, 2 * e.j + c, -ww); + a.add(2 * e.j + c, 2 * e.i + c, -ww); + b[2 * e.j + c] += ww * e.vec[c]; + b[2 * e.i + c] -= ww * e.vec[c]; + } + } + let reg = REG * scale2.recip().min(1.0); + for i in 0..n { + for c in 0..2 { + a.add(2 * i + c, 2 * i + c, reg); + b[2 * i + c] += reg * x0[i][c]; + } + } + let mut x: Vec = x0.iter().flat_map(|p| [p[0], p[1]]).collect(); + for (i, p) in &h.fixed { + x[2 * i] = p[0]; + x[2 * i + 1] = p[1]; + } + let free2: Vec = (0..2 * n).map(|k| !fixed[k / 2]).collect(); + arap::solve(&a, &b, &mut x, &free2); + let mut cur: Vec<[f64; 2]> = (0..n).map(|i| [x[2 * i], x[2 * i + 1]]).collect(); + + // ---- Step 2: fit rigid triangles, then match edge vectors (x and y separately). + let mut l = Sparse::new(n); + for (k, t) in tris.iter().enumerate() { + let wk = w(k); + for (i, j) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + l.add(i, i, wk); + l.add(j, j, wk); + l.add(i, j, -wk); + l.add(j, i, -wk); + } + } + for e in &h.edges { + l.add(e.i, e.i, e.weight); + l.add(e.j, e.j, e.weight); + l.add(e.i, e.j, -e.weight); + l.add(e.j, e.i, -e.weight); + } + for i in 0..n { + l.add(i, i, reg); + } + let free1: Vec = (0..n).map(|i| !fixed[i]).collect(); + for _ in 0..=refine { + let mut bx = vec![0.0; n]; + let mut by = vec![0.0; n]; + for (k, t) in tris.iter().enumerate() { + let wk = w(k); + let f = fit_rigid([rest[t[0]], rest[t[1]], rest[t[2]]], [cur[t[0]], cur[t[1]], cur[t[2]]]); + for (a2, b2) in [(0, 1), (1, 2), (2, 0)] { + let (i, j) = (t[a2], t[b2]); + let d = [f[b2][0] - f[a2][0], f[b2][1] - f[a2][1]]; + bx[j] += wk * d[0]; + bx[i] -= wk * d[0]; + by[j] += wk * d[1]; + by[i] -= wk * d[1]; + } + } + for e in &h.edges { + bx[e.j] += e.weight * e.vec[0]; + bx[e.i] -= e.weight * e.vec[0]; + by[e.j] += e.weight * e.vec[1]; + by[e.i] -= e.weight * e.vec[1]; + } + for i in 0..n { + bx[i] += reg * x0[i][0]; + by[i] += reg * x0[i][1]; + } + let mut xs: Vec = cur.iter().map(|p| p[0]).collect(); + let mut ys: Vec = cur.iter().map(|p| p[1]).collect(); + for (i, p) in &h.fixed { + xs[*i] = p[0]; + ys[*i] = p[1]; + } + arap::solve(&l, &bx, &mut xs, &free1); + arap::solve(&l, &by, &mut ys, &free1); + cur = (0..n).map(|i| [xs[i], ys[i]]).collect(); + } + cur +} + +/// Best rigid copy of triangle `rest` over triangle `cur` (rotation about the centroids). +fn fit_rigid(rest: [[f64; 2]; 3], cur: [[f64; 2]; 3]) -> [[f64; 2]; 3] { + let cr = [(rest[0][0] + rest[1][0] + rest[2][0]) / 3.0, (rest[0][1] + rest[1][1] + rest[2][1]) / 3.0]; + let cc = [(cur[0][0] + cur[1][0] + cur[2][0]) / 3.0, (cur[0][1] + cur[1][1] + cur[2][1]) / 3.0]; + let (mut sd, mut sc) = (0.0, 0.0); + for k in 0..3 { + let p = [rest[k][0] - cr[0], rest[k][1] - cr[1]]; + let q = [cur[k][0] - cc[0], cur[k][1] - cc[1]]; + sd += p[0] * q[0] + p[1] * q[1]; + sc += p[0] * q[1] - p[1] * q[0]; + } + let ang = sc.atan2(sd); + let (s, c) = ang.sin_cos(); + let mut out = [[0.0; 2]; 3]; + for k in 0..3 { + let p = [rest[k][0] - cr[0], rest[k][1] - cr[1]]; + out[k] = [cc[0] + p[0] * c - p[1] * s, cc[1] + p[0] * s + p[1] * c]; + } + out +} + +/// Draw the Puppet effect's meshes as the first version did. +pub(super) fn render(ctx: &EffectCtx, buf: Buf) -> Buf { + let meshes = parse(ctx.params); + if meshes.is_empty() { + return buf; + } + let refine = rounds(ctx.params); + // Triangles of every mesh in pixel space: (rest px, deformed px, depth). + let mut tris: Vec<([[f64; 2]; 3], [[f64; 2]; 3], f64)> = vec![]; + let px = |q: [f64; 2]| [q[0] * buf.scale + buf.offset[0], q[1] * buf.scale + buf.offset[1]]; + for m in &meshes { + let mesh = mesh_for(&buf, m); + if mesh.tris.is_empty() { + continue; + } + let def = solve(&mesh, &m.pins, refine); + let dep = depths(&mesh, &m.pins); + for (k, t) in mesh.tris.iter().enumerate() { + let (Some(a), Some(b), Some(c), Some(d)) = (def.get(t[0]), def.get(t[1]), def.get(t[2]), dep.get(k)) else { continue }; + let d3 = [px(*a), px(*b), px(*c)]; + // A pin position that isn't a number draws nothing. + if d3.iter().flatten().any(|x| !x.is_finite()) { + continue; + } + let r = [px(mesh.verts[t[0]]), px(mesh.verts[t[1]]), px(mesh.verts[t[2]])]; + tris.push((r, d3, *d)); + } + } + if tris.is_empty() { + return buf; + } + // Stable sort: back to front. + tris.sort_by(|a, b| a.2.total_cmp(&b.2)); + rasterize(&buf, &tris) +} + +/// Texture-map `buf` through triangles (rest px → deformed px), back to front. +fn rasterize(buf: &Buf, tris: &[([[f64; 2]; 3], [[f64; 2]; 3], f64)]) -> Buf { + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for (_, d, _) in tris { + for p in d { + x0 = x0.min(p[0]); + y0 = y0.min(p[1]); + x1 = x1.max(p[0]); + y1 = y1.max(p[1]); + } + } + let ox = (x0.floor() as i64).saturating_sub(1); + let oy = (y0.floor() as i64).saturating_sub(1); + let w = (x1.ceil() as i64).saturating_add(1).saturating_sub(ox).clamp(1, 16384) as u32; + let h = (y1.ceil() as i64).saturating_add(1).saturating_sub(oy).clamp(1, 16384) as u32; + let mut out = Image::new(w, h); + // Triangle y-ranges for row bucketing. + let ranges: Vec<(f64, f64)> = tris.iter().map(|(_, d, _)| (d[0][1].min(d[1][1]).min(d[2][1]), d[0][1].max(d[1][1]).max(d[2][1]))).collect(); + const SUB: [[f64; 2]; 4] = [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]]; + out.rows_mut().for_each(|(row, line)| { + let y = oy.saturating_add(row as i64) as f64; + let n = line.len(); + let mut cover = vec![0u8; n]; + let mut center: Vec> = vec![None; n]; + let mut any: Vec> = vec![None; n]; + for (k, ((_, d, _), (ya, yb))) in tris.iter().zip(&ranges).enumerate() { + if *yb < y || *ya > y + 1.0 { + continue; + } + let xa = ((d[0][0].min(d[1][0]).min(d[2][0]).floor() as i64).saturating_sub(ox).max(0) as usize).min(n); + let xb = ((d[0][0].max(d[1][0]).max(d[2][0]).ceil() as i64).saturating_sub(ox).saturating_add(1).max(0) as usize).min(n); + for (i, ((cv, ce), an)) in cover.iter_mut().zip(center.iter_mut()).zip(any.iter_mut()).enumerate().take(xb).skip(xa) { + let x = ox.saturating_add(i as i64) as f64; + for (s, o) in SUB.iter().enumerate() { + if let Some(l) = bary(d[0], d[1], d[2], [x + o[0], y + o[1]]) + && l.iter().all(|v| *v >= -1e-9) + { + *cv |= 1 << s; + *an = Some(k); + } + } + if let Some(l) = bary(d[0], d[1], d[2], [x + 0.5, y + 0.5]) + && l.iter().all(|v| *v >= -1e-9) + { + *ce = Some(k); + } + } + } + for (i, px) in line.iter_mut().enumerate() { + let (Some(cv), Some(ce), Some(an)) = (cover.get(i), center.get(i), any.get(i)) else { continue }; + let c = cv.count_ones(); + let Some(k) = ce.or(*an) else { continue }; + if c == 0 && ce.is_none() { + continue; + } + let Some((r, d, _)) = tris.get(k) else { continue }; + let p = [ox.saturating_add(i as i64) as f64 + 0.5, y + 0.5]; + let Some(l) = bary(d[0], d[1], d[2], p) else { continue }; + let src = [l[0] * r[0][0] + l[1] * r[1][0] + l[2] * r[2][0], l[0] * r[0][1] + l[1] * r[1][1] + l[2] * r[2][1]]; + let s = buf.img.sample_bilinear(src[0], src[1]); + let cov = if ce.is_some() && c == 4 { 1.0 } else { c.max(1) as f32 / 4.0 }; + *px = [s[0] * cov, s[1] * cov, s[2] * cov, s[3] * cov]; + } + }); + Buf { img: out, offset: [buf.offset[0] - ox as f64, buf.offset[1] - oy as f64], scale: buf.scale } +} diff --git a/crates/effects/src/puppet/tests.rs b/crates/effects/src/puppet/tests.rs index c2db999e1..17b1c8ba6 100644 --- a/crates/effects/src/puppet/tests.rs +++ b/crates/effects/src/puppet/tests.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use super::mesh::*; use super::*; use crate::{EffectEnv, flatten_params, instantiate}; @@ -359,3 +361,952 @@ fn single_pin_on_a_traced_solid_does_not_rotate_it() { } } } + +// ------------------------------------------------------------------------------------------ +// #2866: deformation quality, pinned to measurements on far drags. The "was" numbers are the +// renderer before that work; these meshes are what the Puppet Pin tool builds for a 1280x720 +// solid. + +fn traced_solid() -> Mesh { + let (w, h) = (1280, 720); + let o = outline(&vec![1.0; w * h], w, h, 1.0, [0.0; 2], [640.0, 360.0], 3.0); + triangulate(&o, &MeshOpts::default()) +} + +fn three_pins(dragged_to: [f64; 2]) -> Vec { + let (a, b, c) = ([200.0, 360.0], [640.0, 360.0], [1080.0, 360.0]); + vec![pin(PinKind::Position, a, a), pin(PinKind::Position, b, b), pin(PinKind::Position, c, dragged_to)] +} + +fn default_rounds() -> usize { + refinement_rounds(&flatten_params(&puppet_fx(&[]), &mut |p| p.value.clone())) +} + +/// The deformation gradient of triangle `t`, and its singular values (the second negative when +/// the triangle is flipped). +fn gradient(rest: &[[f64; 2]], def: &[[f64; 2]], t: &[usize; 3]) -> ([f64; 4], f64, f64) { + let e = |p: &[[f64; 2]], a: usize, b: usize| [p[t[b]][0] - p[t[a]][0], p[t[b]][1] - p[t[a]][1]]; + let (e1, e2, f1, f2) = (e(rest, 0, 1), e(rest, 0, 2), e(def, 0, 1), e(def, 0, 2)); + let det = e1[0] * e2[1] - e2[0] * e1[1]; + let g = [ + (f1[0] * e2[1] - f2[0] * e1[1]) / det, + (f2[0] * e1[0] - f1[0] * e2[0]) / det, + (f1[1] * e2[1] - f2[1] * e1[1]) / det, + (f2[1] * e1[0] - f1[1] * e2[0]) / det, + ]; + let (q, r) = (((g[0] + g[3]).hypot(g[2] - g[1])) / 2.0, ((g[0] - g[3]).hypot(g[2] + g[1])) / 2.0); + let flipped = g[0] * g[3] - g[1] * g[2] < 0.0; + (g, q + r, if flipped { -(q - r).abs() } else { (q - r).abs() }) +} + +/// Smallest singular value, and the largest and mean jump of the gradient across an edge (the +/// crease a straight line in the image gets there). +fn creases(rest: &[[f64; 2]], def: &[[f64; 2]], tris: &[[usize; 3]]) -> (f64, f64, f64) { + let grads: Vec<_> = tris.iter().map(|t| gradient(rest, def, t)).collect(); + let mut across: HashMap<(usize, usize), Vec> = HashMap::new(); + for (k, t) in tris.iter().enumerate() { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + across.entry((a.min(b), a.max(b))).or_default().push(k); + } + } + let jumps: Vec = + across.values().filter(|k| k.len() == 2).map(|k| (0..4).map(|i| (grads[k[0]].0[i] - grads[k[1]].0[i]).powi(2)).sum::().sqrt()).collect(); + (grads.iter().map(|g| g.2).fold(f64::MAX, f64::min), jumps.iter().copied().fold(0.0, f64::max), jumps.iter().sum::() / jumps.len().max(1) as f64) +} + +/// The rigidity energy per unit area: how far the triangles' gradients are from rotations. +fn rigidity(m: &Mesh, def: &[[f64; 2]]) -> f64 { + let (mut e, mut a) = (0.0, 0.0); + for t in &m.tris { + let (_, s1, s2) = gradient(&m.verts, def, t); + let area = cross(m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]) * 0.5; + e += area * ((s1 - 1.0).powi(2) + (s2 - 1.0).powi(2)); + a += area; + } + e / a +} + +#[test] +fn the_default_refinement_converges_on_a_far_drag() { + // Was: 1.13 mean edges from the converged shape, with twice its rigidity energy (2 rounds). + let m = traced_solid(); + let pins = three_pins([1000.0, -60.0]); + let d = solve(&m, &pins, default_rounds()); + let end = solve(&m, &pins, 400); + let edge = m.tris.iter().map(|t| (m.verts[t[0]][0] - m.verts[t[1]][0]).hypot(m.verts[t[0]][1] - m.verts[t[1]][1])).sum::() / m.tris.len() as f64; + let rms = (d.iter().zip(&end).map(|(a, b)| (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sum::() / d.len() as f64).sqrt() / edge; + assert!(rms < 0.06, "{rms} mean edges from the converged shape"); + let (e, conv) = (rigidity(&m, &d), rigidity(&m, &end)); + assert!(e < conv * 1.02, "rigidity energy {e} vs converged {conv}"); +} + +#[test] +fn pins_do_not_crease_or_fold_the_mesh() { + let m = traced_solid(); + let rounds = default_rounds(); + // Dragged far: was smallest singular value -0.07 (a fold), largest crease 2.13. + let (s, crease, _) = creases(&m.verts, &solve(&m, &three_pins([1000.0, -60.0]), rounds), &m.tris); + assert!(s > 0.6 && crease < 0.4, "smallest singular value {s}, crease {crease}"); + // Pulled straight out: was -0.10 and 2.45, three folded triangles and a chevron through the pins. + let (s, crease, _) = creases(&m.verts, &solve(&m, &three_pins([1500.0, 360.0]), rounds), &m.tris); + assert!(s > 0.6 && crease < 0.65, "smallest singular value {s}, crease {crease}"); +} + +/// How a drag's strain spreads: (share of the strain energy within one mean edge of a pin, share +/// of the mesh's area there, largest ring's mean strain over the mesh's, 99th percentile over mean). +fn spread(m: &Mesh, pins: &[Pin], def: &[[f64; 2]]) -> (f64, f64, f64, f64) { + let edge = m.tris.iter().map(|t| (m.verts[t[0]][0] - m.verts[t[1]][0]).hypot(m.verts[t[0]][1] - m.verts[t[1]][1])).sum::() / m.tris.len() as f64; + let held: Vec<[f64; 2]> = pins.iter().map(|p| m.verts[nearest(&m.verts, p.rest).unwrap()]).collect(); + let (mut near, mut near_area, mut total, mut area, mut mean) = (0.0, 0.0, 0.0, 0.0, 0.0); + let mut rings = vec![(0.0, 0.0); 32]; + let mut all = vec![]; + for t in &m.tris { + let (_, s1, s2) = gradient(&m.verts, def, t); + let strain = ((s1 - 1.0).powi(2) + (s2 - 1.0).powi(2)).sqrt(); + let a = cross(m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]) * 0.5; + let c = centroid(m, t); + let r = held.iter().map(|h| (h[0] - c[0]).hypot(h[1] - c[1])).fold(f64::MAX, f64::min) / edge; + if r <= 1.0 { + near += a * strain * strain; + near_area += a; + } + let ring = &mut rings[(r as usize).min(31)]; + ring.0 += a * strain; + ring.1 += a; + total += a * strain * strain; + area += a; + mean += a * strain; + all.push(strain); + } + mean /= area; + all.sort_by(f64::total_cmp); + let peak = rings.iter().filter(|r| r.1 > 0.0).map(|r| r.0 / r.1).fold(0.0, f64::max); + (near / total, near_area / area, peak / mean, all[(all.len() - 1) * 99 / 100] / mean) +} + +#[test] +fn a_pin_pull_spreads_through_the_mesh() { + let m = traced_solid(); + let rounds = default_rounds(); + // Holding one vertex: 38 % of the strain energy on the 5 % of the mesh by the pins, the ring + // there at 3.3 times the mean strain. A stiff patch only moved that to a ring around the patch. + for to in [[1000.0, -60.0], [1080.0, 240.0]] { + let pins = three_pins(to); + let (near, near_area, ring, p99) = spread(&m, &pins, &solve(&m, &pins, rounds)); + assert!(near < near_area * 1.3, "{near} of the strain on {near_area} of the area"); + assert!(ring < 1.25 && p99 < 2.0, "largest ring {ring}, 99th percentile {p99} times the mean"); + } +} + +#[test] +fn a_pin_added_where_the_mesh_already_is_barely_moves_it() { + // #318 on a far drag. It isn't nothing: the mesh settles towards the pins' rigid fit, and a new + // pin changes that fit and frees the mesh around it. It was 77 px on this kind of mesh when the + // solve stopped short of converging. + let m = traced_solid(); + let pins = three_pins([1000.0, -60.0]); + let d = solve(&m, &pins, default_rounds()); + for at in [[420.0, 200.0], [860.0, 500.0], [1100.0, 150.0]] { + let v = nearest(&m.verts, at).unwrap(); + let mut more = pins.clone(); + more.push(pin(PinKind::Position, m.verts[v], d[v])); + let after = solve(&m, &more, default_rounds()); + let moved = after.iter().zip(&d).map(|(a, b)| (a[0] - b[0]).hypot(a[1] - b[1])).fold(0.0, f64::max); + assert!(moved < 35.0, "a pin at {at:?} moved the mesh by {moved} px"); + } +} + +#[test] +fn a_pin_holds_the_point_under_it() { + // Was: the nearest vertex at a fixed offset, up to half an edge from the pin once the mesh + // turned, and a second pin on the same vertex was dropped. + let m = traced_solid(); + let (a, b) = (m.verts[nearest(&m.verts, [640.0, 360.0]).unwrap()], [650.0, 372.0]); + let pins = [ + pin(PinKind::Position, [203.0, 351.0], [203.0, 351.0]), + pin(PinKind::Position, a, [a[0], a[1] - 60.0]), + pin(PinKind::Position, b, [b[0] + 30.0, b[1] + 70.0]), + pin(PinKind::Position, [1077.0, 368.0], [1000.0, -60.0]), + ]; + let d = solve(&m, &pins, default_rounds()); + for p in &pins { + let (t, l) = locate(&m, p.rest).unwrap(); + let at = [l[0] * d[t[0]][0] + l[1] * d[t[1]][0] + l[2] * d[t[2]][0], l[0] * d[t[0]][1] + l[1] * d[t[1]][1] + l[2] * d[t[2]][1]]; + assert!((at[0] - p.position[0]).hypot(at[1] - p.position[1]) < 0.05, "{at:?} vs {:?}", p.position); + } +} + +#[test] +fn a_bend_pin_alone_stays_finite_and_turns_the_mesh() { + // No held vertex at all: only the regulariser pins down the translation. + let m = traced_solid(); + let mut bend = pin(PinKind::Bend, [640.0, 360.0], [640.0, 360.0]); + bend.rotation = 20.0; + let d = solve(&m, &[bend], default_rounds()); + assert!(d.iter().flatten().all(|c| c.is_finite())); + let moved = d.iter().zip(&m.verts).map(|(a, b)| (a[0] - b[0]).hypot(a[1] - b[1])).fold(0.0, f64::max); + assert!(moved > 1.0 && moved < 1000.0, "moved {moved}"); +} + +#[test] +fn drawing_follows_a_smooth_curve_through_the_solve() { + let m = traced_solid(); + let d = solve(&m, &three_pins([1000.0, -60.0]), default_rounds()); + let sm = smooth_mesh(&m, &d, 1.0); + // Mesh vertices (and so the pins) stay exactly where the solve put them. + assert_eq!(&sm.deformed[..d.len()], &d[..]); + assert_eq!(&sm.rest[..m.verts.len()], &m.verts[..]); + // Was: creases of 0.127 on average and 2.13 at worst at the triangles' edges. + let (s, worst, mean) = creases(&sm.rest, &sm.deformed, &sm.tris); + assert!(s > 0.4 && worst < 0.3 && mean < 0.04, "smallest singular value {s}, creases {worst} worst, {mean} mean"); + // No cracks: the small triangles cover the rest mesh, and an edge only ever has two sides. + let area: f64 = sm.tris.iter().map(|t| cross(sm.rest[t[0]], sm.rest[t[1]], sm.rest[t[2]]) * 0.5).sum(); + let want: f64 = m.tris.iter().map(|t| cross(m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]) * 0.5).sum(); + assert!((area - want).abs() < 1e-6 * want, "{area} vs {want}"); + let mut sides: HashMap<(usize, usize), u32> = HashMap::new(); + for t in &sm.tris { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + *sides.entry((a.min(b), a.max(b))).or_default() += 1; + } + } + assert!(sides.values().all(|n| *n <= 2)); + let open_small = sides.values().filter(|n| **n == 1).count(); + let open_mesh = { + let mut e: HashMap<(usize, usize), u32> = HashMap::new(); + for t in &m.tris { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + *e.entry((a.min(b), a.max(b))).or_default() += 1; + } + } + e.values().filter(|n| **n == 1).count() + }; + let split = (sm.tris.len() as f64 / m.tris.len() as f64).sqrt().round() as usize; + assert_eq!(open_small, open_mesh * split); +} + +#[test] +fn smoothing_leaves_a_rigid_mesh_alone() { + let m = rect_mesh(100.0, 40.0, 200.0); + // Turned 30 degrees and moved: one affine map over the whole mesh. + let (s, c) = 30f64.to_radians().sin_cos(); + let d: Vec<[f64; 2]> = m.verts.iter().map(|p| [p[0] * c - p[1] * s + 7.0, p[0] * s + p[1] * c - 3.0]).collect(); + let sm = smooth_mesh(&m, &d, 1.0); + assert_eq!(sm.tris, m.tris); + assert_eq!(sm.deformed, d); +} + +/// `rasterize` over one quad (two triangles) from `rest` to `to`, both [x0, y0, x1, y1]. +fn draw_quad(img: Image, rest: [f64; 4], to: [f64; 4]) -> Buf { + let c = |q: [f64; 4]| [[q[0], q[1]], [q[2], q[1]], [q[2], q[3]], [q[0], q[3]]]; + let (r, d) = (c(rest), c(to)); + let tris = [([r[0], r[1], r[2]], [d[0], d[1], d[2]]), ([r[0], r[2], r[3]], [d[0], d[2], d[3]])]; + rasterize(&Buf { img, offset: [0.0; 2], scale: 1.0 }, &tris) +} + +#[test] +fn a_squeezed_image_averages_instead_of_skipping_texels() { + // One-pixel stripes squeezed to a third: one read per pixel lands on every third stripe, + // which was solid black and white bars (0.5 off the true grey). + let mut img = Image::new(150, 40); + for y in 0..40 { + for x in 0..150 { + let v = (x % 2) as f32; + img.set(x, y, [v, v, v, 1.0]); + } + } + let out = draw_quad(img, [0.0, 0.0, 150.0, 40.0], [0.0, 0.0, 50.0, 40.0]); + let worst = (5..45).map(|x| (at(&out, x, 20)[0] - 0.5).abs()).fold(0.0, f32::max); + assert!(worst < 0.2, "{worst} off grey"); +} + +#[test] +fn the_outline_has_a_smooth_ramp_and_shared_edges_no_seam() { + let mut img = Image::new(100, 100); + for y in 0..100 { + for x in 0..100 { + img.set(x, y, [1.0, 1.0, 1.0, 1.0]); + } + } + // A mesh inside the opaque image, so its own edge is the outline. Sheared so the edge + // crosses pixels at every offset: was 3 partial alpha levels (2x2 coverage). + let (r, d) = ([[20.0, 20.0], [80.0, 20.0], [80.0, 80.0], [20.0, 80.0]], [[20.0, 20.0], [80.0, 27.0], [73.0, 87.0], [13.0, 80.0]]); + let tris = [([r[0], r[1], r[2]], [d[0], d[1], d[2]]), ([r[0], r[2], r[3]], [d[0], d[2], d[3]])]; + let out = rasterize(&Buf { img, offset: [0.0; 2], scale: 1.0 }, &tris); + let mut levels: Vec = out.img.data.iter().filter(|p| p[3] > 0.0 && p[3] < 1.0).map(|p| (p[3] * 16.0).round() as i32).collect(); + levels.sort_unstable(); + levels.dedup(); + assert!(levels.len() >= 12, "alpha levels {levels:?}"); + // The diagonal both triangles share leaves every pixel along it opaque. + for k in 8..52 { + let (x, y) = (20 + k - k / 9, 20 + k + k / 9); + assert_eq!(at(&out, x, y)[3], 1.0, "({x},{y})"); + } +} + +#[test] +fn a_sheet_dragged_over_the_mesh_stays_whole() { + // The right half is green, the left half red; dragging the right end back over the left + // lays one half across the other. It was a shatter of both, by triangle number, about half of each. + let (w, h) = (640u32, 360u32); + let mut img = Image::new(w, h); + for y in 0..h { + for x in 0..w { + img.set(x, y, if x < w / 2 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0, 1.0] }); + } + } + let fx = puppet_fx(&[ + (PinKind::Position, [100.0, 180.0], [100.0, 180.0]), + (PinKind::Position, [320.0, 100.0], [320.0, 100.0]), + (PinKind::Position, [540.0, 180.0], [100.0, 180.0]), + ]); + let out = run(&fx, img); + // Where the two halves overlap (around the dragged pin), the dragged one is on top. + let (mut red, mut green) = (0, 0); + for y in 172..188 { + for x in 92..108 { + let p = at(&out, x, y); + if p[3] > 0.99 { + if p[0] > 0.9 { + red += 1; + } else if p[1] > 0.9 { + green += 1; + } + } + } + } + assert!(green > 200 && red < 45, "green {green}, red {red}"); +} + +#[test] +fn a_pin_with_no_number_for_a_position_draws_nothing_and_does_not_crash() { + let mut fx = puppet_fx(&[(PinKind::Position, [14.0, 30.0], [14.0, 30.0]), (PinKind::Position, [50.0, 30.0], [f64::NAN, 10.0])]); + for version in [SOLVER_CURRENT, SOLVER_ORIGINAL] { + fx.get_mut(SOLVER_VERSION).unwrap().value = Value::Enum(version); + let out = run(&fx, test_image()); + assert!(out.img.data.iter().all(|p| p.iter().all(|c| c.is_finite())), "solver {version}"); + } +} + +/// The stress test for how the mesh shares out a pull: a bar of four squares with a pin at the +/// centre of each, the second up by a square and the third down by one. +fn s_curve(triangles: f64) -> (Mesh, Vec, Vec<[f64; 2]>) { + let x = 200.0; + let (w, h) = (800, 200); + let o = outline(&vec![1.0; w * h], w, h, 1.0, [0.0; 2], [100.0, 100.0], 3.0); + let m = triangulate(&o, &MeshOpts { triangles, ..MeshOpts::default() }); + let at = |k: f64, up: f64| pin(PinKind::Position, [(k + 0.5) * x, x / 2.0], [(k + 0.5) * x, x / 2.0 + up]); + let pins = vec![at(0.0, 0.0), at(1.0, -x), at(2.0, x), at(3.0, 0.0)]; + let d = solve(&m, &pins, default_rounds()); + (m, pins, d) +} + +#[test] +fn the_s_curve_shares_its_strain_out() { + // At 350 and 2000 triangles, for origin/main and then for stiff patches at the pins: + // smallest singular value -0.73, -0.78 and -0.21, -0.88 (6, 15, 3 and 22 flipped triangles); + // largest crease 2.82, 4.67 and 1.98, 1.78; largest ring 2.55, 5.62 and 1.15, 1.56 times the + // mean strain. origin/main had 35 % and 26 % of the strain energy within an edge of the pins. + // Stiffening triangles near collapse kept the smallest at 0.2 and up; without it one at 350 + // comes close (1e-4), though none flips. + for (triangles, min_s, max_crease) in [(350.0, 0.0, 0.9), (2000.0, 0.2, 0.6)] { + let (m, pins, d) = s_curve(triangles); + let (s, crease, _) = creases(&m.verts, &d, &m.tris); + assert!(s > min_s, "{triangles} triangles: smallest singular value {s}"); + assert!(crease < max_crease, "{triangles} triangles: crease {crease}"); + let (near, near_area, ring, _) = spread(&m, &pins, &d); + assert!(near < near_area * 1.1, "{triangles} triangles: {near} of the strain on {near_area} of the area"); + assert!(ring < 1.2, "{triangles} triangles: largest ring {ring} times the mean"); + } +} + +#[test] +fn the_s_curve_is_as_even_at_the_second_pin_as_at_the_third() { + // The bar and the pull are symmetric under a half turn about the centre. A pin on its nearest + // vertex broke that (the band beyond the third pin was crushed, not the second's). + let (m, _, d) = s_curve(350.0); + let band = |cx: f64, up: bool| { + // Width of the mesh along the line through the pin, on its outer side. + let (mut low, mut high) = (f64::MAX, f64::MIN); + for (r, p) in m.verts.iter().zip(&d) { + if (r[0] - cx).abs() < 40.0 && (r[1] < 100.0) == up { + low = low.min(p[1]); + high = high.max(p[1]); + } + } + high - low + }; + let (top, bottom) = (band(300.0, true), band(500.0, false)); + assert!((top - bottom).abs() < 0.2 * top.max(bottom), "outer bands {top} and {bottom}"); +} + +/// The stress test for keeping volume and staying local: a square with four pins in a cross, each +/// a fifth of the side from the centre, the top one pulled up to the top edge and the bottom one +/// down to the bottom edge. +fn cross_case(triangles: f64) -> (Mesh, Vec<[f64; 2]>) { + let size = 800.0; + let n = size as usize; + let c = size / 2.0; + let off = 0.2 * size; + let o = outline(&vec![1.0; n * n], n, n, 1.0, [0.0; 2], [c, c], 3.0); + let m = triangulate(&o, &MeshOpts { triangles, ..MeshOpts::default() }); + let hold = |p: [f64; 2]| pin(PinKind::Position, p, p); + let pins = [pin(PinKind::Position, [c, c - off], [c, 0.0]), pin(PinKind::Position, [c, c + off], [c, size]), hold([c - off, c]), hold([c + off, c])]; + let d = solve(&m, &pins, default_rounds()); + (m, d) +} + +#[test] +fn the_cross_keeps_its_volume_and_stays_local() { + // Rest area of the mesh's outline against the deformed, through the triangles' edges. + for (triangles, min_s) in [(350.0, 0.15), (2000.0, 0.2)] { + let (m, d) = cross_case(triangles); + let area = |p: &[[f64; 2]]| m.tris.iter().map(|t| cross(p[t[0]], p[t[1]], p[t[2]]) * 0.5).sum::(); + let grown = area(&d) / area(&m.verts) - 1.0; + let moved = |at: [f64; 2]| { + let v = nearest(&m.verts, at).unwrap(); + (d[v][0] - m.verts[v][0]).hypot(d[v][1] - m.verts[v][1]) + }; + let corner = [[0.0, 0.0], [800.0, 0.0], [0.0, 800.0], [800.0, 800.0]].map(moved).into_iter().fold(0.0, f64::max); + let side = [[0.0, 400.0], [800.0, 400.0]].map(moved).into_iter().fold(0.0, f64::max); + let (s, _, _) = creases(&m.verts, &d, &m.tris); + // Last time: the outline grew 97 % and the corners moved 256 px. + assert!(grown.abs() < 0.2, "{triangles} triangles: area changed by {grown}"); + assert!(corner < 45.0 && side < 70.0, "{triangles} triangles: corners moved {corner} px, sides {side} px"); + assert!(s > min_s, "{triangles} triangles: smallest singular value {s}"); + } +} + +/// The stress test for a hard push: a square of three by three cells, pins at the centres of the left +/// and right columns' cells, the middle left one dragged a fraction of the way to the centre. +fn push_case(triangles: f64, fraction: f64) -> (Mesh, Vec<[f64; 2]>) { + let n = 900; + let o = outline(&vec![1.0; n * n], n, n, 1.0, [0.0; 2], [450.0, 450.0], 3.0); + let m = triangulate(&o, &MeshOpts { triangles, ..MeshOpts::default() }); + let mut pins = vec![]; + for x in [150.0, 750.0] { + for y in [150.0, 450.0, 750.0] { + pins.push(pin(PinKind::Position, [x, y], [x, y])); + } + } + pins[1].position = [150.0 + 300.0 * fraction, 450.0]; + let d = solve(&m, &pins, default_rounds()); + (m, d) +} + +/// Where a rest point lands, through the triangle over it. +fn landed(m: &Mesh, d: &[[f64; 2]], p: [f64; 2]) -> [f64; 2] { + let (t, l) = locate(m, p).unwrap(); + [l[0] * d[t[0]][0] + l[1] * d[t[1]][0] + l[2] * d[t[2]][0], l[0] * d[t[0]][1] + l[1] * d[t[1]][1] + l[2] * d[t[2]][1]] +} + +#[test] +fn a_hard_push_compresses_what_is_ahead_instead_of_folding() { + // Before the bending and settling terms, at the full drag: a flipped triangle at 350 triangles, + // area ratios down to -0.02, and cell lengths 0.15 0.16 0.47 0.66 0.74 0.81. Stiffening + // triangles near collapse kept every ratio above 0.2; without it the least is 0.13. + for triangles in [350.0, 2000.0] { + for fraction in [0.25, 0.5, 0.75, 1.0] { + let (m, d) = push_case(triangles, fraction); + let low = m.tris.iter().map(|t| cross(d[t[0]], d[t[1]], d[t[2]]) / cross(m.verts[t[0]], m.verts[t[1]], m.verts[t[2]])).fold(f64::MAX, f64::min); + assert!(low > 0.1, "{triangles} triangles at {fraction}: area ratio {low}"); + // No two triangles over one point, on a coarse grid. + let mut twice = 0; + for y in (-100..1000).step_by(6) { + for x in (-100..1000).step_by(6) { + let p = [x as f64 + 0.5, y as f64 + 0.5]; + let over = m + .tris + .iter() + .filter(|t| cross(d[t[0]], d[t[1]], p) > 1e-6 && cross(d[t[1]], d[t[2]], p) > 1e-6 && cross(d[t[2]], d[t[0]], p) > 1e-6) + .count(); + twice += (over > 1) as usize; + } + } + assert_eq!(twice, 0, "{triangles} triangles at {fraction}"); + } + let (m, d) = push_case(triangles, 1.0); + let along: Vec<[f64; 2]> = (0..7).map(|k| landed(&m, &d, [150.0 + 100.0 * k as f64, 450.0])).collect(); + let cells: Vec = along.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]) / 100.0).collect(); + // Spread along the way, least just ahead of the pin (the cell it sits in it holds open a + // little), and reaching the far cell. + assert!(cells[0] > 0.2 && cells[5] < 0.82, "{triangles} triangles: cells {cells:?}"); + assert!(cells[1..].windows(2).all(|w| w[0] < w[1] + 0.02), "{triangles} triangles: cells {cells:?}"); + } +} + +#[test] +fn pins_dragged_through_each_other_land_without_hanging_or_blowing_up() { + let m = traced_solid(); + let (a, b, c) = ([200.0, 360.0], [640.0, 360.0], [1080.0, 360.0]); + for pins in [ + vec![pin(PinKind::Position, a, c), pin(PinKind::Position, b, b), pin(PinKind::Position, c, a)], + vec![pin(PinKind::Position, a, b), pin(PinKind::Position, b, b), pin(PinKind::Position, c, b)], + ] { + let d = solve(&m, &pins, default_rounds()); + assert!(d.iter().flatten().all(|v| v.is_finite())); + for p in &pins { + let at = landed(&m, &d, p.rest); + assert!((at[0] - p.position[0]).hypot(at[1] - p.position[1]) < 0.5, "{at:?} vs {:?}", p.position); + } + } +} + +/// Area-weighted mean and 95th percentile of `|log(area ratio)|`. +fn area_change(m: &Mesh, d: &[[f64; 2]]) -> (f64, f64) { + let mut logs: Vec<(f64, f64)> = m + .tris + .iter() + .map(|t| { + let rest = cross(m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]); + ((cross(d[t[0]], d[t[1]], d[t[2]]) / rest).max(0.01).ln().abs(), rest) + }) + .collect(); + let total: f64 = logs.iter().map(|l| l.1).sum(); + let mean = logs.iter().map(|l| l.0 * l.1).sum::() / total; + logs.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut acc = 0.0; + for l in &logs { + acc += l.1; + if acc >= 0.95 * total { + return (mean, l.0); + } + } + (mean, 0.0) +} + +#[test] +fn triangles_keep_their_area_in_all_three_stress_tests() { + // Mean and 95th percentile of |log(area ratio)| at 350 triangles without the area terms: + // push 0.205, 0.641; cross 0.277, 0.932; s_curve 0.182, 0.414. Stiffening triangles far from + // their area brought them to 0.161, 0.385; 0.232, 0.780; 0.126, 0.351, but swung at the + // breaking point; the fit's give alone holds them about where they were. + for triangles in [350.0, 2000.0] { + let (m, d) = push_case(triangles, 1.0); + let (mean, p95) = area_change(&m, &d); + assert!(mean < 0.19 && p95 < 0.7, "push at {triangles}: {mean} {p95}"); + let (m, d) = cross_case(triangles); + let (mean, p95) = area_change(&m, &d); + assert!(mean < 0.31 && p95 < 0.97, "cross at {triangles}: {mean} {p95}"); + let (m, _, d) = s_curve(triangles); + let (mean, p95) = area_change(&m, &d); + assert!(mean < 0.18 && p95 < 0.76, "s_curve at {triangles}: {mean} {p95}"); + } +} + +#[test] +fn material_ahead_of_a_push_bulges_sideways() { + // Without the area terms the column ahead of the pin kept its height (1.07 at most); with + // triangles stiffened far from their area it grew to 1.4. + for triangles in [350.0, 2000.0] { + let (m, d) = push_case(triangles, 1.0); + let (a, b) = (landed(&m, &d, [350.0, 350.0]), landed(&m, &d, [350.0, 550.0])); + let tall = (a[0] - b[0]).hypot(a[1] - b[1]) / 200.0; + assert!(tall > 1.2, "{triangles} triangles: height {tall}"); + } +} + +#[test] +fn pins_pulled_apart_past_what_the_mesh_gives_move_it_smoothly() { + // Two pins 10 px apart pulled 600 px apart: no mesh can follow, and stiffening triangles from + // the last solve's shape swung from pass to pass, so half a pixel more moved it 70 to 470 px. + // The pins' leverage alone moves it about 4 px a pixel. + let m = rect_mesh(500.0, 500.0, 200.0); + let at = + |y: f64| solve(&m, &[pin(PinKind::Position, [250.0, 255.0], [250.0, y]), pin(PinKind::Position, [250.0, 245.0], [250.0, -50.0])], default_rounds()); + let mut last = at(545.0); + for k in 1..=10 { + let next = at(545.0 + k as f64 * 0.5); + let moved = next.iter().zip(&last).map(|(a, b)| (a[0] - b[0]).hypot(a[1] - b[1])).fold(0.0, f64::max); + assert!(moved < 4.0, "half a pixel more moved the mesh {moved} px"); + last = next; + } +} + +// ------------------------------------------------------------------------------------------ +// The solver's limits, and one solve for drawing and the overlay. + +fn with_refinement(fx: &PropGroup, refinement: f64) -> Params { + let mut fx = fx.clone(); + fx.get_mut("refinement").unwrap().value = Value::Scalar(refinement); + flatten_params(&fx, &mut |p| p.value.clone()) +} + +#[test] +fn drawing_and_the_overlay_show_the_same_solve() { + let img = test_image(); + let fx = puppet_fx(&[(PinKind::Position, [14.0, 30.0], [14.0, 30.0]), (PinKind::Position, [50.0, 30.0], [45.0, 8.0])]); + for refinement in [0.0, 2.5, 20.0] { + let params = with_refinement(&fx, refinement); + let buf = Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }; + let shown = overlay(&buf, ¶ms); + assert_eq!(shown.len(), 1); + let (_, mesh, def, pins) = &shown[0]; + let rounds = refinement_rounds(¶ms); + assert_eq!(*def, solve(mesh, pins, rounds), "refinement {refinement}"); + // Asked again, the solve isn't made again. + assert!(Arc::ptr_eq(&solve_shared(mesh, pins, rounds), &solve_shared(mesh, pins, rounds))); + // The drawing covers what the overlay's mesh covers, smoothed as it's drawn, and nothing + // else: pixels with the mesh all round them, over the opaque image, are opaque; pixels with + // none of it near are empty. (The mesh reaches a little past the image's alpha.) + let sm = smooth_mesh(mesh, def, 1.0); + let drawn = Mesh { verts: sm.rest, tris: sm.tris, outline: vec![] }; + let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [64.0, 64.0], seed: 1, adjustment: false, env: EffectEnv::default() }; + let out = crate::apply(crate::find(ID).unwrap(), &ctx, buf); + let (mut inside, mut outside) = (0, 0); + for y in -10..74 { + for x in -10..74 { + let around = [-2.0, 0.0, 2.0].into_iter().flat_map(|dy| [-2.0, 0.0, 2.0].map(|dx| [x as f64 + 0.5 + dx, y as f64 + 0.5 + dy])); + let over: Vec = around.map(|p| contains(&drawn, &sm.deformed, p)).collect(); + let a = at(&out, x, y)[3]; + let src = unmap(&drawn, &sm.deformed, [x as f64 + 0.5, y as f64 + 0.5]); + if over.iter().all(|o| *o) && (14.0..50.0).contains(&src[0]) && (18.0..46.0).contains(&src[1]) { + assert!(a > 0.99, "refinement {refinement}: ({x},{y}) alpha {a} inside the mesh"); + inside += 1; + } else if over.iter().all(|o| !*o) { + assert!(a < 1e-3, "refinement {refinement}: ({x},{y}) alpha {a} away from the mesh"); + outside += 1; + } + } + } + assert!(inside > 500 && outside > 500, "{inside} inside, {outside} outside"); + } +} + +/// Largest distance between two solves of the same mesh, which must be whole and finite to compare +/// (`f64::max` would skip a NaN). +fn farthest_apart(a: &[[f64; 2]], b: &[[f64; 2]]) -> f64 { + assert_eq!(a.len(), b.len(), "the solves have different vertex counts"); + assert!(a.iter().chain(b).all(|p| p[0].is_finite() && p[1].is_finite()), "a solve has a non-finite vertex"); + a.iter().zip(b).map(|(p, q)| (p[0] - q[0]).hypot(p[1] - q[1])).fold(0.0, f64::max) +} + +#[test] +fn conjugate_gradients_land_where_the_factor_does() { + // A factor too large to keep hands the solve to conjugate gradients, which must agree. + let m = traced_solid(); + let pins = three_pins([1000.0, -60.0]); + let cg = solve_with(&m, &pins, default_rounds(), arap::Limits { max_factor: 0, ..arap::LIMITS }); + let factored = solve(&m, &pins, default_rounds()); + let off = farthest_apart(&cg, &factored); + assert!(off < 1e-3, "{off} px apart"); +} + +#[test] +fn stopping_once_the_rounds_settle_changes_nothing_visible() { + let m = traced_solid(); + let (s, s_pins, _) = s_curve(350.0); + let cases = [ + (&m, three_pins([1000.0, -60.0])), + (&m, three_pins([1500.0, 360.0])), + (&m, three_pins([1083.0, 357.0])), + (&m, three_pins([1080.0, 360.0])), + (&s, s_pins), + ]; + for (mesh, pins) in &cases { + for rounds in [default_rounds(), 200] { + let all = solve_with(mesh, pins, rounds, arap::Limits { settled: 0.0, ..arap::LIMITS }); + let early = solve(mesh, pins, rounds); + let off = farthest_apart(&all, &early); + assert!(off < 0.01, "{rounds} rounds, pins at {:?}: {off} px apart", pins.iter().map(|p| p.position).collect::>()); + } + } +} + +// ------------------------------------------------------------------------------------------ +// The refinement parameter, the pins' edge cases and smoothing. + +#[test] +fn mesh_rotation_refinement_maps_to_solver_rounds() { + let fx = puppet_fx(&[]); + assert_eq!(default_rounds(), 40); + for (refinement, rounds) in + [(0.0, 0), (-5.0, 0), (1.0, 2), (37.4, 75), (100.0, 200), (150.0, 200), (f64::NAN, 0), (f64::INFINITY, 200), (f64::NEG_INFINITY, 0)] + { + assert_eq!(refinement_rounds(&with_refinement(&fx, refinement)), rounds, "refinement {refinement}"); + } +} + +/// Where the point at `l` in triangle `t` lands. +fn through(d: &[[f64; 2]], t: [usize; 3], l: [f64; 3]) -> [f64; 2] { + [l[0] * d[t[0]][0] + l[1] * d[t[1]][0] + l[2] * d[t[2]][0], l[0] * d[t[0]][1] + l[1] * d[t[1]][1] + l[2] * d[t[2]][1]] +} + +/// Edges of a mesh with the triangles on each side. +fn sides(m: &Mesh) -> HashMap<(usize, usize), Vec> { + let mut e: HashMap<(usize, usize), Vec> = HashMap::new(); + for (k, t) in m.tris.iter().enumerate() { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + e.entry((a.min(b), a.max(b))).or_default().push(k); + } + } + e +} + +#[test] +fn a_pin_on_a_vertex_holds_that_vertex() { + let m = rect_mesh(100.0, 40.0, 200.0); + let v = nearest(&m.verts, [50.0, 20.0]).unwrap(); + assert!(held_point(&m, m.verts[v]).is_none()); + let to = [m.verts[v][0] + 7.0, m.verts[v][1] - 11.0]; + let d = solve(&m, &[pin(PinKind::Position, [0.0, 20.0], [0.0, 20.0]), pin(PinKind::Position, m.verts[v], to)], default_rounds()); + assert_eq!(d[v], to); +} + +#[test] +fn a_pin_on_a_shared_edge_holds_the_same_point_from_either_side() { + let m = rect_mesh(100.0, 40.0, 200.0); + let rest = |i: usize| m.verts[i]; + let mid = |(a, b): (usize, usize)| [(rest(a)[0] + rest(b)[0]) / 2.0, (rest(a)[1] + rest(b)[1]) / 2.0]; + // The inner edge nearest the middle. + let ((a, b), tk) = sides(&m) + .into_iter() + .filter(|(_, k)| k.len() == 2) + .min_by(|x, y| { + let off = |e: (usize, usize)| (mid(e)[0] - 50.0).hypot(mid(e)[1] - 20.0); + off(x.0).total_cmp(&off(y.0)) + }) + .unwrap(); + let at = mid((a, b)); + let (t, l) = held_point(&m, at).unwrap(); + // One of the two triangles, with no weight on its third corner. + assert!(tk.iter().any(|k| m.tris[*k] == t)); + for (i, w) in t.iter().zip(l) { + if *i != a && *i != b { + assert!(w.abs() < 1e-9, "{l:?}"); + } + } + let to = [at[0] + 9.0, at[1] + 6.0]; + let d = solve(&m, &[pin(PinKind::Position, [0.0, 20.0], [0.0, 20.0]), pin(PinKind::Position, at, to)], default_rounds()); + for k in tk { + let t = m.tris[k]; + let p = through(&d, t, t.map(|i| if i == a || i == b { 0.5 } else { 0.0 })); + assert!((p[0] - to[0]).hypot(p[1] - to[1]) < 0.05, "through triangle {k}: {p:?} vs {to:?}"); + } +} + +#[test] +fn a_pin_just_off_the_outline_holds_a_point_and_one_further_off_its_nearest_vertex() { + let m = rect_mesh(100.0, 40.0, 200.0); + // An outline edge along the top, y = 0, away from the corners. + let (a, b) = sides(&m) + .into_iter() + .filter(|(e, k)| k.len() == 1 && m.verts[e.0][1] == 0.0 && m.verts[e.1][1] == 0.0 && m.verts[e.0][0].min(m.verts[e.1][0]) > 20.0) + .map(|(e, _)| e) + .min_by(|x, y| m.verts[x.0][0].total_cmp(&m.verts[y.0][0])) + .unwrap(); + let x = (m.verts[a][0] + m.verts[b][0]) / 2.0; + // Round-off out of the mesh still holds the point on the outline. + let (t, l) = held_point(&m, [x, -1e-12]).unwrap(); + assert!(t.contains(&a) && t.contains(&b) && l.iter().all(|w| *w >= -1e-9), "{t:?} {l:?}"); + // Further out, nothing is under the pin: it holds its nearest vertex at the same offset. + let off = [x, -0.01]; + assert!(locate(&m, off).is_none() && held_point(&m, off).is_none()); + let v = nearest(&m.verts, off).unwrap(); + let to = [off[0] + 5.0, off[1] - 8.0]; + let d = solve(&m, &[pin(PinKind::Position, [0.0, 20.0], [0.0, 20.0]), pin(PinKind::Position, off, to)], default_rounds()); + let want = [to[0] + m.verts[v][0] - off[0], to[1] + m.verts[v][1] - off[1]]; + assert!((d[v][0] - want[0]).abs() < 1e-9 && (d[v][1] - want[1]).abs() < 1e-9, "{:?} vs {want:?}", d[v]); +} + +#[test] +fn a_bend_pin_alone_keeps_its_vertex_in_place() { + // Nothing held: the Bend pin's own vertex stays put and the mesh turns about it. + let m = rect_mesh(100.0, 40.0, 200.0); + let mut bend = pin(PinKind::Bend, [50.0, 20.0], [50.0, 20.0]); + bend.rotation = 30.0; + let d = solve(&m, &[bend], default_rounds()); + let v = nearest(&m.verts, [50.0, 20.0]).unwrap(); + assert_eq!(d[v], m.verts[v]); + // The edges at the pin turn its way. + let turned: Vec = sides(&m) + .into_keys() + .filter(|(a, b)| *a == v || *b == v) + .map(|(a, b)| { + let j = if a == v { b } else { a }; + let (r, e) = ([m.verts[j][0] - m.verts[v][0], m.verts[j][1] - m.verts[v][1]], [d[j][0] - d[v][0], d[j][1] - d[v][1]]); + (r[0] * e[1] - r[1] * e[0]).atan2(r[0] * e[0] + r[1] * e[1]).to_degrees() + }) + .collect(); + assert!(turned.iter().all(|a| *a > 10.0 && *a < 30.0), "{turned:?}"); +} + +#[test] +fn smoothing_falls_back_to_the_solve_when_it_cannot_split() { + let m = rect_mesh(100.0, 40.0, 200.0); + let d = solve(&m, &[pin(PinKind::Position, [0.0, 20.0], [0.0, 20.0]), pin(PinKind::Position, [100.0, 20.0], [80.0, 50.0])], default_rounds()); + // Vertices that don't match the mesh: drawn as they are. + let short = &d[..d.len() - 1]; + let sm = smooth_mesh(&m, short, 1.0); + assert_eq!((&sm.rest, &sm.deformed[..], &sm.tris), (&m.verts, short, &m.tris)); + assert_eq!(sm.parent, (0..m.tris.len()).collect::>()); + // A buffer so small that no split is worth it. + let sm = smooth_mesh(&m, &d, 1e-6); + assert_eq!((&sm.deformed, &sm.tris), (&d, &m.tris)); +} + +#[test] +fn every_small_triangle_lies_in_the_triangle_it_came_from() { + let m = traced_solid(); + let d = solve(&m, &three_pins([1000.0, -60.0]), default_rounds()); + let sm = smooth_mesh(&m, &d, 1.0); + assert!(sm.tris.len() > m.tris.len()); + assert_eq!(sm.parent.len(), sm.tris.len()); + let v = &m.verts; + let mut count = vec![0usize; m.tris.len()]; + for (t, k) in sm.tris.iter().zip(&sm.parent) { + let p = m.tris[*k]; + for i in t { + let l = bary(v[p[0]], v[p[1]], v[p[2]], sm.rest[*i]).unwrap(); + assert!(l.iter().all(|x| *x >= -1e-9), "corner {i} of a piece of triangle {k}: {l:?}"); + } + count[*k] += 1; + } + // Every triangle split the same way. + assert!(count.iter().all(|c| *c == count[0]), "{:?}", &count[..8]); +} + +/// Where the drawing puts the rest point `p`: through the small triangle over it. +fn drawn(s: &SmoothMesh, p: [f64; 2]) -> Option<[f64; 2]> { + s.tris.iter().find_map(|t| { + let l = bary(s.rest[t[0]], s.rest[t[1]], s.rest[t[2]], p).filter(|l| l.iter().all(|x| *x >= -1e-9))?; + Some([0, 1].map(|c| l[0] * s.deformed[t[0]][c] + l[1] * s.deformed[t[1]][c] + l[2] * s.deformed[t[2]][c])) + }) +} + +#[test] +fn the_drawing_keeps_the_image_under_each_pin() { + // Smoothing bent the drawn mesh away from the points the pins hold inside triangles: the image + // under a pin landed up to 10 px from it on these rigs. + let m = traced_solid(); + let (s, s_pins, _) = s_curve(350.0); + let mut cases: Vec<(&Mesh, Vec)> = [[1000.0, -60.0], [1500.0, 360.0], [1083.0, 357.0]].into_iter().map(|to| (&m, three_pins(to))).collect(); + cases.push((&s, s_pins)); + for (mesh, pins) in &cases { + let d = solve(mesh, pins, default_rounds()); + let sm = smooth_mesh_holding(mesh, &d, 1.0, &held_points(mesh, pins)); + for p in pins { + let Some((t, l)) = held_point(mesh, p.rest) else { continue }; + let solved = [0, 1].map(|c| l[0] * d[t[0]][c] + l[1] * d[t[1]][c] + l[2] * d[t[2]][c]); + let q = drawn(&sm, p.rest).unwrap(); + let off = (q[0] - solved[0]).hypot(q[1] - solved[1]); + assert!(off < SMOOTH_TOLERANCE, "pin at {:?} dragged to {:?}: drawn {off} px from where it holds", p.rest, p.position); + } + } +} + +#[test] +fn a_cell_shared_by_two_sheets_mixes_both_colours() { + // Two sheets over the same pixel, owning alternate sample columns: one maps to a red source, + // the other 40 px over to a blue one. Each 2x2 cell holds samples of both, and must count + // each sheet's samples with that sheet's colour instead of all with the first's. + let mut img = Image::new(64, 32); + for y in 0..32u32 { + for x in 0..64u32 { + img.set(x, y, if x < 32 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] }); + } + } + let buf = Buf { img, offset: [0.0; 2], scale: 1.0 }; + let out = [[0.0, 0.0], [30.0, 0.0], [0.0, 30.0]]; + let red = RasterTri::new(&out, &out).unwrap(); + let blue = RasterTri::new(&out.map(|p| [p[0] + 40.0, p[1]]), &out).unwrap(); + let tris = [red, blue]; + // Alternate columns; then a narrow sheet over column 2 alone, which no corner sample shows. + for (column, want) in [(|s: usize| s % 4 % 2 == 1) as fn(usize) -> bool, |s| s % 4 == 2].into_iter().zip([[0.5, 0.0, 0.5, 1.0], [0.75, 0.0, 0.25, 1.0]]) { + let owners: Vec = (0..16).map(|s| u32::from(column(s))).collect(); + let c = resolve(&buf, &tris, &owners, 5.0, 5.0); + for (got, w) in c.iter().zip(want) { + assert!((got - w).abs() < 1e-4, "{c:?}, want {want:?}"); + } + } +} + +#[test] +fn two_points_held_in_one_triangle_both_stay_put() { + // Two held points close together in one triangle pull its gradients nearly the same way: + // correcting them one at a time for a fixed number of sweeps left the first 5 px off. + let verts = vec![[0.0, 0.0], [1000.0, 0.0], [0.0, 1000.0], [1000.0, 1000.0]]; + let mesh = Mesh { verts, tris: vec![[0, 1, 2], [1, 3, 2]], outline: vec![] }; + let def = vec![[0.0, 0.0], [1000.0, 0.0], [0.0, 1000.0], [1000.0, 3000.0]]; + let held = vec![([0, 1, 2], [0.6, 0.25, 0.15]), ([0, 1, 2], [0.6, 0.15, 0.25])]; + let mut g = vertex_gradients(&mesh, &def); + hold_points(&mesh, &mut g, &held); + for (t, l) in &held { + // The smoothed map at the point (see `smooth_mesh_holding`) against the solve's. + let v = &mesh.verts; + let q = [0, 1].map(|c| l[0] * v[t[0]][c] + l[1] * v[t[1]][c] + l[2] * v[t[2]][c]); + let mut off = [0.0, 0.0]; + for k in 0..3 { + let (i, e) = (t[k], [q[0] - v[t[k]][0], q[1] - v[t[k]][1]]); + off[0] += l[k] * (g[i][0] * e[0] + g[i][1] * e[1]); + off[1] += l[k] * (g[i][2] * e[0] + g[i][3] * e[1]); + } + let off = off[0].hypot(off[1]); + assert!(off < 1e-6, "point {l:?}: drawn {off} px from where it holds"); + } +} + +/// A strip of squares `side` px wide, `cols` long, split into triangles that each share vertices +/// with the next, bent by a non-affine map so the smoothed drawing strays from the linear one. +fn bent_strip(cols: usize, side: f64) -> (Mesh, Vec<[f64; 2]>) { + let mut verts = vec![]; + for i in 0..=cols { + verts.push([i as f64 * side, 0.0]); + verts.push([i as f64 * side, side]); + } + let mut tris = vec![]; + for i in 0..cols { + let (t0, b0, t1, b1) = (2 * i, 2 * i + 1, 2 * i + 2, 2 * i + 3); + tris.push([t0, b0, t1]); + tris.push([t1, b0, b1]); + } + let def = verts.iter().map(|v| [v[0], v[1] + v[0] * v[0] / (4.0 * side)]).collect(); + (Mesh { verts, tris, outline: vec![] }, def) +} + +/// How far the smoothed map (see `smooth_mesh_holding`) draws the farthest of `held` from where the +/// solve put it, with gradients `g`. +fn farthest_held(mesh: &Mesh, g: &[[f64; 4]], held: &[([usize; 3], [f64; 3])]) -> f64 { + let v = &mesh.verts; + held.iter() + .map(|(t, l)| { + let q = [0, 1].map(|c| l[0] * v[t[0]][c] + l[1] * v[t[1]][c] + l[2] * v[t[2]][c]); + let mut off = [0.0, 0.0]; + for k in 0..3 { + let (i, e) = (t[k], [q[0] - v[t[k]][0], q[1] - v[t[k]][1]]); + off[0] += l[k] * (g[i][0] * e[0] + g[i][1] * e[1]); + off[1] += l[k] * (g[i][2] * e[0] + g[i][3] * e[1]); + } + off[0].hypot(off[1]) + }) + .fold(0.0, f64::max) +} + +/// The points pins hold inside triangles are solved together exactly in groups of points that +/// share vertices, up to a budget per group, so no dense system is larger than the budget however +/// many pins a rig has. Past the budget a group is corrected point by point for a bounded number of +/// passes, which still takes every point most of the way to its spot. Groups each within the +/// budget stay exact, however many points they have between them. +#[test] +fn held_points_are_exact_within_the_budget_and_near_their_spots_past_it() { + let (mesh, def) = bent_strip(12, 100.0); + let at = |tris: std::ops::Range| -> Vec<([usize; 3], [f64; 3])> { tris.map(|k| (mesh.tris[k], [0.5, 0.3, 0.2])).collect() }; + // (farthest point from its spot, most points in one dense system) + let held_by = |held: &[([usize; 3], [f64; 3])], budget: usize| { + let mut g = vertex_gradients(&mesh, &def); + let dense = hold_points_within(&mesh, &mut g, held, budget); + assert!(g.iter().flatten().all(|x| x.is_finite())); + assert!(dense <= budget, "a dense system of {dense} points, over the budget of {budget}"); + (farthest_held(&mesh, &g, held), dense) + }; + // One group of 6 points: triangles next to each other share vertices. + let group = at(0..6); + let unheld = farthest_held(&mesh, &vertex_gradients(&mesh, &def), &group); + assert!(unheld > 1.0, "the bend should draw the points off their spots: {unheld} px"); + let (exact, _) = held_by(&group, 6); + assert!(exact < 1e-6, "at the budget: {exact} px off"); + let (swept, _) = held_by(&group, 5); + assert!(swept < unheld / 10.0, "just past the budget: {swept} px off, {unheld} px uncorrected"); + // Two groups of 4 that share no vertex, 8 points in all, with a budget of 4: both exact. + let apart: Vec<_> = at(0..4).into_iter().chain(at(14..18)).collect(); + assert!(held_by(&apart, 4).0 < 1e-6); +} diff --git a/crates/engine/src/cmd/puppet.rs b/crates/engine/src/cmd/puppet.rs index bd20bd885..054be7582 100644 --- a/crates/engine/src/cmd/puppet.rs +++ b/crates/engine/src/cmd/puppet.rs @@ -131,17 +131,24 @@ fn add_pin(s: &mut Session, p: &Value) -> Result { } if on_mesh(mesh, def, at) || want_mesh.is_some() { let rest = puppet::unmap(mesh, def, at); - // A moving pin holds its nearest mesh vertex at `position + (vertex - rest)` - // (puppet::solve). Choose the position that keeps that vertex where it is now, so - // adding a pin to a bent mesh moves nothing (After Effects, #318); on an unbent - // mesh that is the click itself. - let now = (0..mesh.verts.len().min(def.len())) - .filter(|_| kind.moves()) - .min_by(|a, b| dist2(mesh.verts[*a], rest).total_cmp(&dist2(mesh.verts[*b], rest))) - .and_then(|v| { - let (r, d) = (mesh.verts.get(v)?, def.get(v)?); - Some([d[0] - (r[0] - rest[0]), d[1] - (r[1] - rest[1])]) + // Choose the position that keeps everything where it is, so adding a pin to a bent + // mesh moves nothing (After Effects, #318). A moving pin holds a point at `position`, + // which is where that point is now (on the mesh, the click itself; just off it, the + // rest point can still be on the mesh). Otherwise, and always on a rig saved with + // the first solve, it holds its nearest vertex at `position + (vertex - rest)` + // (puppet::solve). + let now = kind + .moves() + .then(|| match puppet::held_point_in(¶ms, mesh, rest) { + Some((tri, bary)) => tri.iter().zip(bary).try_fold([0.0, 0.0], |a, (v, l)| def.get(*v).map(|d| [a[0] + l * d[0], a[1] + l * d[1]])), + None => (0..mesh.verts.len().min(def.len())) + .min_by(|a, b| dist2(mesh.verts[*a], rest).total_cmp(&dist2(mesh.verts[*b], rest))) + .and_then(|v| { + let (r, d) = (mesh.verts.get(v)?, def.get(v)?); + Some([d[0] - (r[0] - rest[0]), d[1] - (r[1] - rest[1])]) + }), }) + .flatten() // Round-off only (an unbent mesh): exactly the click. .filter(|n| dist2(*n, at) > 1e-12) .unwrap_or(at); diff --git a/crates/engine/src/tests/paint.rs b/crates/engine/src/tests/paint.rs index 2d2e540a5..ecabc0f7e 100644 --- a/crates/engine/src/tests/paint.rs +++ b/crates/engine/src/tests/paint.rs @@ -218,9 +218,9 @@ fn a_pin_added_to_a_bent_mesh_moves_nothing() { s.execute("puppet.addPin", json!({"layer": id, "position": at})).unwrap(); let after = s.render(cid, t, RenderOpts::default()); let moved = after.data.iter().zip(&before.data).filter(|(a, b)| (a[3] - b[3]).abs() > 0.25).count(); - // (Before #318 the pin at [50, 54] moved about 250 edge pixels; the solver's round-off - // still touches a few.) - assert!(moved <= 16, "a pin at {at:?} moved {moved} pixels"); + // (Before #318 the pin at [50, 54] moved about 250 edge pixels. A few still change: the + // mesh settles towards the pins' rigid fit, and a new pin changes that fit a little.) + assert!(moved <= 24, "a pin at {at:?} moved {moved} pixels"); s.undo(); } } @@ -290,6 +290,59 @@ fn new_mesh_option_starts_a_mesh_on_meshed_art() { assert_eq!((mesh_count(&mut s, id), pin_count(&s, id)), (2, 2)); } +/// A click just off a turned mesh's outline unmaps to a rest point that can be on the mesh. The pin +/// then holds that point (puppet::solve), so it has to go where that point already is, not to the +/// click. The mesh is turned rigidly here, so nothing else (the settling towards the pins' rigid fit, +/// say) can move it. +#[test] +fn a_pin_added_just_off_a_turned_mesh_moves_nothing() { + let (mut s, id) = setup(); + s.execute("puppet.addPin", json!({"layer": id, "position": [5, 30]})).unwrap(); + s.execute("puppet.addPin", json!({"layer": id, "position": [95, 30]})).unwrap(); + s.set_time(Tick::from_seconds_f64(1.0)); + // A third of a turn about the layer's centre: 45 px from it, each way. + let (sn, cs) = 120f64.to_radians().sin_cos(); + s.execute("puppet.movePin", json!({"layer": id, "pin": "Puppet Pin 1", "position": [50.0 - 45.0 * cs, 30.0 - 45.0 * sn]})).unwrap(); + s.execute("puppet.movePin", json!({"layer": id, "pin": "Puppet Pin 2", "position": [50.0 + 45.0 * cs, 30.0 + 45.0 * sn]})).unwrap(); + let at = |v: &Value| [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()]; + let deformed = |s: &mut Session| -> Vec<[f64; 2]> { + s.execute("puppet.info", json!({"layer": id})).unwrap()["meshes"][0]["deformed"].as_array().unwrap().iter().map(at).collect() + }; + let def = deformed(&mut s); + let info = s.execute("puppet.info", json!({"layer": id})).unwrap(); + let tris: Vec<[usize; 3]> = info["meshes"][0]["tris"].as_array().unwrap().iter().map(|t| [0, 1, 2].map(|k| t[k].as_u64().unwrap() as usize)).collect(); + let mut sides: std::collections::BTreeMap<(usize, usize), (u32, usize)> = Default::default(); + for t in &tris { + for k in 0..3 { + let (a, b, c) = (t[k], t[(k + 1) % 3], t[(k + 2) % 3]); + sides.entry((a.min(b), a.max(b))).or_insert((0, c)).0 += 1; + } + } + // Every outline edge's midpoint, a little way out from it. + let mut tried = 0; + for ((a, b), (count, c)) in &sides { + if *count != 1 { + continue; + } + let (p, q, inner) = (def[*a], def[*b], def[*c]); + let mid = [(p[0] + q[0]) / 2.0, (p[1] + q[1]) / 2.0]; + let len = (q[0] - p[0]).hypot(q[1] - p[1]).max(1e-9); + let mut n = [(q[1] - p[1]) / len, (p[0] - q[0]) / len]; + if (inner[0] - mid[0]) * n[0] + (inner[1] - mid[1]) * n[1] > 0.0 { + n = [-n[0], -n[1]]; + } + let click = [mid[0] + n[0] * 5.0, mid[1] + n[1] * 5.0]; + let added = s.execute("puppet.addPin", json!({"layer": id, "position": click})).unwrap(); + assert!(added["pin"].is_u64(), "no pin at {click:?}: {added}"); + let after = deformed(&mut s); + let moved = def.iter().zip(&after).map(|(u, v)| (u[0] - v[0]).hypot(u[1] - v[1])).fold(0.0, f64::max); + assert!(moved < 0.5, "a pin at {click:?} moved the mesh by {moved} px"); + s.undo(); + tried += 1; + } + assert!(tried > 20, "only {tried} clicks"); +} + #[test] fn puppet_pin_kinds_and_mesh_options() { let (mut s, id) = setup(); @@ -567,3 +620,62 @@ fn puppet_pin_recording_makes_keys_at_the_frame_rate() { assert_eq!(r["frames"], 9, "50 %: half the frames"); assert!(s.execute("puppet.recordPin", json!({"layer": id, "pin": pin, "samples": []})).is_err()); } + +/// #2866: a project saved before the Puppet effect kept a solver version opens with the first solve, +/// so its rigs look as they did: each moving pin holds its nearest mesh vertex (at the pin's offset +/// from it), and the frame draws differently from the same rig on the current solve. Saving and +/// opening it again keeps that, and rigs made now get the current solve. +#[test] +fn a_puppet_rig_saved_before_the_solver_version_keeps_its_look() { + use effectcraft_effects::puppet::{SOLVER_CURRENT, SOLVER_ORIGINAL, SOLVER_VERSION}; + let (mut s, id) = setup(); + s.execute("puppet.addPin", json!({"layer": id, "position": [12, 31]})).unwrap(); + s.execute("puppet.addPin", json!({"layer": id, "position": [87, 33]})).unwrap(); + s.set_time(Tick::from_seconds_f64(1.0)); + s.execute("puppet.movePin", json!({"layer": id, "pin": "Puppet Pin 2", "position": [97, 5]})).unwrap(); + let cid = s.active_comp_id().unwrap(); + let version = |s: &Session| layer(s, id).effects().unwrap().groups().next().unwrap().get(SOLVER_VERSION).map(|p| p.value.as_enum()); + assert_eq!(version(&s), Some(SOLVER_CURRENT), "a new rig"); + let at = |v: &Value| [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()]; + let deformed = |s: &mut Session, t: f64| -> Vec<[f64; 2]> { + let info = s.execute("puppet.info", json!({"layer": id, "time": t})).unwrap(); + info["meshes"][0]["deformed"].as_array().unwrap().iter().map(at).collect() + }; + let current = deformed(&mut s, 1.0); + let current_frame = s.render(cid, Tick::from_seconds_f64(1.0), RenderOpts::default()); + + // The project as an earlier version saved it: no solver version. + let l = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(id)).unwrap(); + let fx = l.props.sub_mut("effects").unwrap().children.iter_mut().find_map(|n| match n { + effectcraft_project::Node::Group(g) => Some(g), + _ => None, + }); + fx.unwrap().children.retain(|c| c.match_id() != SOLVER_VERSION); + let dir = std::env::temp_dir().join(format!("ec-2866-saved-rig-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("old.ecproj").to_string_lossy().to_string(); + std::fs::write(&path, s.project.to_file_json().unwrap()).unwrap(); + let mut old = Session::default(); + old.execute("file.open", json!({"path": path})).unwrap(); + assert_eq!(version(&old), Some(SOLVER_ORIGINAL)); + + let rest = deformed(&mut old, 0.0); + let first = deformed(&mut old, 1.0); + let (r2, p2) = ([87.0, 33.0], [97.0, 5.0]); + let v = + (0..rest.len()).min_by(|a, b| (rest[*a][0] - r2[0]).hypot(rest[*a][1] - r2[1]).total_cmp(&(rest[*b][0] - r2[0]).hypot(rest[*b][1] - r2[1]))).unwrap(); + let held = [p2[0] + rest[v][0] - r2[0], p2[1] + rest[v][1] - r2[1]]; + assert!((first[v][0] - held[0]).hypot(first[v][1] - held[1]) < 1e-3, "the pin's nearest vertex is at {:?}, not {held:?}", first[v]); + let apart = current.iter().zip(&first).map(|(a, b)| (a[0] - b[0]).hypot(a[1] - b[1])).fold(0.0, f64::max); + assert!(apart > 0.5, "the first solve put the mesh within {apart} px of the current one"); + let first_frame = old.render(cid, Tick::from_seconds_f64(1.0), RenderOpts::default()); + assert!(first_frame.data != current_frame.data, "the frame draws as on the current solve"); + + // Saved again and opened: still the first solve. + old.execute("file.save", json!({"path": path})).unwrap(); + let mut again = Session::default(); + again.execute("file.open", json!({"path": path})).unwrap(); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(version(&again), Some(SOLVER_ORIGINAL)); + assert_eq!(deformed(&mut again, 1.0), first); +}