PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Image warp: grab anywhere on the grid, Ctrl-click to cut, Warp in the transform menu (#2621)
Jeremyeab15ffdf680
diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rsindex a0194ea21..488b9a2f7 100644--- a/crates/geom/src/warp.rs+++ b/crates/geom/src/warp.rs@@ -512,6 +512,266 @@ impl BezierMesh {(s, t)}+ /// Pulls the surface point at normalised `(s, t)` by `d`, as dragging the grid anywhere inside+ /// a patch does in other editors. `base` is the control grid at the start of the drag.+ ///+ /// Two parts. The surrounding grid follows loosely: every interior anchor within about two cells+ /// moves by a share of `d` that fades with distance. The picture's outer border stays pinned+ /// (the picture keeps filling its frame) unless the grab is within a+ /// few percent of it, and then it follows more and more. Each anchor+ /// takes its whole 3 x 3 block of control points along, so every grid line stays smooth through+ /// its anchors and the neighbouring cells and dividers bend with the pull. Then the four inner+ /// control points of the grabbed patch make up the rest, so the grabbed point lands exactly at+ /// its start + `d`. Grabbing near an anchor moves that anchor more, and the inner points less.+ pub fn pull(&mut self, base: &[[f64; 2]], s: f64, t: f64, d: [f64; 2]) {+ /// Within this distance of the mesh border (in 0..1 box units) a grab starts to drag the+ /// border with it; further in, the border stays exactly where it is.+ const BORDER_ZONE: f64 = 0.12;+ /// Falloff radius, in the grabbed patch's size.+ const REACH: f64 = 1.8;+ if base.len() != self.points.len() || !d.iter().all(|v| v.is_finite()) {+ return;+ }+ self.points.copy_from_slice(base);+ let (cols, rows) = (self.us.len() - 1, self.vs.len() - 1);+ let (pi, a) = Self::locate(&self.us, s);+ let (pj, b) = Self::locate(&self.vs, t);+ let (ba, bb) = (bernstein(a), bernstein(b));+ let nx = self.nx();+ let anchor = |ai: usize, aj: usize| base.get(3 * aj * nx + 3 * ai).copied().unwrap_or([0.0; 2]);+ let at0 = self.eval(s, t);+ let target = [at0[0] + d[0], at0[1] + d[1]];+ // The grabbed patch's size and its "interior-ness": 1 in the middle, 0 on its edges.+ let mut size = 1.0f64;+ for k in 0..2 {+ let vals = [anchor(pi, pj)[k], anchor(pi + 1, pj)[k], anchor(pi, pj + 1)[k], anchor(pi + 1, pj + 1)[k]];+ let (lo, hi) = vals.iter().fold((f64::MAX, f64::MIN), |m, v| (m.0.min(*v), m.1.max(*v)));+ size = size.max(hi - lo);+ }+ let radius = REACH * size;+ let inner_w = (ba[1] + ba[2]) * (bb[1] + bb[2]);+ let interior = (inner_w / 0.5625).clamp(0.0, 1.0);+ let to_border = s.min(1.0 - s).min(t.min(1.0 - t));+ let near_border = (1.0 - to_border / BORDER_ZONE).clamp(0.0, 1.0);+ // How much of the pull each corner of the grabbed patch is responsible for.+ // A corner on the picture's border only takes part once the grab is near that border.+ // The picture's four corners never move in a pull (a grab near the border bends the+ // border through its handles instead).+ let mesh_corner = |ai: usize, aj: usize| (ai == 0 || ai == cols) && (aj == 0 || aj == rows);+ let reach = |ai: usize, aj: usize, wa: f64, wb: f64| {+ let border = ai == 0 || ai == cols || aj == 0 || aj == rows;+ if mesh_corner(ai, aj) { 0.0 } else { wa * wb * if border { near_border } else { 1.0 } }+ };+ let corner = [+ (pi, pj, reach(pi, pj, ba[0] + ba[1], bb[0] + bb[1])),+ (pi + 1, pj, reach(pi + 1, pj, ba[2] + ba[3], bb[0] + bb[1])),+ (pi, pj + 1, reach(pi, pj + 1, ba[0] + ba[1], bb[2] + bb[3])),+ (pi + 1, pj + 1, reach(pi + 1, pj + 1, ba[2] + ba[3], bb[2] + bb[3])),+ ];+ // Share of `d` for each anchor.+ let mut share = vec![0.0f64; (cols + 1) * (rows + 1)];+ for aj in 0..=rows {+ for ai in 0..=cols {+ let p = anchor(ai, aj);+ let x = ((p[0] - at0[0]).hypot(p[1] - at0[1]) / radius).clamp(0.0, 1.0);+ let fall = 0.5 * (1.0 + (std::f64::consts::PI * x).cos());+ let border = ai == 0 || ai == cols || aj == 0 || aj == rows;+ let edge = if mesh_corner(ai, aj) {+ 0.0+ } else if border {+ near_border+ } else {+ 1.0+ };+ share[aj * (cols + 1) + ai] = fall * edge;+ }+ }+ // The grabbed patch's own corners: near one, that corner follows the pointer.+ for (ai, aj, w) in corner {+ let f = &mut share[aj * (cols + 1) + ai];+ *f = f.max((1.0 - interior) * w);+ }+ // Every control point moves with the anchor it is closest to.+ for j in 0..self.ny() {+ for i in 0..nx {+ let (ai, aj) = (((i + 1) / 3).min(cols), ((j + 1) / 3).min(rows));+ let k = share[aj * (cols + 1) + ai];+ let p = &mut self.points[j * nx + i];+ p[0] += d[0] * k;+ p[1] += d[1] * k;+ }+ }+ // Close the gap exactly, with three groups of control points that share the work:+ // - the four inner points of the grabbed patch (all of it in the middle of the patch,+ // little near a grid line, where they barely reach the surface);+ // - the corner blocks (an anchor with its handles, moving as a whole so lines stay smooth);+ // - when the grab is near the picture's border, that border's own handles: the border+ // bends into a curve and its corners stay put.+ // Closing nudges the tangents across the grid lines, so they are evened out again and the+ // gap re-closed.+ let norm: f64 = [1, 2].iter().flat_map(|j| [1, 2].iter().map(move |i| (ba[*i] * bb[*j]).powi(2))).sum();+ let corner_norm: f64 = corner.iter().map(|c| c.2 * c.2).sum();+ // With no free corner to help (a one-patch grid, grabbed away from its border) the four+ // inner points do all of it.+ let inner_part = if corner_norm > 1e-12 { (inner_w / 0.15).min(1.0) } else { 1.0 };+ // Handles along the sides of the grabbed patch that lie on the picture's border.+ let mut edge: Vec<(usize, f64)> = Vec::new();+ for k in [1usize, 2] {+ if pi == 0 {+ edge.push(((3 * pj + k) * nx + 3 * pi, ba[0] * bb[k]));+ }+ if pi + 1 == cols {+ edge.push(((3 * pj + k) * nx + 3 * pi + 3, ba[3] * bb[k]));+ }+ if pj == 0 {+ edge.push((3 * pj * nx + 3 * pi + k, ba[k] * bb[0]));+ }+ if pj + 1 == rows {+ edge.push(((3 * pj + 3) * nx + 3 * pi + k, ba[k] * bb[3]));+ }+ }+ let edge_norm: f64 = edge.iter().map(|e| e.1 * e.1).sum();+ let edge_part = if edge_norm > 1e-12 { near_border } else { 0.0 };+ let (inner_share, corner_share) = ((1.0 - edge_part) * inner_part, (1.0 - edge_part) * (1.0 - inner_part));+ for _ in 0..60 {+ let now = self.eval(s, t);+ let rem = [target[0] - now[0], target[1] - now[1]];+ if rem[0].hypot(rem[1]) < 1e-9 {+ break;+ }+ if inner_share > 0.0 && norm > 0.0 {+ for j in [1usize, 2] {+ for i in [1usize, 2] {+ let k = ba[i] * bb[j] / norm * inner_share;+ let p = &mut self.points[(3 * pj + j) * nx + 3 * pi + i];+ p[0] += rem[0] * k;+ p[1] += rem[1] * k;+ }+ }+ }+ if edge_part > 0.0 {+ for (idx, w) in &edge {+ if let Some(p) = self.points.get_mut(*idx) {+ let k = w / edge_norm * edge_part;+ p[0] += rem[0] * k;+ p[1] += rem[1] * k;+ }+ }+ }+ if corner_share > 0.0 && corner_norm > 0.0 {+ for (ai, aj, w) in corner {+ let k = w / corner_norm * corner_share;+ for dj in -1..=1isize {+ for di in -1..=1isize {+ let (i, j) = ((3 * ai) as isize + di, (3 * aj) as isize + dj);+ if i >= 0 && j >= 0 && (i as usize) < nx && (j as usize) < self.ny() {+ let p = &mut self.points[j as usize * nx + i as usize];+ p[0] += rem[0] * k;+ p[1] += rem[1] * k;+ }+ }+ }+ }+ }+ for _ in 0..3 {+ self.smooth_lines((3 * pi).saturating_sub(3), 3 * pi + 7, (3 * pj).saturating_sub(3), 3 * pj + 7);+ }+ }+ }++ /// Makes the tangent equal on both sides of every interior grid line, for the control points+ /// in columns `i0..i1` and rows `j0..j1` (exclusive ends, clamped to the grid): each pair of+ /// handles takes the average of the two tangents it had.+ fn smooth_lines(&mut self, i0: usize, i1: usize, j0: usize, j1: usize) {+ let nx = self.nx();+ let (i1, j1) = (i1.min(nx), j1.min(self.ny()));+ let hu = |k: usize| self.us[k + 1] - self.us[k];+ let hv = |k: usize| self.vs[k + 1] - self.vs[k];+ // (left, centre, right, span left, span right)+ let mut triples = Vec::new();+ for a in 1..self.us.len() - 1 {+ if 3 * a >= i0 && 3 * a < i1 {+ for j in j0..j1 {+ triples.push((j * nx + 3 * a - 1, j * nx + 3 * a, j * nx + 3 * a + 1, hu(a - 1), hu(a)));+ }+ }+ }+ for b in 1..self.vs.len() - 1 {+ if 3 * b >= j0 && 3 * b < j1 {+ for i in i0..i1 {+ triples.push(((3 * b - 1) * nx + i, 3 * b * nx + i, (3 * b + 1) * nx + i, hv(b - 1), hv(b)));+ }+ }+ }+ for (l, c, r, hl, hr) in triples {+ let (pl, pc, pr) = (self.points[l], self.points[c], self.points[r]);+ let tan = [((pc[0] - pl[0]) / hl + (pr[0] - pc[0]) / hr) / 2.0, ((pc[1] - pl[1]) / hl + (pr[1] - pc[1]) / hr) / 2.0];+ self.points[l] = [pc[0] - tan[0] * hl, pc[1] - tan[1] * hl];+ self.points[r] = [pc[0] + tan[0] * hr, pc[1] + tan[1] * hr];+ }+ }++ /// Drags control point `index` by `d` from the grid `base` it had when the drag began, keeping+ /// the surface smooth across the grid lines:+ /// - an anchor moves with the eight points around it, as one block;+ /// - a handle moves with the two points beside it across its line, and the handle opposite+ /// it on the same anchor turns the other way (with its two neighbours), so the line keeps+ /// passing straight through the anchor instead of creasing there.+ pub fn drag_point(&mut self, base: &[[f64; 2]], index: usize, d: [f64; 2]) {+ if base.len() != self.points.len() || index >= base.len() || !d.iter().all(|v| v.is_finite()) {+ return;+ }+ self.points.copy_from_slice(base);+ let (nx, ny) = (self.nx(), self.ny());+ let (i, j) = (index % nx, index / nx);+ let mut shift = |i: isize, j: isize, d: [f64; 2]| {+ if i >= 0 && j >= 0 && (i as usize) < nx && (j as usize) < ny {+ let p = &mut self.points[j as usize * nx + i as usize];+ p[0] += d[0];+ p[1] += d[1];+ }+ };+ let (ii, jj) = (i as isize, j as isize);+ // Spans either side of interior knot `k`.+ let span = |knots: &[f64], k: usize| (k > 0 && k + 1 < knots.len()).then(|| (knots[k] - knots[k - 1], knots[k + 1] - knots[k]));+ match (i % 3, j % 3) {+ (0, 0) => {+ for dj in -1..=1 {+ for di in -1..=1 {+ shift(ii + di, jj + dj, d);+ }+ }+ }+ // A handle along a vertical line: it takes the two points beside it across the line.+ (0, r) => {+ for di in -1..=1 {+ shift(ii + di, jj, d);+ }+ // The opposite handle of the same anchor turns the other way.+ if let Some((hl, hr)) = span(&self.vs, j / 3 + usize::from(r == 2)) {+ let (other, k) = if r == 1 { (jj - 2, hl / hr) } else { (jj + 2, hr / hl) };+ for di in -1..=1 {+ shift(ii + di, other, [-d[0] * k, -d[1] * k]);+ }+ }+ }+ // A handle along a horizontal line, likewise.+ (r, 0) => {+ for dj in -1..=1 {+ shift(ii, jj + dj, d);+ }+ if let Some((hl, hr)) = span(&self.us, i / 3 + usize::from(r == 2)) {+ let (other, k) = if r == 1 { (ii - 2, hl / hr) } else { (ii + 2, hr / hl) };+ for dj in -1..=1 {+ shift(other, jj + dj, [-d[0] * k, -d[1] * k]);+ }+ }+ }+ // An inner point of a patch has no handle of its own.+ _ => shift(ii, jj, d),+ }+ }+/// Bounding box of the control points (the surface lies inside it).pub fn control_bounds(&self) -> [f64; 4] {self.points.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])])@@ -651,6 +911,197 @@ mod tests {const B: [f64; 4] = [10.0, 20.0, 110.0, 70.0];+ /// The largest mismatch between the tangents on the two sides of any interior grid line.+ fn tangent_defect(m: &BezierMesh) -> f64 {+ let nx = m.nx();+ let mut worst: f64 = 0.0;+ for a in 1..m.us.len() - 1 {+ let (hl, hr) = (m.us[a] - m.us[a - 1], m.us[a + 1] - m.us[a]);+ for j in 0..m.ny() {+ let (l, c, r) = (m.points[j * nx + 3 * a - 1], m.points[j * nx + 3 * a], m.points[j * nx + 3 * a + 1]);+ for k in 0..2 {+ worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs());+ }+ }+ }+ for b in 1..m.vs.len() - 1 {+ let (hl, hr) = (m.vs[b] - m.vs[b - 1], m.vs[b + 1] - m.vs[b]);+ for i in 0..nx {+ let (l, c, r) = (m.points[(3 * b - 1) * nx + i], m.points[3 * b * nx + i], m.points[(3 * b + 1) * nx + i]);+ for k in 0..2 {+ worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs());+ }+ }+ }+ worst+ }++ #[test]+ fn dragging_an_anchor_or_handle_keeps_the_surface_smooth_across_the_lines() {+ let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1);+ for s in [0.3, 0.55, 0.9] {+ assert!(base.split_u(s));+ assert!(base.split_v(s));+ }+ let nx = base.nx();+ // Every kind of point on a grid line, interior and border: anchors, handles each way.+ for (i, j) in [(6, 6), (7, 6), (5, 6), (6, 7), (6, 5), (3, 9), (9, 3), (0, 6), (6, 0), (4, 3), (3, 4), (12, 12)] {+ let mut m = base.clone();+ m.drag_point(&base.points, j * nx + i, [23.0, -31.0]);+ assert_eq!(m.points[j * nx + i], [base.points[j * nx + i][0] + 23.0, base.points[j * nx + i][1] - 31.0], "({i}, {j}) lands on the pointer");+ assert!(tangent_defect(&m) < 1e-6, "({i}, {j}): {}", tangent_defect(&m));+ }+ }++ /// Fraction of the surface where the map folds over itself (its Jacobian is not positive).+ fn fold_fraction(m: &BezierMesh) -> f64 {+ let (n, h) = (80, 1e-4);+ let mut bad = 0;+ for j in 0..n {+ for i in 0..n {+ let (s, t) = ((i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64);+ let q = m.eval(s, t);+ let (qs, qt) = (m.eval(s + h, t), m.eval(s, t + h));+ if (qs[0] - q[0]) * (qt[1] - q[1]) - (qt[0] - q[0]) * (qs[1] - q[1]) <= 0.0 {+ bad += 1;+ }+ }+ }+ bad as f64 / (n * n) as f64+ }++ #[test]+ fn a_pull_within_a_quarter_cell_never_folds_the_surface() {+ // 75 px cells: dragging a quarter of a cell, any direction, anywhere in the grid must not tear the picture.+ let base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 4, 4);+ for (s, t) in [(0.42, 0.42), (0.75, 0.2), (0.2, 0.2), (0.5, 0.5), (0.85, 0.7), (0.3, 0.7)] {+ for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, 0.7)] {+ let mut m = base.clone();+ m.pull(&base.points, s, t, [dx * 19.0, dy * 19.0]);+ assert_eq!(fold_fraction(&m), 0.0, "({s}, {t}) by ({dx}, {dy}) quarter cells");+ }+ }+ }++ #[test]+ fn a_pull_in_the_middle_leaves_the_border_where_it_is() {+ let mut base = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1);+ for s in [0.33, 0.66] {+ assert!(base.split_u(s));+ }+ assert!(base.split_v(0.5));+ let (nx, ny) = (base.nx(), base.ny());+ let on_border = |i: usize, j: usize| i == 0 || j == 0 || i == nx - 1 || j == ny - 1;+ let mut m = base.clone();+ m.pull(&base.points, 0.5, 0.5, [-180.0, 40.0]);+ for j in 0..ny {+ for i in 0..nx {+ if on_border(i, j) {+ let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]);+ assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "border point ({i}, {j}) moved");+ }+ }+ }+ // The pull itself still lands exactly.+ let (before, after) = (base.eval(0.5, 0.5), m.eval(0.5, 0.5));+ assert!((after[0] - before[0] + 180.0).abs() < 1e-4 && (after[1] - before[1] - 40.0).abs() < 1e-4);+ }++ #[test]+ fn a_pull_anywhere_away_from_the_border_never_moves_the_border() {+ // The default one-patch grid and a cut one; grabs all over, none within 12% of an edge.+ let one = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1);+ let mut cut = one.clone();+ assert!(cut.split_u(0.4) && cut.split_u(0.7) && cut.split_v(0.35) && cut.split_v(0.8));+ for base in [one, cut] {+ let (nx, ny) = (base.nx(), base.ny());+ for (s, t) in [(0.5, 0.5), (0.2, 0.5), (0.8, 0.3), (0.3, 0.85), (0.14, 0.14), (0.86, 0.5)] {+ for d in [[-400.0, 0.0], [250.0, -90.0], [0.0, 300.0]] {+ let mut m = base.clone();+ m.pull(&base.points, s, t, d);+ for j in 0..ny {+ for i in 0..nx {+ if i == 0 || j == 0 || i == nx - 1 || j == ny - 1 {+ let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]);+ assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "({s}, {t}) by {d:?} moved border point ({i}, {j})");+ }+ }+ }+ let (before, after) = (base.eval(s, t), m.eval(s, t));+ assert!((after[0] - before[0] - d[0]).abs() < 1e-3 && (after[1] - before[1] - d[1]).abs() < 1e-3, "({s}, {t}) by {d:?}: {after:?}");+ }+ }+ }+ }++ #[test]+ fn pulling_on_the_border_bows_it_and_leaves_the_corners_put() {+ // A one-patch grid, grabbed on the middle of its right edge and pulled 170 px out.+ let base = BezierMesh::identity([0.0, 0.0, 800.0, 1200.0], 1, 1);+ let mut m = base.clone();+ m.pull(&base.points, 1.0, 0.5, [170.0, 0.0]);+ let at = m.eval(1.0, 0.5);+ assert!((at[0] - 970.0).abs() < 1e-3 && (at[1] - 600.0).abs() < 1e-3, "{at:?}");+ for (s, t) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] {+ let (a, b) = (m.eval(s, t), base.eval(s, t));+ assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "corner ({s}, {t}) moved");+ }+ // The other three edges did not move.+ for k in 0..=10 {+ let u = k as f64 / 10.0;+ for (s, t) in [(0.0, u), (u, 0.0), (u, 1.0)] {+ let (a, b) = (m.eval(s, t), base.eval(s, t));+ assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "edge point ({s}, {t}) moved");+ }+ }+ // Only the right edge's two handles carry the pull.+ let nx = base.nx();+ let moved: Vec<usize> = (0..m.points.len()).filter(|k| m.points[*k] != base.points[*k]).collect();+ assert_eq!(moved, vec![nx + 3, 2 * nx + 3], "{moved:?}");+ assert_eq!(fold_fraction(&m), 0.0);+ }++ #[test]+ fn pull_keeps_the_surface_smooth_across_the_grid_lines() {+ // A grid cut unevenly both ways, then pulled hard inside one cell and then another.+ let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1);+ for s in [0.3, 0.55, 0.9] {+ assert!(base.split_u(s));+ assert!(base.split_v(s));+ }+ assert!(tangent_defect(&base) < 1e-9, "cuts are exact");+ for (s, t, d) in [(0.42, 0.42, [60.0, -35.0]), (0.75, 0.2, [-40.0, 50.0]), (0.1, 0.95, [30.0, 30.0])] {+ let mut m = base.clone();+ m.pull(&base.points, s, t, d);+ assert!(tangent_defect(&m) < 1e-6, "({s}, {t}): {}", tangent_defect(&m));+ let before = base.eval(s, t);+ let after = m.eval(s, t);+ assert!((after[0] - before[0] - d[0]).abs() < 1e-4 && (after[1] - before[1] - d[1]).abs() < 1e-4, "{after:?}");+ }+ }++ #[test]+ fn pull_moves_the_grabbed_surface_point_exactly_and_stays_local() {+ let base = BezierMesh::identity(B, 3, 2);+ for (s, t) in [(0.5, 0.5), (0.1, 0.9), (0.4, 0.25), (0.0, 0.5), (1.0, 0.3)] {+ let mut m = base.clone();+ let before = base.eval(s, t);+ m.pull(&base.points, s, t, [7.0, -4.5]);+ let after = m.eval(s, t);+ assert!((after[0] - before[0] - 7.0).abs() < 1e-4 && (after[1] - before[1] + 4.5).abs() < 1e-4, "({s}, {t}): {after:?}");+ }+ // The pull stays near the grabbed patch: the far end of the grid does not move.+ let mut m = base.clone();+ m.pull(&base.points, 0.1, 0.25, [5.0, 5.0]);+ let nx = base.nx();+ let moved = |k: usize| (m.points[k][0] - base.points[k][0]).abs() > 1e-6 || (m.points[k][1] - base.points[k][1]).abs() > 1e-6;+ assert!((0..base.ny()).all(|j| !moved(j * nx + nx - 1)), "last column stays put");+ assert!((0..nx).any(moved), "something moved");+ // Pulling again from the same base replaces the pull (a drag is not cumulative).+ m.pull(&base.points, 0.5, 0.25, [0.0, 0.0]);+ assert!(m.points.iter().zip(&base.points).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9));+ }+fn close(a: (f64, f64), b: (f64, f64), eps: f64) -> bool {(a.0 - b.0).abs() < eps && (a.1 - b.1).abs() < eps}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex ea212ef22..e005dd280 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2613,7 +2613,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}}// Right-click while transforming: switch the box's mode (Free Transform, Scale, Rotate,- // Skew, Distort, Perspective).+ // Skew, Distort, Perspective, Warp).let transforming = app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none());if response.secondary_clicked()&& transforming@@ -2886,7 +2886,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:});if let Some((vertical, _)) = guide_hover {ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });- } else if let Some(c) = response.hover_pos().and_then(|p| crate::transform_tool::cursor(app, xf.to_doc(p), ui.input(|i| i.modifiers.alt))) {+ } else if let Some(c) =+ response.hover_pos().and_then(|p| crate::transform_tool::cursor(app, xf.to_doc(p), ui.input(|i| i.modifiers.alt || i.modifiers.command)))+ {ui.ctx().set_cursor_icon(c);} else if let Some(c) = response.hover_pos().filter(|_| tool.is_type()).and_then(|p| {let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers));diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rsindex 9fab52bed..1ef31e1ea 100644--- a/crates/ui-egui/src/canvas_tool_menu.rs+++ b/crates/ui-egui/src/canvas_tool_menu.rs@@ -37,6 +37,7 @@ pub const TRANSFORM_MENU: &[Row] = &[Some(("Skew", "edit.transform.skew")),Some(("Distort", "edit.transform.distort")),Some(("Perspective", "edit.transform.perspective")),+ Some(("Warp", "edit.transform.warp")),];/// Photoshop's pasteboard menu (right-click outside the image): the pasteboard colour, the choice@@ -162,13 +163,14 @@ pub fn available(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> b}/// Is `command` the transform box's current mode (checked in the transform menu)?-/// Scale and Rotate are Free Transform's mode, so only Free Transform shows it checked.-fn mode_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool {+/// Scale and Rotate are Free Transform's mode, so only Free Transform shows it checked. Warp is+/// not a box mode (it is its own session), and `for_command` would read it as Free.+pub(crate) fn mode_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool {if menu.pasteboard {return pasteboard_choice(command) == Some(app.session.prefs().interface.canvas_color);}menu.transform- && !matches!(command, "edit.transform.scale" | "edit.transform.rotate")+ && matches!(command, "edit.freeTransform" | "edit.transform.skew" | "edit.transform.distort" | "edit.transform.perspective")&& app.ui.transform.as_ref().is_some_and(|t| t.mode == crate::state::TransformMode::for_command(command))}@@ -236,6 +238,10 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str)if menu.pasteboard {return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command);}+ // Warp needs a layer or selection box: a lone mask, channel or path keeps the plain box.+ if menu.transform && command == "edit.transform.warp" {+ return app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none() && t.target.is_none() && t.path.is_none());+ }if menu.transform || menu.tool != Tool::Pen {return crate::menus::is_enabled(app, command);}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex a94d8a76b..797182973 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -168,6 +168,7 @@ mod type_transform;mod variables_ui;pub mod vector_ui;pub mod view_cmds;+pub mod warp_preview;pub mod wheel_nav;pub mod wide_angle_ui;pub mod widgets;diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsindex f8a46dfac..a0386aaa2 100644--- a/crates/ui-egui/src/transform_tool.rs+++ b/crates/ui-egui/src/transform_tool.rs@@ -47,6 +47,14 @@ impl SplitTool {}}+/// What a Warp-mode press grabbed. `pts0` is the mesh's control grid at the press.+enum WarpDrag {+ /// An anchor or handle: it follows the pointer (an anchor takes its handles along).+ Point { index: usize, start: [f64; 2], pts0: Vec<[f64; 2]> },+ /// Anywhere else on the grid: the surface under the pointer follows it.+ Surface { s: f64, t: f64, start: [f64; 2], pts0: Vec<[f64; 2]> },+}+/// Preview state that isn't serialisable: the document without the transformed pixels, and/// full-resolution textures of those pixels (transform_tex.rs).pub struct TransformPreview {@@ -57,8 +65,8 @@ pub struct TransformPreview {/// The layers stacked over the moving one, drawn over its pixels ([`Above`]).above: Option<Above>,gesture: Option<Gesture>,- /// Warp-mode drag: (control point, pointer start, mesh points at the start).- warp_drag: Option<(usize, [f64; 2], Vec<[f64; 2]>)>,+ /// Warp-mode drag in progress.+ warp_drag: Option<WarpDrag>,/// Armed split tool. None while the buttons are off and control points drag as usual.split_tool: Option<SplitTool>,/// Document point the split guide is following (a drag, or the hover while placing).@@ -1336,8 +1344,15 @@ fn single_patch(mesh: &BezierMesh) -> bool {mesh.us.len() == 2 && mesh.vs.len() == 2}-/// Option-click picks the split: crosswise in the open, and the perpendicular split when the-/// pointer is close to an existing grid line.+/// The surface parameters under `p` when it is inside the warped mesh, else None.+fn surface_at(mesh: &BezierMesh, p: [f64; 2]) -> Option<(f64, f64)> {+ let (s, t) = mesh.param_at(p);+ let q = mesh.eval(s, t);+ ((q[0] - p[0]).hypot(q[1] - p[1]) < 1.0).then_some((s, t))+}++/// Ctrl-click (or Option-click) picks the split: crosswise in the open, and the perpendicular+/// split when the pointer is close to an existing grid line.fn quick_split_kind(mesh: &BezierMesh, bounds: [f64; 4], p: [f64; 2]) -> SplitTool {let (s, t) = mesh.param_at(p);let w = (bounds[2] - bounds[0]).abs().max(1.0);@@ -1369,7 +1384,7 @@ fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool);let placing = app.transform_preview.as_ref().is_some_and(|p| p.split_placing);match ev {- ToolEvent::Down { x, y, .. } if armed.is_some() || mods.alt => {+ ToolEvent::Down { x, y, .. } if armed.is_some() || mods.alt || mods.command => {if let Some(pv) = app.transform_preview.as_mut() {pv.split_placing = true;pv.split_pointer = Some([x, y]);@@ -1407,9 +1422,10 @@ fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)}}-/// Drags a warp control point. Anchors (patch corners) carry their handles along. Preset warps-/// turn into a custom mesh on the first drag. An armed split tool (or Option) places a split-/// where the pointer is released instead of moving a point.+/// Drags the warp grid. A press on an anchor or handle moves that point (an anchor carries its+/// handles along); a press anywhere else inside the grid pulls the surface under the pointer.+/// Preset warps turn into a custom mesh when the press grabs something. An armed split tool, or+/// Ctrl / Option held, places a split where the pointer is released instead.fn warp_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64, mods: egui::Modifiers) {if split_gesture(app, ev, mods) {return;@@ -1420,29 +1436,20 @@ fn warp_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64, mods: egui::MoToolEvent::Down { x, y, .. } => {// A preset warp becomes a custom mesh only when the press grabs one of its points.let custom = if w.mesh.is_none() || w.style != WarpStyle::Custom { Warp::custom(w.to_mesh(1, 1), w.bounds) } else { w.clone() };- pv.warp_drag = warp_hit(&custom, [x, y], tol).map(|i| (i, [x, y], custom.mesh.as_ref().map(|m| m.points.clone()).unwrap_or_default()));+ let pts0 = custom.mesh.as_ref().map(|m| m.points.clone()).unwrap_or_default();+ pv.warp_drag = warp_hit(&custom, [x, y], tol).map(|index| WarpDrag::Point { index, start: [x, y], pts0: pts0.clone() }).or_else(|| {+ let (s, t) = surface_at(custom.mesh.as_ref()?, [x, y])?;+ Some(WarpDrag::Surface { s, t, start: [x, y], pts0 })+ });if pv.warp_drag.is_some() {*w = custom;}}ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => {- if let (Some((i, start, pts0)), Some(m)) = (&pv.warp_drag, w.mesh.as_mut()) {- let (dx, dy) = (x - start[0], y - start[1]);- let nx = m.nx();- let (ci, cj) = (i % nx, i / nx);- let ny = m.ny();- let mut moved = vec![*i];- if ci % 3 == 0 && cj % 3 == 0 {- for (di, dj) in [(-1i64, 0i64), (1, 0), (0, -1), (0, 1)] {- let (a, b) = (ci as i64 + di, cj as i64 + dj);- if a >= 0 && b >= 0 && (a as usize) < nx && (b as usize) < ny {- moved.push(b as usize * nx + a as usize);- }- }- }- for k in moved {- m.points[k] = [pts0[k][0] + dx, pts0[k][1] + dy];- }+ match (&pv.warp_drag, w.mesh.as_mut()) {+ (Some(WarpDrag::Point { index, start, pts0 }), Some(m)) => m.drag_point(pts0, *index, [x - start[0], y - start[1]]),+ (Some(WarpDrag::Surface { s, t, start, pts0 }), Some(m)) => m.pull(pts0, *s, *t, [x - start[0], y - start[1]]),+ _ => {}}if matches!(ev, ToolEvent::Up { .. }) {pv.warp_drag = None;@@ -1497,19 +1504,22 @@ fn rotation_degrees(quad: [[f64; 2]; 4]) -> f64 {if dx.is_finite() && dy.is_finite() && dx.hypot(dy) > 1e-9 { dy.atan2(dx).to_degrees() } else { 0.0 }}-/// Cursor for hovering a document point while transforming. `alt` is Option, which arms a quick-/// split while a warp is active.-pub fn cursor(app: &PhotocraftApp, p: [f64; 2], alt: bool) -> Option<CursorIcon> {+/// Cursor for hovering a document point while transforming. `quick_split` is Ctrl or Option,+/// which arms a quick split while a warp is active.+pub fn cursor(app: &PhotocraftApp, p: [f64; 2], quick_split: bool) -> Option<CursorIcon> {let t = app.ui.transform.as_ref()?;let tol = handle_tolerance(app);if let Some(w) = &t.warp {if let Some(tool) = app.transform_preview.as_ref().and_then(|pv| pv.split_tool) {return Some(split_cursor(tool));}- if alt {+ if quick_split {return Some(split_cursor(quick_split_kind(&w.to_mesh(1, 1), w.bounds, p)));}- return Some(if w.style != WarpStyle::Custom || warp_hit(w, p, tol).is_some() { CursorIcon::Crosshair } else { CursorIcon::Default });+ if w.style != WarpStyle::Custom || warp_hit(w, p, tol).is_some() {+ return Some(CursorIcon::Crosshair);+ }+ return Some(if w.mesh.as_ref().and_then(|m| surface_at(m, p)).is_some() { CursorIcon::Grab } else { CursorIcon::Default });}let h = hit(t, p, tol);if !distort_allows(t.mode, h) {@@ -1539,7 +1549,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXformif let Some(w) = &t.warp {let over_canvas = painter.ctx().input(|i| i.pointer.hover_pos()).filter(|p| xf.rect.contains(*p)).map(|p| xf.to_doc(p));let at = pv.split_pointer.or(over_canvas);- let alt = painter.ctx().input(|i| i.modifiers.alt);+ let alt = painter.ctx().input(|i| i.modifiers.alt || i.modifiers.command);let guide = at.and_then(|p| {let tool = pv.split_tool.or_else(|| (alt || pv.split_quick).then(|| quick_split_kind(&w.to_mesh(1, 1), w.bounds, p)));tool.map(|tool| (tool, p))@@ -1689,27 +1699,75 @@ fn draw_rotate_feedback(painter: &egui::Painter, at: Pos2, angle: Option<f64>, b/// boundaries are solid. A single patch (Grid › Default) also draws its rule-of-thirds guides;/// 3×3, 4×4 and 5×5 are just those even cells, with an anchor at every intersection. `guide` is/// the split line following the pointer.+/// How near the pointer (screen px) a handle's anchor or the handle itself must be for the+/// handle to show. Everything else stays out of the way: only anchors are always drawn.+const HANDLE_REVEAL_PX: f32 = 56.0;++/// The anchor a handle belongs to, as `(i, j)` in the control grid (an anchor is its own).+fn handle_anchor(i: usize, j: usize) -> (usize, usize) {+ if i.is_multiple_of(3) {+ let aj = match j % 3 {+ 0 => j,+ 1 => j - 1,+ _ => j + 1,+ };+ (i, aj)+ } else {+ (if i % 3 == 1 { i - 1 } else { i + 1 }, j)+ }+}+/// Anchors always, small and quiet. A handle and its arm show only while the pointer is close to+/// them or they are being dragged, so a dense grid does not bury the picture in dots.+fn draw_warp_points(painter: &egui::Painter, m: &BezierMesh, scr: impl Fn([f64; 2]) -> Pos2, pv: &TransformPreview, line: Stroke) {+ let (nx, ny) = (m.nx(), m.ny());+ let hover = painter.ctx().input(|i| i.pointer.hover_pos());+ let dragged = match &pv.warp_drag {+ Some(WarpDrag::Point { index, .. }) => Some(handle_anchor(index % nx, index / nx)),+ _ => None,+ };+ let near = |p: Pos2| hover.is_some_and(|h| h.distance(p) <= HANDLE_REVEAL_PX);+ let faint = Stroke::new(0.75, line.color.gamma_multiply(0.8));+ for j in 0..ny {+ for i in 0..nx {+ if !on_section_edge(i, j) {+ continue;+ }+ let p = scr(m.point(i, j));+ if i.is_multiple_of(3) && j.is_multiple_of(3) {+ let r = egui::Rect::from_center_size(p, vec2(5.0, 5.0));+ painter.rect_filled(r, 0.0, Color32::WHITE);+ painter.rect_stroke(r, 0.0, faint, egui::StrokeKind::Inside);+ continue;+ }+ let (ai, aj) = handle_anchor(i, j);+ let a = scr(m.point(ai, aj));+ if !(near(p) || near(a) || dragged == Some((ai, aj))) {+ continue;+ }+ painter.line_segment([a, p], faint);+ painter.circle_filled(p, 2.75, Color32::WHITE);+ painter.circle_stroke(p, 2.75, faint);+ }+ }+}+fn draw_warp(painter: &egui::Painter, xf: &ViewXform, t: &TransformSession, w: &Warp, pv: &TransformPreview, guide: Option<(SplitTool, [f64; 2])>) {let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32);let r = t.rect;- let n = 32;+ let m = w.to_mesh(1, 1);+ let (us, vs) = crate::warp_preview::samples(&m, xf.zoom as f64);let (tex, uv) = pv.texture.pick(painter.ctx(), xf.zoom * painter.ctx().pixels_per_point(), 1.0, t.interpolation == "nearest");let mut mesh = egui::Mesh::with_texture(tex);let tint = Color32::from_white_alpha((pv.opacity.clamp(0.0, 1.0) * 255.0) as u8);- for j in 0..=n {- for i in 0..=n {- let (u, v) = (i as f64 / n as f64, j as f64 / n as f64);+ for v in &vs {+ for u in &us {let (x, y) = w.map(r[0] + u * (r[2] - r[0]), r[1] + v * (r[3] - r[1]));- mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x as f32, y as f32), uv: pos2(u as f32 * uv[0], v as f32 * uv[1]), color: tint });- }- }- for j in 0..n {- for i in 0..n {- let a = (j * (n + 1) + i) as u32;- mesh.add_triangle(a, a + 1, a + n as u32 + 2);- mesh.add_triangle(a, a + n as u32 + 2, a + n as u32 + 1);+ mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x as f32, y as f32), uv: pos2(*u as f32 * uv[0], *v as f32 * uv[1]), color: tint });}}+ let pos: Vec<[f32; 2]> = mesh.vertices.iter().map(|v| [v.pos.x, v.pos.y]).collect();+ let rest: Vec<[f32; 2]> = vs.iter().flat_map(|v| us.iter().map(move |u| [(r[0] + u * (r[2] - r[0])) as f32, (r[1] + v * (r[3] - r[1])) as f32])).collect();+ mesh.indices = crate::warp_preview::triangle_order(&pos, &rest, us.len());painter.add(clip_to_canvas(mesh, canvas_size(pv), |p| xf.to_screen(p.x, p.y)));if let Some(a) = &pv.above {a.draw(painter, xf);@@ -1717,7 +1775,6 @@ fn draw_warp(painter: &egui::Painter, xf: &ViewXform, t: &TransformSession, w: &let accent = crate::theme::Tokens::get(painter.ctx()).accent;let line = Stroke::new(1.0, accent);let thin = Stroke::new(0.75, accent.gamma_multiply(0.7));- let m = w.to_mesh(1, 1);let curve = |fixed_u: Option<f64>, fixed_v: Option<f64>| -> Vec<Pos2> {(0..=40).map(|k| {@@ -1753,27 +1810,7 @@ fn draw_warp(painter: &egui::Painter, xf: &ViewXform, t: &TransformSession, w: &painter.add(egui::Shape::line(curve(None, Some(win[1])), line));}if w.style == WarpStyle::Custom {- let (nx, ny) = (m.nx(), m.ny());- for j in 0..ny {- for i in 0..nx {- if !on_section_edge(i, j) {- continue;- }- let p = scr(m.point(i, j));- let anchor = i.is_multiple_of(3) && j.is_multiple_of(3);- if anchor {- let r = egui::Rect::from_center_size(p, vec2(7.0, 7.0));- painter.rect_filled(r, 0.0, Color32::WHITE);- painter.rect_stroke(r, 0.0, line, egui::StrokeKind::Inside);- } else {- // Arm to the nearest anchor along the row/column.- let (ai, aj) = if i.is_multiple_of(3) { (i, if j % 3 == 1 { j - 1 } else { j + 1 }) } else { (if i % 3 == 1 { i - 1 } else { i + 1 }, j) };- painter.line_segment([scr(m.point(ai, aj)), p], line);- painter.circle_filled(p, 3.5, Color32::WHITE);- painter.circle_stroke(p, 3.5, line);- }- }- }+ draw_warp_points(painter, &m, scr, pv, line);}if let Some((tool, p)) = guide {let (s, t) = m.param_at(p);@@ -1815,6 +1852,8 @@ fn readout(t: &TransformSession) -> (f64, f64, f64, f64) {/// Width of the mode, cancel and commit cluster kept on the right of the options bar.const ACTIONS_W: f32 = 140.0;+/// Width of the action buttons when they follow the Warp fields (one more than the box bar: Reset).+const WARP_ACTIONS_W: f32 = 176.0;/// Reach of the reference point X/Y fields: the largest document side (`image.canvasSize`'s limit).const POSITION_LIMIT_PX: f32 = 300_000.0;@@ -1832,26 +1871,29 @@ fn scale_limit_pct(side: f64) -> f32 {((f64::from(POSITION_LIMIT_PX) / side * 100.0) as f32).clamp(100.0, SCALE_LIMIT_PCT)}-/// Options bar while transforming: reference point X/Y, W/H %, angle, interpolation, and, pinned-/// to the right, the warp switch, cancel and commit.+/// Options bar while transforming: the fields (reference point X/Y, W/H %, angle, interpolation,+/// or the warp controls), then the mode switch, cancel and commit right after them. A bar too+/// narrow for both pins the buttons to the right edge and clips the fields, so Commit and Cancel+/// are always reachable.pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let Some(t) = app.ui.transform.clone() else { return };let bar = ui.available_rect_before_wrap();- let split = (bar.right() - ACTIONS_W).max(bar.left());+ let warping = t.warp.is_some();+ let buttons_w = if warping { WARP_ACTIONS_W } else { ACTIONS_W };+ let split = (bar.right() - buttons_w).max(bar.left());let fields = egui::Rect::from_min_max(bar.min, egui::pos2(split, bar.bottom()));- let actions = egui::Rect::from_min_max(egui::pos2(split, bar.top()), bar.max);- {- let mut row =- ui.new_child(egui::UiBuilder::new().id_salt("transform-fields").max_rect(fields).layout(egui::Layout::left_to_right(egui::Align::Center)));- row.set_clip_rect(fields);- if let Some(w) = t.warp.clone() {- warp_fields(app, &mut row, &w);- } else {- transform_fields(app, &mut row, &t);- }+ let mut row = ui.new_child(egui::UiBuilder::new().id_salt("transform-fields").max_rect(fields).layout(egui::Layout::left_to_right(egui::Align::Center)));+ row.set_clip_rect(fields);+ if let Some(w) = t.warp.clone() {+ warp_fields(app, &mut row, &w);+ } else {+ transform_fields(app, &mut row, &t);}- let mut row = ui.new_child(egui::UiBuilder::new().id_salt("transform-actions").max_rect(actions).layout(egui::Layout::right_to_left(egui::Align::Center)));- transform_actions(app, &mut row, t.warp.is_some());+ crate::widgets::vline(&mut row, 22.0);+ let start = row.min_rect().right().min(split);+ let actions = egui::Rect::from_min_max(egui::pos2(start, bar.top()), egui::pos2(start + buttons_w, bar.bottom()));+ let mut btns = ui.new_child(egui::UiBuilder::new().id_salt("transform-actions").max_rect(actions).layout(egui::Layout::right_to_left(egui::Align::Center)));+ transform_actions(app, &mut btns, warping);}fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) {@@ -1922,6 +1964,47 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) {let lbl = |ui: &mut egui::Ui, s: &str| {ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0));};+ // Split, Grid, then the warp style with its bend fields.+ lbl(ui, tl!("Split:"));+ let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool);+ for (tool, tip) in [+ (SplitTool::Cross, tl!("Split Warp Crosswise")),+ (SplitTool::Vertical, tl!("Split Warp Vertically")),+ (SplitTool::Horizontal, tl!("Split Warp Horizontally")),+ ] {+ let on = armed == Some(tool);+ if split_icon(ui, tool.icon(), tip, on).clicked()+ && let Some(pv) = app.transform_preview.as_mut()+ {+ pv.split_tool = if on { None } else { Some(tool) };+ pv.split_placing = false;+ pv.split_pointer = None;+ pv.split_quick = false;+ }+ }+ crate::widgets::vline(ui, 22.0);+ lbl(ui, tl!("Grid:"));+ let mesh = w.mesh.clone().unwrap_or_else(|| BezierMesh::identity(w.bounds, 1, 1));+ let mut grid = warp_grid_id(&mesh).to_string();+ let opts = [+ ("custom".to_string(), tl!("Custom")),+ ("default".to_string(), tl!("Default")),+ ("3".to_string(), tl!("3 x 3")),+ ("4".to_string(), tl!("4 x 4")),+ ("5".to_string(), tl!("5 x 5")),+ ];+ if crate::widgets::dropdown(ui, "warp-grid", &mut grid, &opts, 92.0)+ && let Some(n) = match grid.as_str() {+ "default" => Some(1),+ "3" => Some(3),+ "4" => Some(4),+ "5" => Some(5),+ _ => None,+ }+ {+ let _ = edit_session_warp(app, "edit.transform.warpGrid", &json!({ "size": n }));+ }+ crate::widgets::vline(ui, 22.0);lbl(ui, tl!("Warp:"));let mut style = w.style;let opts: Vec<(WarpStyle, &str)> = WarpStyle::all().map(|s| (s, s.label())).collect();@@ -1935,12 +2018,15 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) {s => Warp { style: s, bend: if w.style.is_preset() { w.bend } else { 50.0 }, ..Warp::none(b) },});}- if w.style.is_preset() {- let mut vertical = w.vertical;- if crate::widgets::checkbox(ui, &mut vertical, tl!("Vertical")).changed()+ // Orientation and the bend fields are always there, and only act on a preset style.+ let preset = w.style.is_preset();+ ui.add_enabled_ui(preset, |ui| {+ let orient = crate::icons::button(ui, "arrow-left-right", 26.0, w.vertical, tl!("Vertical"));+ orient.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, preset, "Change warp orientation"));+ if orient.clicked()&& let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut()){- cur.vertical = vertical;+ cur.vertical = !cur.vertical;}let fields: [(&str, f64); 3] = [(tl!("Bend:"), w.bend), ("H:", w.h_distort), ("V:", w.v_distort)];for (k, (name, v)) in fields.iter().enumerate() {@@ -1956,47 +2042,23 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) {}}}- } else {- crate::widgets::vline(ui, 22.0);- lbl(ui, tl!("Split:"));- let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool);- for (tool, tip) in [- (SplitTool::Cross, tl!("Split Warp Crosswise")),- (SplitTool::Vertical, tl!("Split Warp Vertically")),- (SplitTool::Horizontal, tl!("Split Warp Horizontally")),- ] {- let on = armed == Some(tool);- if split_icon(ui, tool.icon(), tip, on).clicked()- && let Some(pv) = app.transform_preview.as_mut()- {- pv.split_tool = if on { None } else { Some(tool) };- pv.split_placing = false;- pv.split_pointer = None;- pv.split_quick = false;- }- }- crate::widgets::vline(ui, 22.0);- lbl(ui, tl!("Grid:"));- let mesh = w.mesh.clone().unwrap_or_else(|| BezierMesh::identity(w.bounds, 1, 1));- let mut grid = warp_grid_id(&mesh).to_string();- let opts = [- ("custom".to_string(), tl!("Custom")),- ("default".to_string(), tl!("Default")),- ("3".to_string(), tl!("3 x 3")),- ("4".to_string(), tl!("4 x 4")),- ("5".to_string(), tl!("5 x 5")),- ];- if crate::widgets::dropdown(ui, "warp-grid", &mut grid, &opts, 92.0)- && let Some(n) = match grid.as_str() {- "default" => Some(1),- "3" => Some(3),- "4" => Some(4),- "5" => Some(5),- _ => None,- }- {- let _ = edit_session_warp(app, "edit.transform.warpGrid", &json!({ "size": n }));- }+ });+}++/// Back to the untouched box: the default one-patch grid over the box, no bend.+pub fn reset_warp(app: &mut PhotocraftApp) {+ let Some(t) = app.ui.transform.as_mut() else { return };+ if t.warp.is_none() {+ return;+ }+ let b = t.rect;+ t.warp = Some(Warp::custom(BezierMesh::identity(b, 1, 1), b));+ if let Some(pv) = app.transform_preview.as_mut() {+ pv.warp_drag = None;+ pv.split_tool = None;+ pv.split_pointer = None;+ pv.split_placing = false;+ pv.split_quick = false;}}@@ -2071,6 +2133,13 @@ fn transform_actions(app: &mut PhotocraftApp, ui: &mut egui::Ui, warping: bool)if cancel_btn.clicked() {cancel(app);}+ if warping {+ let reset = crate::icons::button(ui, "undo-2", 26.0, false, tl!("Reset"));+ reset.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Reset warp"));+ if reset.clicked() {+ reset_warp(app);+ }+ }crate::widgets::vline(ui, 22.0);let mode = crate::icons::button(ui, "grid-3x3", 26.0, warping, tl!("Switch between free transform and warp modes"));mode.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Switch between free transform and warp modes"));@@ -2184,6 +2253,58 @@ mod tests {assert!(h.state().ui.transform.is_none());}+ #[test]+ fn free_transform_bar_buttons_follow_the_fields_on_a_wide_bar() {+ use egui_kittest::Harness;+ use egui_kittest::kittest::Queryable;+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.ui.transform = Some(session());+ let width = 2400.0;+ let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ return;+ }+ ui.horizontal_centered(|ui| options_bar(app, ui));+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);+ h.run_steps(6);+ let commit = h.get_by_label("Commit transform").rect();+ assert!(commit.right() < width * 0.7, "commit sits next to the fields, not at the far right: {commit:?}");+ }++ #[test]+ fn warp_bar_buttons_follow_the_fields_on_a_wide_bar() {+ use egui_kittest::Harness;+ use egui_kittest::kittest::Queryable;+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.ui.transform = Some(session());+ let width = 2000.0;+ let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ return;+ }+ ui.horizontal_centered(|ui| options_bar(app, ui));+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);+ h.run_steps(6);+ h.get_by_label("Switch between free transform and warp modes").click();+ h.run_steps(4);+ assert!(h.state().ui.transform.as_ref().unwrap().warp.is_some());+ let commit = h.get_by_label("Commit transform").rect();+ assert!(commit.right() < width / 2.0, "commit sits next to the fields, not at the far right: {commit:?}");+ let reset = h.get_by_label("Reset warp").rect();+ assert!(reset.right() < commit.left() + 1.0, "reset is left of commit");+ h.get_by_label("Reset warp").click();+ h.run_steps(2);+ assert!(h.state().ui.transform.as_ref().unwrap().warp.as_ref().unwrap().is_identity());+ }+/// Types `text` + Enter into the `n`th numeric field of the transform bar (X, Y, W, H, angle…).fn type_into_bar_field(n: usize, text: &str) -> TransformSession {use egui_kittest::Harness;@@ -2938,6 +3059,36 @@ mod tests {assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Distort);}+ #[test]+ fn right_click_menu_warp_row_enters_warp_mode() {+ let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));+ let ctx = egui::Context::default();+ begin(&mut app, &ctx).unwrap();+ assert!(crate::canvas_tool_menu::open_transform(&mut app, [10.0, 10.0]));+ let menu = app.ui.canvas_tool_menu.clone().unwrap();+ assert!(crate::canvas_tool_menu::rows(&menu).iter().flatten().any(|e| e.1 == "edit.transform.warp"));+ assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp"));+ // Only the current mode (Free Transform) is checked: not Scale, Rotate or Warp.+ let checked: Vec<&str> =+ crate::canvas_tool_menu::rows(&menu).iter().flatten().map(|e| e.1).filter(|id| crate::canvas_tool_menu::mode_checked(&app, &menu, id)).collect();+ assert_eq!(checked, ["edit.freeTransform"]);+ crate::canvas_tool_menu::choose(&mut app, &ctx, "edit.transform.warp");+ assert!(app.ui.transform.as_ref().unwrap().warp.is_some());+ // Already warping: the row is no longer offered.+ assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp"));+ }++ #[test]+ fn right_click_menu_warp_row_is_off_for_a_lone_path() {+ let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));+ let ctx = egui::Context::default();+ begin(&mut app, &ctx).unwrap();+ app.ui.transform.as_mut().unwrap().path = Some(json!({}));+ assert!(crate::canvas_tool_menu::open_transform(&mut app, [10.0, 10.0]));+ let menu = app.ui.canvas_tool_menu.clone().unwrap();+ assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp"));+ }+fn app_with_square(size: u32, fill: photocraft_geom::Rect) -> PhotocraftApp {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());app.session.execute("file.new", json!({"width": size, "height": size})).unwrap();@@ -3250,6 +3401,84 @@ mod tests {assert!(app.ui.transform.as_ref().unwrap().warp.is_none());}+ fn warping_square() -> PhotocraftApp {+ let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32));+ begin_warp(&mut app, &egui::Context::default()).unwrap();+ app+ }++ fn warp_mesh(app: &PhotocraftApp) -> BezierMesh {+ app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.clone().unwrap()+ }++ #[test]+ fn warp_drag_from_inside_the_grid_pulls_the_surface_under_the_pointer() {+ let mut app = warping_square();+ let before = warp_mesh(&app);+ // (20, 20) is mid-cell, far from every anchor and handle.+ warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);+ assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Surface { .. })));+ warp_pointer(&mut app, ToolEvent::Move { x: 30.0, y: 14.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);+ warp_pointer(&mut app, ToolEvent::Up { x: 30.0, y: 14.0 }, 2.0, egui::Modifiers::NONE);+ let after = warp_mesh(&app);+ let (s, t) = surface_at(&before, [20.0, 20.0]).unwrap();+ let moved = after.eval(s, t);+ assert!((moved[0] - 30.0).abs() < 1e-6 && (moved[1] - 14.0).abs() < 1e-6, "{moved:?}");+ assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none());+ // The picture keeps filling its frame: a pull in the middle leaves the box corners put.+ assert!([0, 3, 12, 15].iter().all(|k| after.points[*k] == before.points[*k]));+ assert!(after.points[5] != before.points[5], "the inside of the grid moved");+ }++ #[test]+ fn a_handle_belongs_to_the_anchor_it_hangs_off() {+ assert_eq!(handle_anchor(0, 1), (0, 0));+ assert_eq!(handle_anchor(0, 2), (0, 3));+ assert_eq!(handle_anchor(1, 0), (0, 0));+ assert_eq!(handle_anchor(5, 3), (6, 3));+ assert_eq!(handle_anchor(3, 3), (3, 3));+ }++ #[test]+ fn reset_warp_returns_to_the_untouched_grid_and_keeps_the_session() {+ let mut app = warping_square();+ warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);+ warp_pointer(&mut app, ToolEvent::Up { x: 30.0, y: 14.0 }, 2.0, egui::Modifiers::NONE);+ assert!(!app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().is_identity());+ reset_warp(&mut app);+ let w = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap();+ assert!(w.is_identity(), "back to the untouched box");+ assert_eq!(w.mesh.as_ref().map(|m| (m.us.len(), m.vs.len())), Some((2, 2)));+ assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none());+ // Not warping: nothing to reset.+ leave_warp(&mut app);+ reset_warp(&mut app);+ assert!(app.ui.transform.as_ref().unwrap().warp.is_none());+ }++ #[test]+ fn warp_press_outside_the_grid_grabs_nothing() {+ let mut app = warping_square();+ let before = warp_mesh(&app);+ warp_pointer(&mut app, ToolEvent::Down { x: 55.0, y: 55.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);+ assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none());+ warp_pointer(&mut app, ToolEvent::Up { x: 60.0, y: 60.0 }, 2.0, egui::Modifiers::NONE);+ assert_eq!(warp_mesh(&app), before);+ }++ #[test]+ fn ctrl_click_cuts_the_grid_both_ways() {+ let mut app = warping_square();+ let ctrl = egui::Modifiers::COMMAND;+ warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, ctrl);+ warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, ctrl);+ let m = warp_mesh(&app);+ // A cut each way at the pointer (the default grid's rule-of-thirds guides become real+ // lines too, as with the Cross split tool).+ assert!(m.us.iter().any(|u| (u - 0.5).abs() < 1e-6), "vertical cut: {:?}", m.us);+ assert!(m.vs.iter().any(|v| (v - 0.5).abs() < 1e-6), "horizontal cut: {:?}", m.vs);+ }+#[test]fn replacing_the_warp_mesh_cancels_a_pending_point_drag() {let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32));@@ -3260,7 +3489,7 @@ mod tests {}pointer(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, egui::Modifiers::NONE);- assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_some(), "the anchor drag is armed");+ assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Point { .. })), "the anchor drag is armed");split(&mut app, "edit.transform.removeWarpSplit", None).unwrap();assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none(), "the old mesh index is discarded");@@ -3272,7 +3501,7 @@ mod tests {/// A press on a preset warp that misses its points leaves the preset alone (no invisible undo/// step); grabbing a point turns it into a custom mesh.#[test]- fn a_press_on_a_preset_warp_converts_it_only_when_it_grabs_a_point() {+ fn a_press_on_a_preset_warp_converts_it_only_when_it_grabs_the_grid() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();app.sync_views();@@ -3287,9 +3516,15 @@ mod tests {let t = app.ui.transform.as_mut().unwrap();let preset = Warp::preset(WarpStyle::Arc, 50.0, t.rect);t.warp = Some(preset.clone());+ // Off the grid altogether: a miss.+ warp_pointer(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);+ warp_pointer(&mut app, ToolEvent::Up { x: 60.0, y: 60.0 }, 2.0, egui::Modifiers::NONE);+ assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref(), Some(&preset), "a miss changes nothing");+ // Inside the grid, away from every point: the surface is grabbed, so the preset converts.warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);+ assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Custom);warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, egui::Modifiers::NONE);- assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref(), Some(&preset), "a miss changes nothing");+ app.ui.transform.as_mut().unwrap().warp = Some(preset.clone());let corner = preset.to_mesh(1, 1).points[15];warp_pointer(&mut app, ToolEvent::Down { x: corner[0], y: corner[1], pressure: 1.0 }, 2.0, egui::Modifiers::NONE);assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Custom);diff --git a/crates/ui-egui/src/warp_preview.rs b/crates/ui-egui/src/warp_preview.rsnew file mode 100644index 000000000..ec1437579--- /dev/null+++ b/crates/ui-egui/src/warp_preview.rs@@ -0,0 +1,152 @@+//! Where the Warp preview samples its mesh: finer where the warp pulls hard.+//!+//! A fixed grid of samples across the whole picture draws a narrow, heavily pulled grid cell with+//! only a few big triangles. Their shear shows as a comb of long wedges along the fold. Here each+//! grid cell gets as many samples as its control points are spread wide, so every triangle stays+//! a few screen pixels across wherever the surface is stretched.++use photocraft_geom::warp::BezierMesh;++/// Target screen pixels per preview segment.+const SEGMENT_PX: f64 = 6.0;+/// Fewest and most segments one grid cell gets along an axis.+const MIN_PER_CELL: usize = 4;+const MAX_PER_CELL: usize = 96;+/// Most samples along either axis for the whole mesh (the triangle count grows with their product).+const MAX_PER_AXIS: usize = 240;++/// Normalised sample positions `(us, vs)` for `mesh` shown at `zoom` screen px per document px.+/// Both include every grid line (0, the knots and 1) in increasing order.+pub fn samples(mesh: &BezierMesh, zoom: f64) -> (Vec<f64>, Vec<f64>) {+ let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 };+ let (cols, rows) = (mesh.us.len() - 1, mesh.vs.len() - 1);+ let nx = mesh.nx();+ // Screen size of each cell's control points: bounds how far the cell's surface can stretch.+ let mut cu = vec![MIN_PER_CELL; cols];+ let mut cv = vec![MIN_PER_CELL; rows];+ for (b, cv) in cv.iter_mut().enumerate() {+ for (a, cu) in cu.iter_mut().enumerate() {+ let (mut lo, mut hi) = ([f64::MAX; 2], [f64::MIN; 2]);+ for j in 0..4 {+ for i in 0..4 {+ if let Some(p) = mesh.points.get((3 * b + j) * nx + 3 * a + i) {+ for k in 0..2 {+ lo[k] = lo[k].min(p[k]);+ hi[k] = hi[k].max(p[k]);+ }+ }+ }+ }+ let ext = ((hi[0] - lo[0]).max(hi[1] - lo[1]) * zoom).abs();+ let n = if ext.is_finite() { (ext / SEGMENT_PX).ceil() as usize } else { MIN_PER_CELL };+ let n = n.clamp(MIN_PER_CELL, MAX_PER_CELL);+ *cu = (*cu).max(n);+ *cv = (*cv).max(n);+ }+ }+ (axis(&mesh.us, &mut cu), axis(&mesh.vs, &mut cv))+}++/// Triangle indices for a `row`-wide vertex grid (`pos` and `rest` row by row; `rest` is where each+/// vertex sits with no warp), two triangles per cell. Cells are drawn from the most displaced to the+/// least, so the part of the picture the warp left alone is on top.+///+/// Drawing in plain row order lets the layers of a hard pull (the sheets of an S-shaped fold) cover+/// each other row by row, which shows as a comb along the fold. A fold's layers differ in how far+/// the warp moved them, so ordering by displacement keeps each layer whole, with the tip of the+/// pull underneath and the picture as it was on top.+pub fn triangle_order(pos: &[[f32; 2]], rest: &[[f32; 2]], row: usize) -> Vec<u32> {+ if row < 2 || pos.len() != rest.len() {+ return Vec::new();+ }+ let rows = pos.len() / row;+ let moved = |k: usize| match (pos.get(k), rest.get(k)) {+ (Some(p), Some(r)) => (p[0] - r[0]).hypot(p[1] - r[1]),+ _ => 0.0,+ };+ let mut cells: Vec<(f32, usize)> = Vec::with_capacity(rows * row);+ for j in 0..rows.saturating_sub(1) {+ for i in 0..row - 1 {+ let a = j * row + i;+ cells.push(((moved(a) + moved(a + 1) + moved(a + row) + moved(a + row + 1)) / 4.0, a));+ }+ }+ cells.sort_by(|x, y| y.0.total_cmp(&x.0));+ let mut out = Vec::with_capacity(cells.len() * 6);+ for (_, a) in cells {+ out.extend([a, a + 1, a + row + 1, a, a + row + 1, a + row].map(|k| k as u32));+ }+ out+}++/// Samples along one axis: `counts[k]` segments in knot interval `k`, scaled down together when+/// the total would pass [`MAX_PER_AXIS`].+fn axis(knots: &[f64], counts: &mut [usize]) -> Vec<f64> {+ let total: usize = counts.iter().sum();+ if total > MAX_PER_AXIS {+ for c in counts.iter_mut() {+ *c = (*c * MAX_PER_AXIS / total).max(2);+ }+ }+ let mut out = Vec::with_capacity(counts.iter().sum::<usize>() + 1);+ for (k, n) in counts.iter().enumerate() {+ let (a, b) = (knots[k], knots[k + 1]);+ out.extend((0..*n).map(|i| a + (b - a) * i as f64 / *n as f64));+ }+ out.push(1.0);+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_narrow_pulled_cell_gets_as_many_samples_as_its_stretch_needs() {+ // A 900 x 1100 mesh with a narrow column (0.45..0.5) pulled 300 px to the left.+ let mut base = BezierMesh::identity([0.0, 0.0, 900.0, 1100.0], 1, 1);+ assert!(base.split_u(0.45) && base.split_u(0.5));+ let mut m = base.clone();+ m.pull(&base.points, 0.47, 0.5, [-300.0, 0.0]);+ let (us, vs) = samples(&m, 1.0);+ let in_narrow = us.iter().filter(|u| **u >= 0.45 && **u < 0.5).count();+ assert!(in_narrow >= 30, "{in_narrow} samples in the narrow cell");+ // Grid lines are samples, and the lists are sorted and span the box.+ for k in [0.0, 0.45, 0.5, 1.0] {+ assert!(us.iter().any(|u| (u - k).abs() < 1e-12), "{k}");+ }+ assert!(us.windows(2).all(|w| w[1] > w[0]) && vs.windows(2).all(|w| w[1] > w[0]));+ assert!(us.len() <= MAX_PER_AXIS + 8 && vs.len() <= MAX_PER_AXIS + 8, "{} x {}", us.len(), vs.len());+ }++ #[test]+ fn the_most_displaced_cells_are_drawn_first() {+ // A 4 x 3 vertex grid; the middle column was pulled 30 px right, so it moved most.+ let rest: Vec<[f32; 2]> = (0..3).flat_map(|j| (0..4).map(move |i| [i as f32 * 10.0, j as f32 * 10.0])).collect();+ let pos: Vec<[f32; 2]> = rest.iter().enumerate().map(|(k, p)| if k % 4 == 1 || k % 4 == 2 { [p[0] + 30.0, p[1]] } else { *p }).collect();+ let idx = triangle_order(&pos, &rest, 4);+ assert_eq!(idx.len(), 2 * 2 * 3 * 3);+ // Cells come in whole pairs of triangles, and displacement never rises along the list.+ let moved = |k: u32| (pos[k as usize][0] - rest[k as usize][0]).abs();+ let per_cell: Vec<f32> = idx.chunks(6).map(|c| c.iter().map(|k| moved(*k)).sum::<f32>()).collect();+ assert!(per_cell.windows(2).all(|w| w[0] >= w[1]), "{per_cell:?}");+ assert!(per_cell[0] > per_cell[per_cell.len() - 1]);+ assert!(triangle_order(&pos, &rest[..5], 4).is_empty());+ }++ #[test]+ fn an_unwarped_mesh_stays_cheap() {+ let m = BezierMesh::identity([0.0, 0.0, 100.0, 100.0], 1, 1);+ let (us, vs) = samples(&m, 1.0);+ assert!(us.len() <= 20 && vs.len() <= 20, "{} x {}", us.len(), vs.len());+ }++ #[test]+ fn a_bad_zoom_still_gives_samples() {+ let m = BezierMesh::identity([0.0, 0.0, 100.0, 100.0], 2, 2);+ for z in [0.0, -1.0, f64::NAN, f64::INFINITY] {+ let (us, vs) = samples(&m, z);+ assert!(us.len() >= 3 && vs.len() >= 3);+ }+ }+}