diff --git a/crates/sketch/examples/solve_bench.rs b/crates/sketch/examples/solve_bench.rs index cf31f9c78..19ee33848 100644 --- a/crates/sketch/examples/solve_bench.rs +++ b/crates/sketch/examples/solve_bench.rs @@ -6,7 +6,9 @@ use std::time::Instant; use solidcraft_geom::Vec2; -use solidcraft_sketch::{Analysis, Budget, ConstraintKind, Hold, Sketch, SolveReport, solve, solve_with}; +use solidcraft_sketch::{ + Analysis, Budget, ConstraintKind, Hold, PatternAlignment, Sketch, SketchPattern, SketchPatternKind, SolveReport, solve, solve_with, +}; /// A small deterministic generator for the start offsets. struct Lcg(u64); @@ -66,6 +68,33 @@ fn strip(n: usize) -> Result<(Sketch, usize), Box> { Ok((sk, bottom[0])) } +/// A slot (two arcs joined by two lines) copied `count` times around the origin by a circular +/// pattern. Returns the sketch and the seed's first arc start point. +fn slot_pattern(count: usize) -> Result<(Sketch, usize), Box> { + let mut sk = Sketch::new(); + let center = sk.add_point(Vec2::ZERO, None)?; + sk.add_constraint(ConstraintKind::Fix { p: center }, None)?; + let (c0, c1) = (Vec2::new(200.0, 0.0), Vec2::new(210.0, 0.0)); + let p = [c0 + Vec2::new(0.0, -2.0), c0 + Vec2::new(0.0, 2.0), c1 + Vec2::new(0.0, -2.0), c1 + Vec2::new(0.0, 2.0)]; + let pts: Vec = p.iter().map(|q| sk.add_point(*q, None)).collect::>()?; + let left = sk.add_arc(c0, p[1], p[0], [None, Some(pts[1]), Some(pts[0])], None)?; + let right = sk.add_arc(c1, p[2], p[3], [None, Some(pts[2]), Some(pts[3])], None)?; + let bottom = sk.add_line_pts(pts[0], pts[2], None)?; + let top = sk.add_line_pts(pts[1], pts[3], None)?; + let entities = [left, right, bottom, top].iter().filter_map(|i| sk.curves.get(*i).map(|c| c.id.clone())).collect(); + let center_id = sk.points.get(center).map(|q| q.id.clone()).ok_or("missing center")?; + let kind = SketchPatternKind::Circular { center: center_id, count, angle: 360.0, alignment: PatternAlignment::Right, reversed: false }; + let id = sk.fresh("pat")?; + sk.patterns.push(SketchPattern { id, entities, kind: kind.clone(), count_expression: None, instances: vec![], expressions: Default::default() }); + sk.update_pattern(0, kind)?; + Ok((sk, pts[1])) +} + +/// A hash of the whole sketch, every number to the bit, to compare solver output between builds. +fn fingerprint(sk: &Sketch) -> u64 { + format!("{sk:?}").bytes().fold(0xcbf29ce484222325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3)) +} + /// Best of `reps` solves of a copy of `sk` (ms) and the last report. fn time(sk: &Sketch, reps: usize, f: impl Fn(&mut Sketch) -> SolveReport) -> (f64, SolveReport) { let mut best = f64::MAX; @@ -104,5 +133,30 @@ fn main() -> Result<(), Box> { let (full, _) = time(&sk, 5, solve); println!("| {n} rectangles | {} | {frame:.2} ({:?}) | {full:.2} |", sk.points.len(), rep.status); } + println!(); + println!("| circular slot pattern | curves | points | drag frame on another line ms | drag frame on the seed ms | output |"); + println!("|---|---|---|---|---|---|"); + for count in [100usize, 500] { + let (mut sk, seed) = slot_pattern(count)?; + let a = sk.add_point(Vec2::new(-500.0, -500.0), None)?; + let b = sk.add_point(Vec2::new(-480.0, -500.0), None)?; + let l = sk.add_line_pts(a, b, None)?; + sk.add_constraint(ConstraintKind::Horizontal { l }, None)?; + let drag = |point: usize| -> (f64, u64) { + let mut start = sk.clone(); + if let Some(p) = start.points.get_mut(point) { + p.pos += Vec2::new(0.5, 0.3); + } + let hold = Hold { points: vec![point], radii: vec![] }; + let frame = |k: &mut Sketch| solve_with(k, &hold, None, Analysis::StatusOnly, Some(&mut Budget::frame())); + let (ms, _) = time(&start, 5, frame); + frame(&mut start); + (ms, fingerprint(&start)) + }; + let (other, other_out) = drag(b); + // Solving the whole pattern takes seconds at 500 copies. + let (on_seed, seed_out) = if count <= 100 { drag(seed) } else { (f64::NAN, 0) }; + println!("| {count} slots | {} | {} | {other:.2} | {on_seed:.2} | {other_out:016x} {seed_out:016x} |", sk.curves.len(), sk.points.len()); + } Ok(()) } diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index f3acc923d..3b32a4304 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -827,9 +827,13 @@ impl Sketch { } pub fn point_index(&self, id: &str) -> Option { + #[cfg(test)] + crate::tests::count_id_search(); self.points.iter().position(|p| p.id == id) } pub fn curve_index(&self, id: &str) -> Option { + #[cfg(test)] + crate::tests::count_id_search(); self.curves.iter().position(|c| c.id == id) } pub fn point(&self, i: usize) -> Option { diff --git a/crates/sketch/src/pattern.rs b/crates/sketch/src/pattern.rs index 7f98347e4..efa3650b0 100644 --- a/crates/sketch/src/pattern.rs +++ b/crates/sketch/src/pattern.rs @@ -334,15 +334,31 @@ impl Sketch { /// Conic rho is an authored shape parameter rather than a solver unknown. Like its /// defining points, the copies follow the seed's shape when that parameter is edited. pub(crate) fn refresh_pattern_shapes(&mut self) { - if !self.curves.iter().any(|c| matches!(c.kind, CurveKind::Conic { .. } | CurveKind::Arc { .. })) { + if self.patterns.is_empty() || !self.curves.iter().any(|c| matches!(c.kind, CurveKind::Conic { .. } | CurveKind::Arc { .. })) { return; } - for pattern in &self.patterns { - let sources: Vec<_> = pattern.entities.iter().filter_map(|id| self.curve_index(id)).collect(); - for instance in &pattern.instances { - for (seed, copy) in sources.iter().zip(&instance.curves) { + // This runs before every solve, drag frames included. Ids resolve through maps built + // once here: a linear search per copy cost patterns × copies × seeds × curves string + // comparisons, which dominated dragging anything in a sketch with a large pattern. + // Only curve shapes change below, so the indices stay valid throughout. + let (sources, copies): (Vec>, Vec>>>) = { + let curves = first_index(self.curves.iter().map(|c| c.id.as_str())); + self.patterns + .iter() + .map(|pattern| { + ( + pattern.entities.iter().filter_map(|id| curves.get(id.as_str()).copied()).collect(), + pattern.instances.iter().map(|i| i.curves.iter().map(|id| curves.get(id.as_str()).copied()).collect()).collect(), + ) + }) + .unzip() + }; + let points = first_index(self.points.iter().map(|p| p.id.as_str())); + for ((pattern, sources), copies) in self.patterns.iter().zip(&sources).zip(&copies) { + for (instance, copies) in pattern.instances.iter().zip(copies) { + for (seed, copy) in sources.iter().zip(copies) { if let Some(CurveKind::Conic { rho, .. }) = self.curves.get(*seed).map(|c| &c.kind) - && let Some(copy) = self.curve_index(copy) + && let Some(copy) = *copy { let rho = *rho; if let Some(CurveKind::Conic { rho: slot, .. }) = self.curves.get_mut(copy).map(|c| &mut c.kind) { @@ -355,9 +371,9 @@ impl Sketch { self.points .get(p) .and_then(|p| instance.points.iter().find(|(id, _)| *id == p.id)) - .and_then(|(_, id)| self.point_index(id)) + .and_then(|(_, id)| points.get(id.as_str()).copied()) }; - if let (Some(c), Some(a), Some(b), Some(copy)) = (mapped(c), mapped(a), mapped(b), self.curve_index(copy)) + if let (Some(c), Some(a), Some(b), Some(copy)) = (mapped(c), mapped(a), mapped(b), *copy) && let Some(curve) = self.curves.get_mut(copy) { curve.kind = CurveKind::Arc { c, a, b }; @@ -561,3 +577,12 @@ fn rotate(c: Vec2, ang: f64) -> impl Fn(Vec2) -> Vec2 { c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) } } + +/// Each id's first index, as `position` finds it. +fn first_index<'a>(ids: impl Iterator) -> std::collections::HashMap<&'a str, usize> { + let mut map = std::collections::HashMap::new(); + for (i, id) in ids.enumerate() { + map.entry(id).or_insert(i); + } + map +} diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index 2dce5a775..26c693344 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -25,6 +25,15 @@ impl Lcg { } } +thread_local! { + static ID_SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A linear search for a point or curve by id on this thread. +pub(crate) fn count_id_search() { + ID_SEARCHES.with(|c| c.set(c.get() + 1)); +} + /// Run `f` with the constructive seed on or off, without the seed-on/seed-off comparison (for /// tests that measure the difference). pub(crate) fn seeded(on: bool, f: impl FnOnce() -> T) -> T { @@ -1471,3 +1480,31 @@ fn a_held_solve_that_cannot_succeed_stops_once_it_stalls() { // A solve whose report names the violated constraints still iterates to the end. assert!(solve(Analysis::Full) >= 500); } + +/// Pattern upkeep runs before every solve, each drag frame included. It once looked up every +/// copy and its arc points by a linear search over all ids, so dragging anything in a sketch +/// with a large pattern of arcs spent most of each frame there; its searches must not grow +/// with the copies. The copies still follow their seed's arc direction. +#[test] +fn pattern_upkeep_does_not_search_ids_per_copy() { + let mut sk = Sketch::new(); + let center = sk.add_point(v(0.0, 0.0), None).unwrap(); + let arc = sk.add_arc(v(20.0, 0.0), v(23.0, 0.0), v(20.0, 3.0), [None, None, None], None).unwrap(); + let entities = vec![sk.curves[arc].id.clone()]; + let kind = SketchPatternKind::Circular { + center: sk.points[center].id.clone(), + count: 50, + angle: 360.0, + alignment: PatternAlignment::Right, + reversed: false, + }; + let id = sk.fresh("pat").unwrap(); + sk.patterns.push(SketchPattern { id, entities, kind: kind.clone(), count_expression: None, instances: vec![], expressions: Default::default() }); + sk.update_pattern(0, kind).unwrap(); + assert_eq!(sk.curves.len(), 50); + sk.curves[arc].reversed = true; + ID_SEARCHES.with(|c| c.set(0)); + sk.refresh_pattern_shapes(); + assert_eq!(ID_SEARCHES.with(std::cell::Cell::get), 0, "id searches in pattern upkeep"); + assert!(sk.curves.iter().all(|c| c.reversed)); +}