diff --git a/.gitattributes b/.gitattributes index e3ff66fc1c..dc4403a4db 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,4 @@ # The DXF writer goldens are compared byte for byte with the writer's output (LF line endings). crates/cad/tests/data/*.dxf -text +# `cargo xtask ui-commands --check` compares this file byte for byte with rustfmt's output (LF line endings). +crates/mcp/src/ui_catalog.rs -text diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 53e1cb5786..77c6371e49 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -527,41 +527,174 @@ fn bridge(ring: Vec, hole: &[Corner], others: &[Vec], work: &mut /// is set and it lies straight between them: it then stays a corner of the triangles beside it. If /// no ear is left (a ring that crosses itself), the rest is cut as a fan. fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool) -> Result<(), String> { + let grid = if ring.len() > GRID_CORNERS { Grid::new(ring) } else { None }; + cut(ring, out, work, keep_straight, grid.as_ref()).map(|_| ()) +} + +/// Rings with more corners than this are sorted into a [`Grid`] before they are cut. +const GRID_CORNERS: usize = 64; + +/// The corners of a ring sorted into square cells, so that the test of an ear looks only at the +/// corners in the cells its triangle covers, widened by `margin`. +struct Grid { + x: f64, + y: f64, + size: f64, + cols: usize, + rows: usize, + /// Where each cell's corners start in `corners`, row by row, with the end of the last cell + /// after them. + start: Vec, + corners: Vec, + /// How far outside a triangle the cells looked at reach: far more than the rounding of the + /// tests of a corner against the triangle's edges, at the size and distance from the origin of + /// the ring. + margin: f64, +} + +impl Grid { + /// The grid of `ring`, about one corner to a cell. `None` for a ring with a corner that is not + /// finite or with no extent. + fn new(ring: &[Corner]) -> Option { + if !ring.iter().all(|c| c.x.is_finite() && c.y.is_finite()) { + return None; + } + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for c in ring { + (x0, y0, x1, y1) = (x0.min(c.x), y0.min(c.y), x1.max(c.x), y1.max(c.y)); + } + let extent = (x1 - x0).max(y1 - y0); + let size = extent / (ring.len() as f64).sqrt().ceil(); + if !(size > 0.0 && size.is_finite()) { + return None; + } + let (cols, rows) = (((x1 - x0) / size) as usize + 1, ((y1 - y0) / size) as usize + 1); + let cells = cols.checked_mul(rows)?; + let reach = x0.abs().max(x1.abs()).max(y0.abs()).max(y1.abs()); + let margin = (extent + reach) * 1e-6 + 1e-8; + let mut grid = Grid { x: x0, y: y0, size, cols, rows, start: vec![], corners: vec![], margin }; + let mut start = vec![0usize; cells + 1]; + for c in ring { + start[grid.cell(c) + 1] += 1; + } + for k in 1..start.len() { + start[k] += start[k - 1]; + } + let mut fill = start.clone(); + let mut corners = vec![0; ring.len()]; + for (k, c) in ring.iter().enumerate() { + let at = &mut fill[grid.cell(c)]; + corners[*at] = k; + *at += 1; + } + (grid.start, grid.corners) = (start, corners); + Some(grid) + } + + fn col(&self, x: f64) -> usize { + (((x - self.x) / self.size).max(0.0) as usize).min(self.cols - 1) + } + + fn row(&self, y: f64) -> usize { + (((y - self.y) / self.size).max(0.0) as usize).min(self.rows - 1) + } + + fn cell(&self, c: &Corner) -> usize { + self.row(c.y) * self.cols + self.col(c.x) + } + + /// Whether `blocks` holds for a corner in a cell that triangle `t` covers, widened by the + /// margin. Every corner within the margin of the triangle is in such a cell. + fn any_near(&self, t: [&Corner; 3], mut blocks: impl FnMut(usize) -> bool) -> bool { + let m = self.margin; + let low = t.iter().map(|p| p.y).fold(f64::INFINITY, f64::min); + let high = t.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max); + for r in self.row(low - m)..=self.row(high + m) { + // The triangle's extent across the row's band, widened by the margin each way. + let top = self.y + r as f64 * self.size; + let (from, to) = ((top - m).clamp(low, high), (top + self.size + m).clamp(low, high)); + let (mut left, mut right) = (f64::INFINITY, f64::NEG_INFINITY); + for (p, q) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + let (p, q) = if p.y <= q.y { (p, q) } else { (q, p) }; + if q.y < from || p.y > to { + continue; + } + let xs = if q.y > p.y { + let at = |y: f64| p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x); + [at(from.max(p.y)), at(to.min(q.y))] + } else { + [p.x, q.x] + }; + for x in xs { + (left, right) = (left.min(x), right.max(x)); + } + } + if left > right { + continue; + } + for col in self.col(left - m)..=self.col(right + m) { + let cell = r * self.cols + col; + if self.corners[self.start[cell]..self.start[cell + 1]].iter().any(|&k| blocks(k)) { + return true; + } + } + } + false + } +} + +/// [`clip`], looking up the corners an ear's test needs in `grid` when there is one, for a triangle +/// whose every angle has a sine of at least 1e-6: a corner that passes the test then lies within +/// the grid's margin of the triangle. Other ears test every corner left. Returns the number of +/// corners tested against ears. +fn cut(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool, grid: Option<&Grid>) -> Result { let n = ring.len(); if n < 3 { - return Ok(()); + return Ok(0); } let mut next: Vec = (1..=n).map(|i| i % n).collect(); let mut prev: Vec = (0..n).map(|i| (i + n - 1) % n).collect(); - let (mut left, mut i, mut tried) = (n, 0usize, 0usize); + let mut gone = vec![false; n]; + let (mut left, mut i, mut tried, mut tested) = (n, 0usize, 0usize, 0usize); let cross = |a: &Corner, b: &Corner, c: &Corner| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); let same = |a: &Corner, b: &Corner| (a.x - b.x).hypot(a.y - b.y) < 1e-12; while left > 3 { let (a, c) = (prev[i], next[i]); let (pa, pb, pc) = (&ring[a], &ring[i], &ring[c]); let turn = cross(pa, pb, pc); - let scale = (pb.x - pa.x).hypot(pb.y - pa.y) * (pc.x - pb.x).hypot(pc.y - pb.y); + let (ab, bc) = ((pb.x - pa.x).hypot(pb.y - pa.y), (pc.x - pb.x).hypot(pc.y - pb.y)); + let scale = ab * bc; let mut ear = false; let flat = turn.abs() <= 1e-12 * scale.max(1e-300); let straight = keep_straight && flat && (pb.x - pa.x) * (pc.x - pb.x) + (pb.y - pa.y) * (pc.y - pb.y) > 0.0; let drop = flat && !straight; if !flat && turn > 0.0 { spend(work, left)?; - ear = true; - let mut k = next[c]; - while k != a { + // A corner inside the ear, or a kept corner on the ear's new edge, which would be + // left off every triangle. + let mut blocks = |k: usize| { + if k == a || k == i || k == c || gone[k] { + return false; + } + tested += 1; let p = &ring[k]; - if !same(p, pa) && !same(p, pb) && !same(p, pc) && cross(pa, pb, p) > 0.0 && cross(pb, pc, p) > 0.0 && cross(pc, pa, p) > 0.0 { - ear = false; - break; + (cross(pa, pb, p) > 0.0 && cross(pb, pc, p) > 0.0 && cross(pc, pa, p) > 0.0 && !same(p, pa) && !same(p, pb) && !same(p, pc)) + || (keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y))) + }; + let ca = (pa.x - pc.x).hypot(pa.y - pc.y); + let blocked = match grid { + Some(grid) if turn >= 1e-6 * (ab * bc).max(ab * ca).max(bc * ca) => grid.any_near([pa, pb, pc], &mut blocks), + _ => { + let mut k = next[c]; + let mut found = false; + while k != a && !found { + found = blocks(k); + k = next[k]; + } + found } - // A kept corner on the ear's new edge would be left off every triangle. - if keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y)) { - ear = false; - break; - } - k = next[k]; - } + }; + ear = !blocked; } if !ear && !drop && tried > left { // No ear anywhere: cut what is left as a fan. @@ -571,7 +704,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight out.push([ring[start].v, ring[k].v, ring[next[k]].v]); k = next[k]; } - return Ok(()); + return Ok(tested); } if ear || drop { if ear { @@ -579,6 +712,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight } next[a] = c; prev[c] = a; + gone[i] = true; left -= 1; i = a; tried = 0; @@ -589,7 +723,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight } let (a, c) = (prev[i], next[i]); out.push([ring[a].v, ring[i].v, ring[c].v]); - Ok(()) + Ok(tested) } #[cfg(test)] diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 29d58a66f6..960f85dbf0 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -235,6 +235,136 @@ fn flat_triangles_stop_at_their_budget() { assert!(work >= all, "{work} of {all}"); } +fn ring_of(points: &[(f64, f64)]) -> Vec { + points.iter().map(|&(x, y)| Corner { x, y, v: V3(x, y, 0.0) }).collect() +} + +/// `n` corners on a circle of radius `r` about (`x`, `y`), every other one pulled in to `inner` +/// times the radius, counterclockwise, or clockwise when `back` is set. +fn star_ring(n: usize, x: f64, y: f64, r: f64, inner: f64, back: bool) -> Vec { + let mut points: Vec<(f64, f64)> = (0..n) + .map(|i| { + let (s, c) = (std::f64::consts::TAU * i as f64 / n as f64).sin_cos(); + let r = if i % 2 == 1 { r * inner } else { r }; + (x + r * c, y + r * s) + }) + .collect(); + if back { + points.reverse(); + } + ring_of(&points) +} + +/// `count` rings drawn from a fixed seed, each counterclockwise about its center: corners at random +/// angles and distances, with every other corner pulled in close to the center in some (spikes), +/// corners rounded to whole numbers and slanted in some (so that corners on other parts of the ring +/// lie exactly on the line between two corners), corners midway along every edge in some, some +/// stretched along one axis, some so small that a corner within the tolerance of an ear's new edge +/// lies in another cell, and some far from the origin. +fn random_rings(count: usize) -> Vec> { + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + let mut unit = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + (0..count) + .map(|k| { + let n = 70 + (unit() * 200.0) as usize; + let mut angles: Vec = (0..n).map(|_| unit() * std::f64::consts::TAU).collect(); + angles.sort_by(f64::total_cmp); + angles.dedup(); + let spiky = k % 3 == 1; + let whole = k % 3 != 0; + let mut points: Vec<(f64, f64)> = angles + .iter() + .enumerate() + .map(|(i, a)| { + let r = if spiky && i % 2 == 1 { 0.05 + 0.1 * unit() } else { 0.5 + 0.5 * unit() }; + let (x, y) = (r * a.cos(), r * a.sin()); + if whole { + let (x, y) = ((40.0 * x).round(), (40.0 * y).round()); + (x + y, y) + } else { + (x, y) + } + }) + .collect(); + points.dedup(); + if points.first() == points.last() { + points.pop(); + } + if k % 2 == 0 { + points = points.iter().zip(points.iter().cycle().skip(1)).flat_map(|(&p, &q)| [p, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0)]).collect(); + } + let (sx, sy) = [(1.0, 1.0), (1024.0, 1.0), (1.0, 1.0 / 1024.0), (32.0, 64.0), (1e-7, 1e-7)][k % 5]; + let (ox, oy) = if k % 7 == 0 { ((1e6 * (unit() - 0.5)).round(), (1e6 * (unit() - 0.5)).round()) } else { (0.0, 0.0) }; + ring_of(&points.iter().map(|&(x, y)| (ox + sx * x, oy + sy * y)).collect::>()) + }) + .collect() +} + +/// The triangles `ring` is cut into, with the ring's corners sorted into a grid as [`clip`] sorts +/// them, or without one, and the number of corners tested against ears. +fn cut_ring(ring: &[Corner], keep_straight: bool, grid: bool) -> (Vec<[[u64; 3]; 3]>, usize) { + let grid = if grid && ring.len() > GRID_CORNERS { Grid::new(ring) } else { None }; + let (mut out, mut work) = (vec![], 0); + let tested = cut(ring, &mut out, &mut work, keep_straight, grid.as_ref()).unwrap(); + (out.into_iter().map(|t| t.map(|v| [v.0.to_bits(), v.1.to_bits(), v.2.to_bits()])).collect(), tested) +} + +#[test] +fn a_large_cap_is_cut_testing_few_corners_per_ear() { + // Tested against every corner left, the ears of a ring of n corners test about n * n / 2. + let n = 4096; + let (triangles, tested) = cut_ring(&star_ring(n, 0.0, 0.0, 100.0, 1.0, false), false, true); + assert_eq!(triangles.len(), n - 2); + assert!(tested <= 64 * n, "a ring of {n} corners tested {tested} corners against its ears"); + let (triangles, tested) = cut_ring(&star_ring(n, 0.0, 0.0, 100.0, 0.9, false), false, true); + assert_eq!(triangles.len(), n - 2); + assert!(tested <= 64 * n, "a star of {n} corners tested {tested} corners against its ears"); +} + +#[test] +fn rings_cut_with_a_grid_give_the_triangles_cut_without_one() { + let mut rings = vec![ + star_ring(500, 0.0, 0.0, 100.0, 1.0, false), + star_ring(1000, 3.0, -7.0, 50.0, 0.4, false), + star_ring(999, 0.0, 0.0, 1.0, 0.97, false), + // Far from the origin, where the rounding of the tests is largest. + star_ring(800, 1e7, -3e7, 20.0, 0.6, false), + ]; + // Holes bridged to their outline, so that some corners appear twice. + let mut work = 0; + let mut outline = star_ring(600, 0.0, 0.0, 100.0, 0.8, false); + for (k, (x, y)) in [(30.0, 0.0), (-20.0, 25.0), (-10.0, -40.0)].into_iter().enumerate() { + let hole = star_ring(90 + 10 * k, x, y, 12.0, 0.5, true); + outline = bridge(outline, &hole, &[], &mut work).unwrap(); + } + rings.push(outline); + // Edges carrying corners midway, as a cell shares with its finer neighbors. + let mut square = vec![]; + for (from, to) in [((0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)), ((10.0, 10.0), (0.0, 10.0)), ((0.0, 10.0), (0.0, 0.0))] { + for i in 0..40 { + let t = i as f64 / 40.0; + square.push((from.0 + (to.0 - from.0) * t, from.1 + (to.1 - from.1) * t)); + } + } + let square = ring_of(&square); + let dent = ring_of(&[(4.0, 4.0), (4.0, 6.0), (6.0, 6.0), (6.0, 5.0), (6.0, 4.0), (5.0, 4.0)]); + rings.push(bridge(square.clone(), &dent, &[], &mut work).unwrap()); + rings.push(square); + rings.extend(random_rings(1200)); + for (k, ring) in rings.iter().enumerate() { + for keep_straight in [false, true] { + let (with, _) = cut_ring(ring, keep_straight, true); + let (without, _) = cut_ring(ring, keep_straight, false); + assert!(with == without, "ring {k} (keep_straight {keep_straight}) is cut into other triangles with a grid"); + } + } +} + #[test] fn an_inside_bevel_stays_inside_a_collapsing_convex_outline() { for points in [