diff --git a/assets/icons/geometry_cleanup.svg b/assets/icons/geometry_cleanup.svg new file mode 100644 index 0000000000..2b39e9d020 --- /dev/null +++ b/assets/icons/geometry_cleanup.svg @@ -0,0 +1 @@ + diff --git a/crates/ocs_geom/src/geom2d/cleanup.rs b/crates/ocs_geom/src/geom2d/cleanup.rs new file mode 100644 index 0000000000..b948bd07f0 --- /dev/null +++ b/crates/ocs_geom/src/geom2d/cleanup.rs @@ -0,0 +1,990 @@ +//! Geometry Cleanup: the ends of lines, arcs and polylines that almost meet +//! other geometry. +//! +//! Three kinds of error, each found within a tolerance and repaired by +//! moving the end: +//! +//! - **Gap**: the end almost meets the end of another curve. +//! - **Overshoot**: the end runs a little past a curve that it crosses. +//! - **Undershoot**: the end stops a little short of a curve. +//! +//! An end that meets other geometry (within the weld tolerance) is not an +//! error. An end with more than one candidate is reported once, as the +//! candidate nearest to it; each end belongs to at most one error. + +use std::collections::{HashMap, HashSet}; +use std::f64::consts::{PI, TAU}; + +use super::angle::normalize_angle; +use super::cross::intersect; +use super::curve::{Arc, Curve, Line}; +use super::polyline::BulgeArc; +use super::vec::Vec2; +use super::{analytic_curve_bounds, Tolerance}; + +/// What is wrong with an end. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum EndErrorKind { + Gap, + Overshoot, + Undershoot, +} + +/// One end of one of the curves given to [`end_errors`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct CurveEnd { + /// The index of the curve. + pub curve: usize, + /// The start of the curve (`true`) or its end. + pub at_start: bool, +} + +/// An end that almost meets other geometry. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct EndError { + pub kind: EndErrorKind, + pub end: CurveEnd, + /// Where the end is. + pub location: [f64; 2], + /// Where the repair puts the end: the other end of a gap, the crossing + /// of an overshoot, or the point that an undershoot falls short of. + pub target: [f64; 2], + /// The other end of a gap. + pub other: Option, + /// For a gap between two straight ends: the point where their lines + /// cross, when it is ahead of both ends and within the tolerance of + /// each. + pub corner: Option<[f64; 2]>, + /// How far the end is from `target`, along the curve for an overshoot + /// or an undershoot. + pub deviation: f64, +} + +/// A straight or circular piece: a line, an arc, or one segment of a +/// polyline. +#[derive(Debug, Clone, Copy)] +enum Shape { + Line(Line), + Arc(Arc), +} + +impl Shape { + fn curve(self) -> Curve { + match self { + Shape::Line(line) => Curve::Line(line), + Shape::Arc(arc) => Curve::Arc(arc), + } + } +} + +struct Piece { + curve: usize, + shape: Shape, +} + +/// How an end continues past itself: along a straight line or along its +/// circle (counter-clockwise when `turn` is positive). +#[derive(Debug, Clone, Copy)] +enum Reach { + Straight { + direction: [f64; 2], + }, + Round { + centre: [f64; 2], + radius: f64, + angle: f64, + turn: f64, + }, +} + +struct EndInfo { + end: CurveEnd, + point: [f64; 2], + /// The index in `pieces` of the piece that the end is on. + piece: usize, + /// The length of that piece. + piece_length: f64, + reach: Reach, +} + +fn distance(a: [f64; 2], b: [f64; 2]) -> f64 { + Vec2::from(a).distance(Vec2::from(b)) +} + +fn shape_length(shape: Shape) -> f64 { + match shape { + Shape::Line(line) => line.length(), + Shape::Arc(arc) => arc.radius * arc.sweep(), + } +} + +/// The pieces of the curves that Geometry Cleanup reads. A curve of any +/// other kind gives none. +fn pieces_of(curves: &[Curve]) -> Vec { + let mut pieces = Vec::new(); + for (curve, item) in curves.iter().enumerate() { + match item { + Curve::Line(line) => pieces.push(Piece { + curve, + shape: Shape::Line(*line), + }), + Curve::Arc(arc) => pieces.push(Piece { + curve, + shape: Shape::Arc(*arc), + }), + Curve::Polyline(polyline) => { + let n = polyline.vertices.len(); + let count = if polyline.closed { + n + } else { + n.saturating_sub(1) + }; + for index in 0..count { + let from = polyline.vertices[index]; + let to = polyline.vertices[(index + 1) % n]; + let shape = match BulgeArc::from_bulge(from.position, to.position, from.bulge) { + Some(arc) => { + let (start_angle, end_angle) = if arc.sweep > 0.0 { + (arc.start_angle, arc.end_angle) + } else { + (arc.end_angle, arc.start_angle) + }; + Shape::Arc(Arc { + centre: arc.center, + radius: arc.radius, + start_angle, + end_angle, + }) + } + None => Shape::Line(Line { + start: from.position, + end: to.position, + }), + }; + pieces.push(Piece { curve, shape }); + } + } + _ => {} + } + } + pieces +} + +/// The two ends of each open curve. +fn ends_of(curves: &[Curve], pieces: &[Piece]) -> Vec { + let mut ends = Vec::new(); + let mut first_piece = HashMap::new(); + let mut last_piece = HashMap::new(); + for (k, piece) in pieces.iter().enumerate() { + first_piece.entry(piece.curve).or_insert(k); + last_piece.insert(piece.curve, k); + } + for (curve, item) in curves.iter().enumerate() { + let (Some(&first), Some(&last)) = (first_piece.get(&curve), last_piece.get(&curve)) else { + continue; + }; + // Whether the curve runs along its pieces the way they are stored + // (a polyline arc piece is stored counter-clockwise), and the bulge + // sign of a polyline's end segments. + let (open, first_turn, last_turn) = match item { + Curve::Line(_) | Curve::Arc(_) => (true, 1.0, 1.0), + Curve::Polyline(polyline) => { + let n = polyline.vertices.len(); + ( + !polyline.closed && n >= 2, + polyline.vertices[0].bulge.signum(), + polyline.vertices[n.saturating_sub(2)].bulge.signum(), + ) + } + _ => (false, 1.0, 1.0), + }; + if !open { + continue; + } + for at_start in [true, false] { + let k = if at_start { first } else { last }; + let piece = &pieces[k]; + let turn = if at_start { first_turn } else { last_turn }; + let (point, reach) = match piece.shape { + Shape::Line(line) => { + let (point, back) = if at_start { + (line.start, line.end) + } else { + (line.end, line.start) + }; + let length = distance(point, back); + if length <= 0.0 { + continue; + } + let direction = [(point[0] - back[0]) / length, (point[1] - back[1]) / length]; + (point, Reach::Straight { direction }) + } + Shape::Arc(arc) => { + // The curve runs counter-clockwise along the piece for a + // LINE's ARC and for a positive bulge. + let forward = turn > 0.0; + // The end of the curve is the piece's end angle when the + // curve runs forward and leaves at its end. + let at_piece_end = forward != at_start; + let angle = if at_piece_end { + arc.end_angle + } else { + arc.start_angle + }; + let point = [ + arc.centre[0] + arc.radius * angle.cos(), + arc.centre[1] + arc.radius * angle.sin(), + ]; + let turn = if at_piece_end { 1.0 } else { -1.0 }; + ( + point, + Reach::Round { + centre: arc.centre, + radius: arc.radius, + angle, + turn, + }, + ) + } + }; + ends.push(EndInfo { + end: CurveEnd { curve, at_start }, + point, + piece: k, + piece_length: shape_length(piece.shape), + reach, + }); + } + } + ends +} + +/// The continuation of an end, `length` long. +fn extension(end: &EndInfo, length: f64) -> Curve { + match end.reach { + Reach::Straight { direction } => Curve::Line(Line { + start: end.point, + end: [ + end.point[0] + direction[0] * length, + end.point[1] + direction[1] * length, + ], + }), + Reach::Round { + centre, + radius, + angle, + turn, + } => { + let sweep = (length / radius).min(PI); + let (start_angle, end_angle) = if turn > 0.0 { + (angle, angle + sweep) + } else { + (angle - sweep, angle) + }; + Curve::Arc(Arc { + centre, + radius, + start_angle: normalize_angle(start_angle), + end_angle: normalize_angle(end_angle), + }) + } + } +} + +/// How far `point` is from the end, along the end's line or circle; ahead +/// of the end when `ahead`, back along the curve otherwise. +fn along(end: &EndInfo, point: [f64; 2], ahead: bool) -> f64 { + match end.reach { + Reach::Straight { direction } => { + let d = + (point[0] - end.point[0]) * direction[0] + (point[1] - end.point[1]) * direction[1]; + if ahead { + d + } else { + -d + } + } + Reach::Round { + centre, + radius, + angle, + turn, + } => { + let to = (point[1] - centre[1]).atan2(point[0] - centre[0]); + let sign = if ahead { turn } else { -turn }; + radius * (sign * (to - angle)).rem_euclid(TAU) + } + } +} + +type Bounds = ([f64; 2], [f64; 2]); + +fn shape_bounds(shape: Shape) -> Option { + analytic_curve_bounds(&[shape.curve()]) +} + +/// The pieces near each place, by grid cell. +struct Grid { + size: f64, + cells: HashMap<(i64, i64), Vec>, + /// Pieces that cover too many cells to list in each. + everywhere: Vec, +} + +impl Grid { + const MAX_CELLS: i64 = 4096; + + fn cell(&self, p: [f64; 2]) -> (i64, i64) { + ( + (p[0] / self.size).floor() as i64, + (p[1] / self.size).floor() as i64, + ) + } + + fn new(pieces: &[Piece], size: f64, reach: f64) -> Self { + let mut grid = Grid { + size, + cells: HashMap::new(), + everywhere: Vec::new(), + }; + for (k, piece) in pieces.iter().enumerate() { + let Some((min, max)) = shape_bounds(piece.shape) else { + continue; + }; + let low = grid.cell([min[0] - reach, min[1] - reach]); + let high = grid.cell([max[0] + reach, max[1] + reach]); + let count = (high.0 - low.0 + 1).saturating_mul(high.1 - low.1 + 1); + if !(0..=Self::MAX_CELLS).contains(&count) { + grid.everywhere.push(k); + continue; + } + for x in low.0..=high.0 { + for y in low.1..=high.1 { + grid.cells.entry((x, y)).or_default().push(k); + } + } + } + grid + } + + /// The pieces whose bounds, widened by the reach, hold `p`. + fn near(&self, p: [f64; 2]) -> impl Iterator + '_ { + self.cells + .get(&self.cell(p)) + .into_iter() + .flatten() + .chain(&self.everywhere) + .copied() + } +} + +/// The tolerance that Geometry Cleanup proposes for a drawing: 1% of the +/// mean length of its lines and polyline segments (of all its pieces when +/// it has neither), and not less than 0.0001. +pub fn proposed_tolerance(curves: &[Curve]) -> f64 { + const MINIMUM: f64 = 0.0001; + let pieces = pieces_of(curves); + let straight: Vec = pieces + .iter() + .filter(|piece| { + matches!(piece.shape, Shape::Line(_)) + || matches!(curves[piece.curve], Curve::Polyline(_)) + }) + .map(|piece| shape_length(piece.shape)) + .collect(); + let lengths: Vec = if straight.is_empty() { + pieces + .iter() + .map(|piece| shape_length(piece.shape)) + .collect() + } else { + straight + }; + let lengths: Vec = lengths.into_iter().filter(|l| l.is_finite()).collect(); + if lengths.is_empty() { + return MINIMUM; + } + let mean = lengths.iter().sum::() / lengths.len() as f64; + (mean * 0.01).max(MINIMUM) +} + +/// The point where two straight ends' lines cross, when it is ahead of both +/// ends and at most `tolerance` from each. +fn corner(a: &EndInfo, b: &EndInfo, tolerance: f64, weld: f64) -> Option<[f64; 2]> { + let (Reach::Straight { direction: u }, Reach::Straight { direction: v }) = (a.reach, b.reach) + else { + return None; + }; + let cross = u[0] * v[1] - u[1] * v[0]; + if cross.abs() < 1e-9 { + return None; + } + let w = [b.point[0] - a.point[0], b.point[1] - a.point[1]]; + let s = (w[0] * v[1] - w[1] * v[0]) / cross; + let t = (w[0] * u[1] - w[1] * u[0]) / cross; + let reach = -weld..=tolerance; + (reach.contains(&s) && reach.contains(&t)) + .then(|| [a.point[0] + u[0] * s, a.point[1] + u[1] * s]) +} + +/// The ends of `curves` that almost meet other geometry: each within +/// `tolerance`, and more than `weld` away (closer counts as meeting). +/// +/// Lines, arcs and polylines are read; any other curve is ignored. A closed +/// polyline has no ends but is still geometry that ends can meet. The +/// errors come in the order of their ends. +pub fn end_errors(curves: &[Curve], tolerance: f64, weld: Tolerance) -> Vec { + let weld = weld.linear(); + if !tolerance.is_finite() || tolerance <= weld { + return Vec::new(); + } + let pieces = pieces_of(curves); + let ends = ends_of(curves, &pieces); + let mean = if pieces.is_empty() { + tolerance + } else { + pieces.iter().map(|p| shape_length(p.shape)).sum::() / pieces.len() as f64 + }; + let size = if mean.is_finite() { + mean.max(2.0 * tolerance) + } else { + 2.0 * tolerance + }; + let grid = Grid::new(&pieces, size, tolerance); + + // An end is loose when no other piece passes within the weld of it. + let loose: Vec = ends + .iter() + .map(|end| { + !grid.near(end.point).any(|k| { + k != end.piece + && super::containment::distance_to(&pieces[k].shape.curve(), end.point) <= weld + }) + }) + .collect(); + + let mut candidates = Vec::new(); + let mut by_cell: HashMap<(i64, i64), Vec> = HashMap::new(); + let cell = |p: [f64; 2]| { + ( + (p[0] / tolerance).floor() as i64, + (p[1] / tolerance).floor() as i64, + ) + }; + for (e, end) in ends.iter().enumerate() { + if loose[e] { + by_cell.entry(cell(end.point)).or_default().push(e); + } + } + + for (e, end) in ends.iter().enumerate() { + if !loose[e] { + continue; + } + // Gaps: another loose end close by, of another curve or the other + // end of the same polyline. + let (cx, cy) = cell(end.point); + for x in cx - 1..=cx + 1 { + for y in cy - 1..=cy + 1 { + for &f in by_cell.get(&(x, y)).into_iter().flatten() { + let other = &ends[f]; + let same_curve = other.end.curve == end.end.curve; + if f <= e + || (same_curve && !matches!(curves[end.end.curve], Curve::Polyline(_))) + { + continue; + } + let gap = distance(end.point, other.point); + if gap > weld && gap <= tolerance { + candidates.push(EndError { + kind: EndErrorKind::Gap, + end: end.end, + location: end.point, + target: other.point, + other: Some(other.end), + corner: corner(end, other, tolerance, weld), + deviation: gap, + }); + } + } + } + } + + let own = &pieces[end.piece]; + let reach = extension(end, tolerance); + let mut seen = HashSet::new(); + for k in grid.near(end.point) { + if k == end.piece || !seen.insert(k) { + continue; + } + let target = pieces[k].shape.curve(); + // Undershoot: the end's continuation reaches the piece. + for crossing in intersect(&reach, &target, Tolerance::new(weld)) { + let d = along(end, crossing.point, true); + if d > weld && d <= tolerance { + candidates.push(EndError { + kind: EndErrorKind::Undershoot, + end: end.end, + location: end.point, + target: crossing.point, + other: None, + corner: None, + deviation: d, + }); + } + } + // Overshoot: the end's own piece crosses the piece just before + // the end. A crossing at the far end of the end's piece (where a + // polyline goes on, or a short line is attached) is not one. + for crossing in intersect(&own.shape.curve(), &target, Tolerance::new(weld)) { + let d = along(end, crossing.point, false); + if d > weld && d <= tolerance && d < end.piece_length - weld { + candidates.push(EndError { + kind: EndErrorKind::Overshoot, + end: end.end, + location: end.point, + target: crossing.point, + other: None, + corner: None, + deviation: d, + }); + } + } + } + } + + // Nearest first; at equal distance a gap (end to end) before the + // others. Each end goes to one error only. + candidates.sort_by(|a, b| { + a.deviation + .total_cmp(&b.deviation) + .then(a.kind.cmp(&b.kind)) + .then(a.end.cmp(&b.end)) + }); + let mut used = HashSet::new(); + let mut errors: Vec = candidates + .into_iter() + .filter(|error| { + if used.contains(&error.end) || error.other.is_some_and(|other| used.contains(&other)) { + return false; + } + used.insert(error.end); + if let Some(other) = error.other { + used.insert(other); + } + true + }) + .collect(); + errors.sort_by_key(|error| error.end); + errors +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::geom2d::{Polyline, PolylineVertex}; + + fn line(start: [f64; 2], end: [f64; 2]) -> Curve { + Curve::Line(Line { start, end }) + } + + fn polyline(points: &[[f64; 2]], closed: bool) -> Curve { + Curve::Polyline(Polyline { + vertices: points + .iter() + .map(|&position| PolylineVertex { + position, + bulge: 0.0, + }) + .collect(), + closed, + }) + } + + fn scan(curves: &[Curve], tolerance: f64) -> Vec { + end_errors(curves, tolerance, Tolerance::new(1e-9)) + } + + fn near(a: [f64; 2], b: [f64; 2]) -> bool { + distance(a, b) < 1e-9 + } + + fn end(curve: usize, at_start: bool) -> CurveEnd { + CurveEnd { curve, at_start } + } + + #[test] + fn ends_that_meet_or_are_far_apart_are_not_errors() { + let meeting = [ + line([0.0, 0.0], [10.0, 0.0]), + line([10.0, 0.0], [10.0, 10.0]), + ]; + assert!(scan(&meeting, 0.5).is_empty()); + let far = [ + line([0.0, 0.0], [10.0, 0.0]), + line([11.0, 0.0], [20.0, 0.0]), + ]; + assert!(scan(&far, 0.5).is_empty()); + } + + #[test] + fn a_gap_between_two_ends_targets_the_other_end_and_its_corner() { + let curves = [ + line([0.0, 0.0], [10.0, 0.0]), + line([10.2, 0.1], [10.2, 10.0]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + let gap = errors[0]; + assert_eq!(gap.kind, EndErrorKind::Gap); + assert_eq!(gap.end, end(0, false)); + assert_eq!(gap.other, Some(end(1, true))); + assert!(near(gap.location, [10.0, 0.0])); + assert!(near(gap.target, [10.2, 0.1])); + assert!(near(gap.corner.expect("a corner"), [10.2, 0.0])); + assert!((gap.deviation - 0.05f64.sqrt()).abs() < 1e-12); + } + + #[test] + fn a_gap_between_collinear_ends_has_no_corner() { + let curves = [ + line([0.0, 0.0], [10.0, 0.0]), + line([10.3, 0.0], [20.0, 0.0]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Gap); + assert_eq!(errors[0].corner, None); + } + + #[test] + fn an_end_short_of_a_line_is_an_undershoot() { + let curves = [ + line([0.0, 0.0], [9.7, 0.0]), + line([10.0, -5.0], [10.0, 5.0]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + let undershoot = errors[0]; + assert_eq!(undershoot.kind, EndErrorKind::Undershoot); + assert_eq!(undershoot.end, end(0, false)); + assert!(near(undershoot.target, [10.0, 0.0])); + assert!((undershoot.deviation - 0.3).abs() < 1e-9); + } + + #[test] + fn an_end_past_a_line_is_an_overshoot() { + let curves = [ + line([10.4, 0.0], [0.0, 0.0]), + line([10.0, -5.0], [10.0, 5.0]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + let overshoot = errors[0]; + assert_eq!(overshoot.kind, EndErrorKind::Overshoot); + assert_eq!(overshoot.end, end(0, true)); + assert!(near(overshoot.target, [10.0, 0.0])); + assert!((overshoot.deviation - 0.4).abs() < 1e-9); + } + + #[test] + fn a_short_line_attached_at_its_other_end_is_not_an_overshoot() { + let curves = [ + line([10.0, 0.0], [10.3, 0.0]), + line([10.0, -5.0], [10.0, 5.0]), + ]; + assert!(scan(&curves, 0.5).is_empty()); + } + + #[test] + fn an_arc_end_reaches_along_its_circle() { + // A quarter arc of radius 10 about the origin that stops 0.03 rad + // short of the y axis, where a line runs. + let stop = std::f64::consts::FRAC_PI_2 - 0.03; + let arc = Curve::Arc(Arc { + centre: [0.0, 0.0], + radius: 10.0, + start_angle: 0.0, + end_angle: stop, + }); + let curves = [arc, line([0.0, 0.0], [0.0, 20.0])]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Undershoot); + assert_eq!(errors[0].end, end(0, false)); + assert!(near(errors[0].target, [0.0, 10.0])); + assert!((errors[0].deviation - 0.3).abs() < 1e-9); + } + + #[test] + fn an_almost_closed_polyline_has_a_gap_between_its_own_ends() { + let outline = polyline( + &[ + [0.0, 0.0], + [10.0, 0.0], + [10.0, 10.0], + [0.0, 10.0], + [0.0, 0.2], + ], + false, + ); + let errors = scan(&[outline], 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Gap); + assert_eq!(errors[0].end, end(0, true)); + assert_eq!(errors[0].other, Some(end(0, false))); + } + + #[test] + fn a_line_shorter_than_the_tolerance_has_no_gap_to_itself() { + assert!(scan(&[line([0.0, 0.0], [0.2, 0.0])], 0.5).is_empty()); + } + + #[test] + fn a_closed_polyline_has_no_ends_but_ends_can_fall_short_of_it() { + let square = polyline(&[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]], true); + assert!(scan(std::slice::from_ref(&square), 0.5).is_empty()); + let errors = scan(&[square, line([5.0, 20.0], [5.0, 10.2])], 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Undershoot); + assert!(near(errors[0].target, [5.0, 10.0])); + } + + #[test] + fn each_end_is_reported_once_as_its_nearest_error() { + // The end of the first line is 0.1 short of the vertical line and + // 0.4 from the end of the third line: the undershoot wins, and the + // third line's end, left without a partner, is not reported. + let curves = [ + line([0.0, 0.0], [9.9, 0.0]), + line([10.0, -5.0], [10.0, 5.0]), + line([9.9, 0.4], [9.9, 8.0]), + ]; + let errors = scan(&curves, 0.5); + let kinds: Vec<_> = errors.iter().map(|e| (e.kind, e.end)).collect(); + assert!( + kinds.contains(&(EndErrorKind::Undershoot, end(0, false))), + "{errors:?}" + ); + assert!( + !errors.iter().any(|e| e.kind == EndErrorKind::Gap), + "{errors:?}" + ); + } + + #[test] + fn a_polyline_end_reaches_along_its_last_segment() { + let path = polyline(&[[0.0, 0.0], [5.0, 0.0], [5.0, 4.8]], false); + let errors = scan(&[path, line([0.0, 5.0], [10.0, 5.0])], 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Undershoot); + assert_eq!(errors[0].end, end(0, false)); + assert!(near(errors[0].target, [5.0, 5.0])); + } + + #[test] + fn the_proposed_tolerance_is_a_hundredth_of_the_mean_length() { + let curves = [line([0.0, 0.0], [10.0, 0.0]), line([0.0, 0.0], [0.0, 30.0])]; + assert!((proposed_tolerance(&curves) - 0.2).abs() < 1e-12); + assert_eq!(proposed_tolerance(&[]), 0.0001); + assert_eq!( + proposed_tolerance(&[line([0.0, 0.0], [0.001, 0.0])]), + 0.0001 + ); + } + + fn arc(centre: [f64; 2], radius: f64, start_angle: f64, end_angle: f64) -> Curve { + Curve::Arc(Arc { + centre, + radius, + start_angle, + end_angle, + }) + } + + #[test] + fn an_oblique_corner_is_where_both_lines_cross() { + // Both lines run towards (6, 5): the first stops 0.2 short of it + // along (0.6, 0.8), the second 0.3 short along (-0.8, 0.6). + let curves = [ + line([-0.12, -3.16], [5.88, 4.84]), + line([14.24, -1.18], [6.24, 4.82]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Gap); + assert_eq!(errors[0].other, Some(end(1, false))); + let corner = errors[0].corner.expect("a corner"); + assert!(distance(corner, [6.0, 5.0]) < 1e-9, "{corner:?}"); + assert!((errors[0].deviation - 0.36f64.hypot(0.02)).abs() < 1e-9); + } + + #[test] + fn a_corner_farther_than_the_tolerance_from_an_end_is_not_offered() { + // The lines cross 0.525 ahead of the first end. + let curves = [ + line([-10.0, 0.0], [0.0, 0.0]), + line([-5.7, 8.3], [0.3, 0.3]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Gap); + assert_eq!(errors[0].corner, None); + } + + #[test] + fn both_ends_of_an_arc_reach_along_its_circle() { + let centre = [3.0, -2.0]; + let quarter = std::f64::consts::FRAC_PI_2; + let curves = [ + arc(centre, 10.0, 0.03, quarter - 0.03), + line(centre, [3.0, 20.0]), + line(centre, [20.0, -2.0]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors.iter().all(|e| e.kind == EndErrorKind::Undershoot)); + let at = |at_start| { + errors + .iter() + .find(|e| e.end == end(0, at_start)) + .expect("both ends") + }; + let start = [3.0 + 10.0 * 0.03f64.cos(), -2.0 + 10.0 * 0.03f64.sin()]; + assert!(near(at(true).location, start), "{errors:?}"); + assert!(near(at(true).target, [13.0, -2.0]), "{errors:?}"); + assert!(near(at(false).target, [3.0, 8.0]), "{errors:?}"); + assert!(errors.iter().all(|e| (e.deviation - 0.3).abs() < 1e-9)); + } + + #[test] + fn an_arc_end_past_a_line_is_an_overshoot() { + let curves = [ + arc([3.0, -2.0], 10.0, 0.0, std::f64::consts::FRAC_PI_2 + 0.03), + line([3.0, 0.0], [3.0, 20.0]), + ]; + let errors = scan(&curves, 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Overshoot); + assert_eq!(errors[0].end, end(0, false)); + assert!(near(errors[0].target, [3.0, 8.0]), "{errors:?}"); + assert!((errors[0].deviation - 0.3).abs() < 1e-9); + } + + #[test] + fn a_small_arc_reaches_the_tolerance_along_its_circle() { + // Radius 0.5: the 0.3 shortfall is 0.6 rad of the circle. + let curves = [ + arc([2.0, 1.0], 0.5, 0.0, std::f64::consts::FRAC_PI_2 - 0.6), + line([2.0, 0.6], [2.0, 5.0]), + ]; + let errors = scan(&curves, 0.4); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Undershoot); + assert!(near(errors[0].target, [2.0, 1.5]), "{errors:?}"); + assert!((errors[0].deviation - 0.3).abs() < 1e-9); + } + + #[test] + fn a_clockwise_polyline_arc_reaches_along_its_circle() { + // From the top of a circle about (3, -2) clockwise to 0.03 rad + // above its right side. + let to = [3.0 + 10.0 * 0.03f64.cos(), -2.0 + 10.0 * 0.03f64.sin()]; + let sweep = -(std::f64::consts::FRAC_PI_2 - 0.03); + let path = Curve::Polyline(Polyline { + vertices: vec![ + PolylineVertex { + position: [3.0, 8.0], + bulge: (sweep / 4.0).tan(), + }, + PolylineVertex { + position: to, + bulge: 0.0, + }, + ], + closed: false, + }); + let errors = scan(&[path, line([8.0, -2.0], [20.0, -2.0])], 0.5); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Undershoot); + assert_eq!(errors[0].end, end(0, false)); + assert!(near(errors[0].target, [13.0, -2.0]), "{errors:?}"); + assert!((errors[0].deviation - 0.3).abs() < 1e-9); + } + + #[test] + fn a_large_tolerance_reaches_as_far_as_it_says() { + let gap = [ + line([-50.0, 1.0], [1.0, 1.0]), + line([4.0, 3.0], [4.0, 50.0]), + ]; + let errors = scan(&gap, 5.0); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Gap); + assert!(near(errors[0].corner.expect("a corner"), [4.0, 1.0])); + let under = [ + line([-50.0, 0.0], [0.0, 0.0]), + line([4.0, -50.0], [4.0, 50.0]), + ]; + let errors = scan(&under, 5.0); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Undershoot); + assert!((errors[0].deviation - 4.0).abs() < 1e-9); + } + + #[test] + fn a_gap_is_found_across_the_edge_of_a_search_cell() { + // With a tolerance of 1, the ends at 0.9 and 1.1 are in cells next + // to each other: along X and along Y, with the lower or the upper + // cell scanned first. + let flip = |p: [f64; 2]| [p[1], p[0]]; + let close = [([-10.0, 0.0], [0.9, 0.0]), ([1.1, 0.1], [1.1, 10.0])]; + for swap in [false, true] { + for reverse in [false, true] { + let mut curves: Vec = close + .iter() + .map(|&(a, b)| { + if swap { + line(flip(a), flip(b)) + } else { + line(a, b) + } + }) + .collect(); + if reverse { + curves.reverse(); + } + let errors = scan(&curves, 1.0); + assert_eq!(errors.len(), 1, "swap {swap} reverse {reverse}: {errors:?}"); + assert_eq!(errors[0].kind, EndErrorKind::Gap); + } + } + // Ends in cells next to each other but more than the tolerance + // apart are not a gap. + let apart = [ + line([-10.0, 0.0], [0.9, 0.0]), + line([1.95, 0.5], [1.95, 10.0]), + ]; + assert!(scan(&apart, 1.0).is_empty()); + } + + #[test] + fn the_proposed_tolerance_leaves_out_arcs_unless_there_are_only_arcs() { + let quarter = arc([0.0, 0.0], 10.0, 0.0, std::f64::consts::FRAC_PI_2); + let expected = 0.01 * 5.0 * std::f64::consts::PI; + assert!((proposed_tolerance(std::slice::from_ref(&quarter)) - expected).abs() < 1e-12); + let mixed = [quarter, line([0.0, 0.0], [10.0, 0.0])]; + assert!((proposed_tolerance(&mixed) - 0.1).abs() < 1e-12); + } + + #[test] + fn no_tolerance_above_the_weld_finds_nothing() { + let curves = [ + line([0.0, 0.0], [10.0, 0.0]), + line([10.2, 0.0], [20.0, 0.0]), + ]; + assert!(end_errors(&curves, 1e-9, Tolerance::new(1e-9)).is_empty()); + assert!(end_errors(&curves, f64::NAN, Tolerance::new(1e-9)).is_empty()); + assert!(end_errors(&curves, f64::INFINITY, Tolerance::new(1e-9)).is_empty()); + } +} diff --git a/crates/ocs_geom/src/geom2d/mod.rs b/crates/ocs_geom/src/geom2d/mod.rs index 7e69ee63bf..427f8cacef 100644 --- a/crates/ocs_geom/src/geom2d/mod.rs +++ b/crates/ocs_geom/src/geom2d/mod.rs @@ -16,6 +16,7 @@ pub mod band; mod boundary_recovery; pub mod clip; pub mod centerline; +pub mod cleanup; pub mod containment; pub mod construct; pub mod constrained; diff --git a/locales/ar-SA/opencadstudio.ftl b/locales/ar-SA/opencadstudio.ftl index 6d6a3b1315..029233dccf 100644 --- a/locales/ar-SA/opencadstudio.ftl +++ b/locales/ar-SA/opencadstudio.ftl @@ -6728,6 +6728,22 @@ manage = .find-non-purgeable-items = البحث عن العناصر غير القابلة للتنظيف + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = تجاهل خاصية الكائن .load-partial-cui = تحميل CUI جزئي .maintain-associative-objects = الحفاظ على الكائنات الترابطية diff --git a/locales/bg-BG/opencadstudio.ftl b/locales/bg-BG/opencadstudio.ftl index cc9ebd1c35..e5bca1f163 100644 --- a/locales/bg-BG/opencadstudio.ftl +++ b/locales/bg-BG/opencadstudio.ftl @@ -6716,6 +6716,22 @@ manage = .find-non-purgeable-items = Намери непочистваеми елементи + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Игнориране на свойство на обект .load-partial-cui = Зареди частичен CUI .maintain-associative-objects = Запазване на асоциативните обекти diff --git a/locales/cs-CZ/opencadstudio.ftl b/locales/cs-CZ/opencadstudio.ftl index 99a2fd5dc2..1dc862f913 100644 --- a/locales/cs-CZ/opencadstudio.ftl +++ b/locales/cs-CZ/opencadstudio.ftl @@ -6718,6 +6718,22 @@ manage = .find-non-purgeable-items = Najít nevyčistitelné položky + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ignorovat vlastnost objektu .load-partial-cui = Načíst částečné CUI .maintain-associative-objects = Zachovat asociativní objekty diff --git a/locales/de-DE/opencadstudio.ftl b/locales/de-DE/opencadstudio.ftl index a3c82fa605..603d09cab9 100644 --- a/locales/de-DE/opencadstudio.ftl +++ b/locales/de-DE/opencadstudio.ftl @@ -6714,6 +6714,22 @@ manage = .find-non-purgeable-items = Nicht- finden- Spülbare Gegenstände + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Objekteigenschaft ignorieren .load-partial-cui = Teillast CUI .maintain-associative-objects = Assoziative Objekte beibehalten diff --git a/locales/el-GR/opencadstudio.ftl b/locales/el-GR/opencadstudio.ftl index 041e4b9828..f277652767 100644 --- a/locales/el-GR/opencadstudio.ftl +++ b/locales/el-GR/opencadstudio.ftl @@ -6716,6 +6716,22 @@ manage = .find-non-purgeable-items = Εύρεση μη εκκαθαρίσιμων στοιχείων + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Παράβλεψη ιδιότητας αντικειμένου .load-partial-cui = Φόρτωση μερικού CUI .maintain-associative-objects = Διατήρηση συσχετιστικών αντικειμένων diff --git a/locales/en-US/opencadstudio.ftl b/locales/en-US/opencadstudio.ftl index 285725b18d..53c5c1d0b7 100644 --- a/locales/en-US/opencadstudio.ftl +++ b/locales/en-US/opencadstudio.ftl @@ -6717,6 +6717,22 @@ manage = .find-non-purgeable-items = Find Non- Purgeable Items + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ignore object property .load-partial-cui = Load Partial CUI .maintain-associative-objects = Maintain associative objects diff --git a/locales/es-ES/opencadstudio.ftl b/locales/es-ES/opencadstudio.ftl index 09b051d622..5e5e8ddc09 100644 --- a/locales/es-ES/opencadstudio.ftl +++ b/locales/es-ES/opencadstudio.ftl @@ -6716,6 +6716,22 @@ manage = .find-non-purgeable-items = Buscar elementos no limpiables + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ignorar propiedad de objeto .load-partial-cui = Cargar CUI parcial .maintain-associative-objects = Mantener objetos asociativos diff --git a/locales/fi-FI/opencadstudio.ftl b/locales/fi-FI/opencadstudio.ftl index 54f5bd4849..db881b026b 100644 --- a/locales/fi-FI/opencadstudio.ftl +++ b/locales/fi-FI/opencadstudio.ftl @@ -6715,6 +6715,22 @@ manage = .find-non-purgeable-items = Etsi ei- Puhdistettavat tuotteet + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ohita objektin ominaisuus .load-partial-cui = Kuorma osittainen CUI .maintain-associative-objects = Säilytä assosiatiiviset objektit diff --git a/locales/fr-FR/opencadstudio.ftl b/locales/fr-FR/opencadstudio.ftl index fb82594c00..5ce1fa037d 100644 --- a/locales/fr-FR/opencadstudio.ftl +++ b/locales/fr-FR/opencadstudio.ftl @@ -6717,6 +6717,22 @@ manage = .find-non-purgeable-items = Trouver des éléments non purgeables + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ignorer la propriété d'objet .load-partial-cui = Charge partielle CUI .maintain-associative-objects = Conserver les objets associatifs diff --git a/locales/hi-IN/opencadstudio.ftl b/locales/hi-IN/opencadstudio.ftl index 0ea4c84c47..f3d10b586d 100644 --- a/locales/hi-IN/opencadstudio.ftl +++ b/locales/hi-IN/opencadstudio.ftl @@ -6704,6 +6704,22 @@ manage = .find-non-purgeable-items = गैर खोजें प्रशंसनीय आइटम + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = ऑब्जेक्ट गुण अनदेखा करें .load-partial-cui = लोड आंशिक CUI .maintain-associative-objects = सहयोगी ऑब्जेक्ट बनाए रखें diff --git a/locales/hu-HU/opencadstudio.ftl b/locales/hu-HU/opencadstudio.ftl index 7b589653f3..ad12fb4523 100644 --- a/locales/hu-HU/opencadstudio.ftl +++ b/locales/hu-HU/opencadstudio.ftl @@ -6697,6 +6697,22 @@ manage = .edit-aliases = Rövidítések szerkesztése .export = Exportálás .find-non-purgeable-items = Nem tisztítható elemek keresése + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Objektumtulajdonság figyelmen kívül hagyása .load-partial-cui = Részleges CUI betöltése .maintain-associative-objects = Asszociatív objektumok megtartása diff --git a/locales/it-IT/opencadstudio.ftl b/locales/it-IT/opencadstudio.ftl index eb0fe6bfe6..d51f2c0051 100644 --- a/locales/it-IT/opencadstudio.ftl +++ b/locales/it-IT/opencadstudio.ftl @@ -6715,6 +6715,22 @@ manage = .find-non-purgeable-items = Trova elementi non eliminabili + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ignora proprietà oggetto .load-partial-cui = Carica CUI parziale .maintain-associative-objects = Mantieni oggetti associativi diff --git a/locales/ja-JP/opencadstudio.ftl b/locales/ja-JP/opencadstudio.ftl index e3ec6561ea..d74f2c78cb 100644 --- a/locales/ja-JP/opencadstudio.ftl +++ b/locales/ja-JP/opencadstudio.ftl @@ -6704,6 +6704,22 @@ manage = .find-non-purgeable-items = パージ不可項目を 検索 + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = 無視するオブジェクト プロパティ .load-partial-cui = 部分 CUI を読み込む .maintain-associative-objects = 自動調整オブジェクトを維持 diff --git a/locales/ko-KR/opencadstudio.ftl b/locales/ko-KR/opencadstudio.ftl index 4e596cb18a..4f996b09d0 100644 --- a/locales/ko-KR/opencadstudio.ftl +++ b/locales/ko-KR/opencadstudio.ftl @@ -6715,6 +6715,22 @@ manage = .find-non-purgeable-items = 비 찾기 제거 가능한 항목 + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = 무시할 객체 특성 .load-partial-cui = 부분 CUI 로드 .maintain-associative-objects = 연관 객체 유지 diff --git a/locales/lo-LA/opencadstudio.ftl b/locales/lo-LA/opencadstudio.ftl index f08b6322ef..49749def9a 100644 --- a/locales/lo-LA/opencadstudio.ftl +++ b/locales/lo-LA/opencadstudio.ftl @@ -6717,6 +6717,22 @@ manage = .find-non-purgeable-items = ຊອກຫາລາຍການທີ່ ບໍ່ສາມາດລຶບອອກໄດ້ + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = ບໍ່ສົນໃຈຄຸນສົມບັດຂອງວັດຖຸ .load-partial-cui = ໂຫຼດ CUI ບາງສ່ວນ .maintain-associative-objects = ຮັກສາວັດຖຸທີ່ເຊື່ອມໂຍງ diff --git a/locales/nl-NL/opencadstudio.ftl b/locales/nl-NL/opencadstudio.ftl index d691c1ae77..62bd5508c5 100644 --- a/locales/nl-NL/opencadstudio.ftl +++ b/locales/nl-NL/opencadstudio.ftl @@ -6714,6 +6714,22 @@ manage = .find-non-purgeable-items = Zoek niet- Zuiverbare items + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Objecteigenschap negeren .load-partial-cui = Gedeeltelijke belasting CUI .maintain-associative-objects = Associatieve objecten behouden diff --git a/locales/pl-PL/opencadstudio.ftl b/locales/pl-PL/opencadstudio.ftl index a5ee7982d1..de62a4b677 100644 --- a/locales/pl-PL/opencadstudio.ftl +++ b/locales/pl-PL/opencadstudio.ftl @@ -6715,6 +6715,22 @@ manage = .find-non-purgeable-items = Znajdź nie- Elementy do oczyszczenia + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ignoruj właściwość obiektu .load-partial-cui = Załaduj częściowo CUI .maintain-associative-objects = Zachowaj obiekty skojarzone diff --git a/locales/pt-BR/opencadstudio.ftl b/locales/pt-BR/opencadstudio.ftl index 43781a36d0..b711815671 100644 --- a/locales/pt-BR/opencadstudio.ftl +++ b/locales/pt-BR/opencadstudio.ftl @@ -6716,6 +6716,22 @@ manage = .find-non-purgeable-items = Localizar itens não elimináveis + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Ignorar propriedade do objeto .load-partial-cui = Carregar CUI parcial .maintain-associative-objects = Manter objetos associativos diff --git a/locales/ru-RU/opencadstudio.ftl b/locales/ru-RU/opencadstudio.ftl index 95ad7625e0..045f826a21 100644 --- a/locales/ru-RU/opencadstudio.ftl +++ b/locales/ru-RU/opencadstudio.ftl @@ -6717,6 +6717,22 @@ manage = .find-non-purgeable-items = Найти не- Чистоплотные предметы + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Игнорировать свойство объекта .load-partial-cui = Загрузка Частично CUI .maintain-associative-objects = Сохранять ассоциативные объекты diff --git a/locales/tr-TR/opencadstudio.ftl b/locales/tr-TR/opencadstudio.ftl index 0854dab5fd..79533a914d 100644 --- a/locales/tr-TR/opencadstudio.ftl +++ b/locales/tr-TR/opencadstudio.ftl @@ -6655,6 +6655,22 @@ manage = .export = Dışa Aktar .find-non-purgeable-items = Temizlenemeyen Öğeleri Bul + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Nesne özelliğini yoksay .load-partial-cui = Kısmi CUI Yükle .maintain-associative-objects = İlişkisel nesneleri koru diff --git a/locales/uz-UZ/opencadstudio.ftl b/locales/uz-UZ/opencadstudio.ftl index 5b6eb814ce..cfd2a90a7a 100644 --- a/locales/uz-UZ/opencadstudio.ftl +++ b/locales/uz-UZ/opencadstudio.ftl @@ -6717,6 +6717,22 @@ manage = .find-non-purgeable-items = Tozalanmaydigan elementlarni topiş + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Obyekt xususiyatini e’tiborsiz qoldiriş .load-partial-cui = Qisman CUI yuklaş .maintain-associative-objects = Assotsiativ obyektlarni saqlab qoliş diff --git a/locales/vi-VN/opencadstudio.ftl b/locales/vi-VN/opencadstudio.ftl index fb434d27e1..e002ae7410 100644 --- a/locales/vi-VN/opencadstudio.ftl +++ b/locales/vi-VN/opencadstudio.ftl @@ -6723,6 +6723,22 @@ manage = .find-non-purgeable-items = Tìm mục không thể dọn + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = Bỏ qua thuộc tính đối tượng .load-partial-cui = Tải CUI bổ sung .maintain-associative-objects = Giữ các đối tượng liên kết diff --git a/locales/zh-CN/opencadstudio.ftl b/locales/zh-CN/opencadstudio.ftl index ac25436fcf..f00a19a320 100644 --- a/locales/zh-CN/opencadstudio.ftl +++ b/locales/zh-CN/opencadstudio.ftl @@ -6699,6 +6699,22 @@ manage = .find-non-purgeable-items = 查找不可 清理项目 + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = 忽略对象特性 .load-partial-cui = 加载局部 CUI .maintain-associative-objects = 保持关联对象 diff --git a/locales/zh-TW/opencadstudio.ftl b/locales/zh-TW/opencadstudio.ftl index edc71b9b8b..be19289c1a 100644 --- a/locales/zh-TW/opencadstudio.ftl +++ b/locales/zh-TW/opencadstudio.ftl @@ -6711,6 +6711,22 @@ manage = .find-non-purgeable-items = 尋找不可 清理項目 + .geometry-cleanup = Geometry Cleanup + .geometry-cleanup-cannot-fix = This error cannot be fixed that way. + .geometry-cleanup-empty = Select objects to find gaps, overshoots and undershoots. + .geometry-cleanup-error-gone = The error is no longer in the drawing. + .geometry-cleanup-found = Geometry Cleanup: __ocs_fmt_0__ error(s) found. + .geometry-cleanup-no-errors = No errors found. + .geometry-cleanup-overshoot = Overshoot + .geometry-cleanup-remaining = Remaining Errors: __ocs_fmt_0__ + .geometry-cleanup-rescan = Rescan + .geometry-cleanup-tip-extend = Lengthen the end along its own line or arc to the object it stops short of. + .geometry-cleanup-tip-extend-both = Lengthen both ends along their own lines to the corner where they meet. + .geometry-cleanup-tip-move = Move the whole object so that its end meets the other end. + .geometry-cleanup-tip-stretch = Move only this end onto the other end. The rest of the object stays. + .geometry-cleanup-tip-trim = Cut the end back to the object it crosses. + .geometry-cleanup-tolerance = Tolerance: __ocs_fmt_0__ + .geometry-cleanup-undershoot = Undershoot .ignore-object-property = 忽略物件性質 .load-partial-cui = 載入局部 CUI .maintain-associative-objects = 保留關聯式物件 diff --git a/src/app/commands/geometry_cleanup.rs b/src/app/commands/geometry_cleanup.rs new file mode 100644 index 0000000000..df8ccf22db --- /dev/null +++ b/src/app/commands/geometry_cleanup.rs @@ -0,0 +1,358 @@ +//! GEOMETRYCLEANUPOPEN, GEOMETRYCLEANUPCLOSE and the Geometry Cleanup +//! palette: the scan of the selected objects and the repair of one error. + +use crate::app::{Message, OpenCADStudio}; +use crate::modules::manage::geometry_cleanup as cleanup; +use crate::ui::dock::PanelId; +use crate::ui::window::geometry_cleanup::{rows, Finding, Fix, GeometryCleanupMsg, Scan}; +use document::{EntityType, Handle}; +use iced::Task; +use ocs_geom::geom2d::cleanup::{end_errors, proposed_tolerance}; +use ocs_geom::geom2d::{Curve, Tolerance}; + +/// Ends nearer than this meet: they are not an error. +const WELD: f64 = 1e-6; + +impl OpenCADStudio { + pub(super) fn dispatch_geometry_cleanup( + &mut self, + cmd: &str, + i: usize, + ) -> Option> { + let cmd = cmd.trim(); + let (verb, rest) = cmd.split_once(char::is_whitespace).unwrap_or((cmd, "")); + match verb.to_ascii_uppercase().as_str() { + "GEOMETRYCLEANUPOPEN" => { + self.set_geometry_cleanup(true); + // Objects selected before the command are scanned at once. + let selected = self.tabs[i].scene.selected_handles_in_order(); + if !selected.is_empty() { + self.tabs[i].scene.deselect_all(); + self.geometry_cleanup_scan(i, selected, None, true); + } + Some(Task::none()) + } + "GEOMETRYCLEANUPCLOSE" => { + self.set_geometry_cleanup(false); + Some(Task::none()) + } + "_GEOMETRYCLEANUPSCAN" => { + let objects = rest + .split(',') + .filter_map(|text| u64::from_str_radix(text.trim(), 16).ok()) + .map(Handle::new) + .collect(); + self.tabs[i].scene.deselect_all(); + self.geometry_cleanup_scan(i, objects, None, true); + Some(Task::none()) + } + _ => None, + } + } + + /// Open or close the Geometry Cleanup palette (docked, expanded). + pub(in crate::app) fn set_geometry_cleanup(&mut self, open: bool) { + let id = PanelId::GeometryCleanup; + self.geometry_cleanup.show = open; + if open { + self.dock_open_at_default(id); + } else { + self.dock_unpeek(id); + } + } + + /// The curves of the objects that Geometry Cleanup may read, with + /// their handles. + fn geometry_cleanup_curves(&self, i: usize, objects: &[Handle]) -> Vec<(Handle, Curve)> { + let document = &self.tabs[i].scene.document; + objects + .iter() + .filter(|handle| cleanup::is_candidate(document, **handle)) + .filter_map(|handle| { + Some(( + *handle, + cleanup::cleanup_curve(document.get_entity(*handle)?)?, + )) + }) + .collect() + } + + /// The errors among `objects` now, within `tolerance`. + fn geometry_cleanup_findings( + &self, + i: usize, + objects: &[Handle], + tolerance: f64, + ) -> Vec { + let kept = self.geometry_cleanup_curves(i, objects); + let curves: Vec = kept.iter().map(|(_, curve)| curve.clone()).collect(); + end_errors(&curves, tolerance, Tolerance::new(WELD)) + .into_iter() + .map(|error| Finding { + kind: error.kind, + handle: kept[error.end.curve].0, + at_start: error.end.at_start, + location: error.location, + target: error.target, + other: error + .other + .map(|other| (kept[other.curve].0, other.at_start)), + corner: error.corner, + deviation: error.deviation, + }) + .collect() + } + + /// Scan `objects` and show what was found. A new selection gets the + /// tolerance proposed for the drawing and a report on the command line; + /// a rescan keeps the tolerance, and the picked error if it is still + /// there. + fn geometry_cleanup_scan( + &mut self, + i: usize, + objects: Vec, + tolerance: Option, + report: bool, + ) { + let rescan = tolerance.is_some(); + let tolerance = tolerance.unwrap_or_else(|| { + let document = &self.tabs[i].scene.document; + let drawing: Vec = document + .entities() + .filter(|entity| cleanup::is_candidate(document, entity.common().handle)) + .filter_map(cleanup::cleanup_curve) + .collect(); + proposed_tolerance(&drawing) + }); + let findings = self.geometry_cleanup_findings(i, &objects, tolerance); + if report { + self.command_line.push_output(&crate::tf!( + "Geometry Cleanup: {} error(s) found.", + findings.len() + )); + } + let picked = self + .geometry_cleanup_scan_here(i) + .zip(self.geometry_cleanup.picked) + .and_then(|(scan, index)| scan.findings.get(index).copied()) + .filter(|_| rescan) + .and_then(|old| findings.iter().position(|f| f.same_error(&old))); + self.geometry_cleanup.scan = Some(Scan { + tab: self.tabs[i].id, + epoch: self.tabs[i].scene.geometry_epoch, + objects, + tolerance, + findings, + }); + self.geometry_cleanup.picked = picked; + } + + /// After the drawing changes, the open palette scans its objects again: + /// an edit, an undo or a repair keeps the list true. Not while a command + /// or a grip edit runs, which change the drawing on each move; the scan + /// comes when they end. + pub(in crate::app) fn refresh_geometry_cleanup_if_stale(&mut self) { + let i = self.active_tab; + let tab = &self.tabs[i]; + if !self.geometry_cleanup.show || tab.active_cmd.is_some() || tab.active_grip.is_some() { + return; + } + let Some(scan) = self.geometry_cleanup_scan_here(i) else { + return; + }; + if scan.epoch == self.tabs[i].scene.geometry_epoch { + return; + } + let (objects, tolerance) = (scan.objects.clone(), scan.tolerance); + self.geometry_cleanup_scan(i, objects, Some(tolerance), false); + } + + /// The scan of the active tab, if the palette shows one. + fn geometry_cleanup_scan_here(&self, i: usize) -> Option<&Scan> { + self.geometry_cleanup + .scan + .as_ref() + .filter(|scan| scan.tab == self.tabs[i].id) + } + + pub(in crate::app) fn on_geometry_cleanup(&mut self, m: GeometryCleanupMsg) -> Task { + let i = self.active_tab; + match m { + GeometryCleanupMsg::SelectObjects => { + self.tabs[i].scene.deselect_all(); + let command = cleanup::SelectObjects; + self.reset_command_start_state(i); + self.command_line + .push_info(&crate::command::CadCommand::prompt(&command)); + self.tabs[i].active_cmd = Some(Box::new(command)); + self.push_ucs_to_cmd(i); + self.sync_dyn_fields(); + return self.focus_cmd_input(); + } + GeometryCleanupMsg::Rescan => { + if let Some(scan) = self.geometry_cleanup_scan_here(i) { + let (objects, tolerance) = (scan.objects.clone(), scan.tolerance); + self.geometry_cleanup_scan(i, objects, Some(tolerance), true); + } + } + GeometryCleanupMsg::Pick(index) => { + let Some(finding) = self.geometry_cleanup_scan_here(i).and_then(|scan| { + scan.findings + .get(index) + .copied() + .map(|f| (f, scan.tolerance)) + }) else { + return Task::none(); + }; + self.geometry_cleanup.picked = Some(index); + self.geometry_cleanup_show(i, finding.0, finding.1); + } + GeometryCleanupMsg::Fix(index, fix) => { + let Some(scan) = self.geometry_cleanup_scan_here(i) else { + return Task::none(); + }; + let Some(picked) = scan.findings.get(index).copied() else { + return Task::none(); + }; + // The rows below the fixed one, then those above it nearest + // first: where the pick goes after the repair. + let rows = rows(&self.geometry_cleanup, scan); + let at = rows.iter().position(|&row| row == index).unwrap_or(0); + let after: Vec = rows[at + 1..] + .iter() + .chain(rows[..at].iter().rev()) + .map(|&row| scan.findings[row]) + .collect(); + let (objects, tolerance) = (scan.objects.clone(), scan.tolerance); + if !self.geometry_cleanup_fix(i, picked, fix, &objects, tolerance) { + return Task::none(); + } + self.geometry_cleanup_scan(i, objects, Some(tolerance), false); + self.geometry_cleanup_pick_next(i, &after); + } + GeometryCleanupMsg::Fold(kind) => { + let folded = &mut self.geometry_cleanup.folded; + if let Some(at) = folded.iter().position(|k| *k == kind) { + folded.remove(at); + } else { + folded.push(kind); + } + } + } + Task::none() + } + + /// After a repair: pick the first of `after` that is still an error, + /// and zoom to it. Nothing is picked when none is left. + fn geometry_cleanup_pick_next(&mut self, i: usize, after: &[Finding]) { + let Some(scan) = self.geometry_cleanup_scan_here(i) else { + return; + }; + let tolerance = scan.tolerance; + let next = after.iter().find_map(|old| { + let index = scan.findings.iter().position(|f| f.same_error(old))?; + Some((index, scan.findings[index])) + }); + self.geometry_cleanup.picked = next.map(|(index, _)| index); + if let Some((_, finding)) = next { + self.geometry_cleanup_show(i, finding, tolerance); + } + } + + /// Zoom to an error and select its objects. + fn geometry_cleanup_show(&mut self, i: usize, finding: Finding, tolerance: f64) { + let reach = (tolerance * 25.0).max(finding.deviation * 5.0); + let [x, y] = finding.location; + self.handle_zoom_to_window( + glam::DVec3::new(x - reach, y - reach, 0.0), + glam::DVec3::new(x + reach, y + reach, 0.0), + ); + let scene = &mut self.tabs[i].scene; + scene.select_entity(finding.handle, true); + if let Some((other, _)) = finding.other { + scene.select_entity(other, false); + } + self.refresh_selected_grips(); + } + + /// Repair one error as one undo step; `false` when nothing changed. The + /// drawing can have changed since the scan (an undo, an edit), so the + /// error is looked up again first; an error that is gone changes + /// nothing. + fn geometry_cleanup_fix( + &mut self, + i: usize, + picked: Finding, + fix: Fix, + objects: &[Handle], + tolerance: f64, + ) -> bool { + let Some(finding) = self + .geometry_cleanup_findings(i, objects, tolerance) + .into_iter() + .find(|f| f.same_error(&picked)) + else { + self.command_line + .push_error(&crate::t!("The error is no longer in the drawing.")); + return false; + }; + let document = &self.tabs[i].scene.document; + let entity = |handle: Handle| document.get_entity(handle); + let mut edits: Vec<(Handle, EntityType)> = Vec::new(); + let done = (|| -> Option<()> { + let own = entity(finding.handle)?; + match fix { + Fix::Trim | Fix::Extend => { + edits.push(( + finding.handle, + cleanup::moved_along(own, finding.at_start, finding.target)?, + )); + } + Fix::Stretch => { + edits.push(( + finding.handle, + cleanup::stretched(own, finding.at_start, finding.target)?, + )); + } + Fix::Move => { + let by = [ + finding.target[0] - finding.location[0], + finding.target[1] - finding.location[1], + ]; + edits.push((finding.handle, cleanup::moved(own, by))); + } + Fix::ExtendBoth => { + let corner = finding.corner?; + let (other, other_at_start) = finding.other?; + edits.push(( + finding.handle, + cleanup::moved_along(own, finding.at_start, corner)?, + )); + edits.push(( + other, + cleanup::moved_along(entity(other)?, other_at_start, corner)?, + )); + } + } + Some(()) + })(); + if done.is_none() || !finding.fixes().contains(&fix) { + self.command_line + .push_error(&crate::t!("This error cannot be fixed that way.")); + return false; + } + self.push_undo_snapshot(i, "GEOMETRYCLEANUP"); + let mut changes = Vec::new(); + for (handle, replacement) in edits { + if let Some(target) = self.tabs[i].scene.document.get_entity_mut(handle) { + *target = replacement; + changes.push((handle, crate::scene::ChangeKind::Modified)); + } + } + self.tabs[i].scene.bump_entities(&changes); + self.tabs[i].dirty = true; + self.refresh_selected_grips(); + self.refresh_properties(); + true + } +} diff --git a/src/app/commands/geometry_cleanup_tests.rs b/src/app/commands/geometry_cleanup_tests.rs new file mode 100644 index 0000000000..2990e1581e --- /dev/null +++ b/src/app/commands/geometry_cleanup_tests.rs @@ -0,0 +1,623 @@ +use crate::app::{Message, OpenCADStudio}; +use crate::ui::dock::PanelId; +use crate::ui::window::geometry_cleanup::{Finding, Fix, GeometryCleanupMsg}; +use document::entities::{Arc, Line, LwPolyline}; +use document::types::{Vector2, Vector3}; +use document::{EntityType, Handle}; +use ocs_geom::geom2d::cleanup::EndErrorKind; + +fn app() -> (OpenCADStudio, usize) { + let mut app = OpenCADStudio::new_for_test(); + app.automation_op(r#"{"op":"new"}"#); + let i = app.active_tab; + app.tabs[i].scene.selection.borrow_mut().view.vp_size = (800.0, 600.0); + (app, i) +} + +fn add(app: &mut OpenCADStudio, entity: EntityType) -> Handle { + let i = app.active_tab; + app.tabs[i].scene.add_entity(entity) +} + +fn line(app: &mut OpenCADStudio, a: [f64; 2], b: [f64; 2]) -> Handle { + add( + app, + EntityType::Line(Line::from_points( + Vector3::new(a[0], a[1], 0.0), + Vector3::new(b[0], b[1], 0.0), + )), + ) +} + +fn ends(app: &OpenCADStudio, handle: Handle) -> [[f64; 2]; 2] { + match app.tabs[app.active_tab].scene.document.get_entity(handle) { + Some(EntityType::Line(line)) => [[line.start.x, line.start.y], [line.end.x, line.end.y]], + other => panic!("expected a line, found {other:?}"), + } +} + +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).hypot(a[1] - b[1]) < 1e-9 +} + +/// Scan `objects` as Select Objects does. +fn scan(app: &mut OpenCADStudio, objects: &[Handle]) -> Vec { + let list: Vec = objects.iter().map(|h| format!("{:X}", h.value())).collect(); + let _ = app.dispatch_command(&format!("_GEOMETRYCLEANUPSCAN {}", list.join(","))); + findings(app) +} + +fn findings(app: &OpenCADStudio) -> Vec { + app.geometry_cleanup + .scan + .as_ref() + .map(|scan| scan.findings.clone()) + .unwrap_or_default() +} + +fn fix(app: &mut OpenCADStudio, kind: EndErrorKind, fix: Fix) { + let index = findings(app) + .iter() + .position(|finding| finding.kind == kind) + .expect("the error is listed"); + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::Fix( + index, fix, + ))); +} + +/// A wall (x = 10), a line 0.4 past it, a line 0.3 short of it, and two +/// lines whose ends are 0.2 apart. The mean length is 64, so the proposed +/// tolerance (1% of it) is 0.64. +fn errors_drawing(app: &mut OpenCADStudio) -> [Handle; 5] { + let wall = line(app, [10.0, -100.0], [10.0, 100.0]); + let over = line(app, [0.0, 50.0], [10.4, 50.0]); + let under = line(app, [0.0, -50.0], [9.7, -50.0]); + let left = line(app, [-60.0, 0.0], [-40.0, 0.0]); + let right = line(app, [-39.8, 0.0], [-20.0, 0.0]); + [wall, over, under, left, right] +} + +#[test] +fn open_and_close_show_and_hide_the_palette() { + let (mut app, _) = app(); + let _ = app.dispatch_command("GEOMETRYCLEANUPOPEN"); + assert!(app.geometry_cleanup.show); + assert!(app.dock_panel_wanted(PanelId::GeometryCleanup)); + let _ = app.dispatch_command("GEOMETRYCLEANUPCLOSE"); + assert!(!app.geometry_cleanup.show); +} + +#[test] +fn a_scan_lists_each_end_error_of_the_selection() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + let [_, over, under, left, right] = objects; + let found = scan(&mut app, &objects); + let tolerance = app.geometry_cleanup.scan.as_ref().unwrap().tolerance; + assert!(tolerance > 0.4, "proposed tolerance {tolerance}"); + let mut kinds: Vec<(EndErrorKind, Handle)> = found.iter().map(|f| (f.kind, f.handle)).collect(); + kinds.sort_by_key(|(kind, handle)| (*kind, handle.value())); + assert_eq!( + kinds, + [ + (EndErrorKind::Gap, left), + (EndErrorKind::Overshoot, over), + (EndErrorKind::Undershoot, under), + ] + ); + let gap = found.iter().find(|f| f.kind == EndErrorKind::Gap).unwrap(); + assert_eq!(gap.other, Some((right, true))); +} + +#[test] +fn trim_cuts_an_overshoot_back_as_one_undo_step() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + scan(&mut app, &objects); + fix(&mut app, EndErrorKind::Overshoot, Fix::Trim); + assert!(near(ends(&app, objects[1])[1], [10.0, 50.0])); + assert!( + !findings(&app) + .iter() + .any(|f| f.kind == EndErrorKind::Overshoot), + "the list is scanned again after the fix" + ); + let _ = app.update(Message::Undo); + assert!(near(ends(&app, objects[1])[1], [10.4, 50.0])); +} + +#[test] +fn extend_runs_an_undershoot_on_to_the_wall() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + scan(&mut app, &objects); + fix(&mut app, EndErrorKind::Undershoot, Fix::Extend); + assert!(near(ends(&app, objects[2])[1], [10.0, -50.0])); +} + +#[test] +fn stretch_and_move_close_a_gap() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + scan(&mut app, &objects); + fix(&mut app, EndErrorKind::Gap, Fix::Stretch); + assert_eq!(ends(&app, objects[3]), [[-60.0, 0.0], [-39.8, 0.0]]); + + let (mut app, _) = self::app(); + let objects = errors_drawing(&mut app); + scan(&mut app, &objects); + fix(&mut app, EndErrorKind::Gap, Fix::Move); + let moved = ends(&app, objects[3]); + assert!(near(moved[0], [-59.8, 0.0]) && near(moved[1], [-39.8, 0.0])); +} + +#[test] +fn extend_takes_both_ends_of_a_corner_gap_to_the_corner() { + let (mut app, _) = app(); + let wide = line(&mut app, [-200.0, -200.0], [200.0, 200.0]); + let a = line(&mut app, [0.0, 0.0], [10.0, 0.0]); + let b = line(&mut app, [10.2, 0.1], [10.2, 10.0]); + let found = scan(&mut app, &[wide, a, b]); + let gap = found.iter().find(|f| f.kind == EndErrorKind::Gap).copied(); + let gap = gap.expect("a gap"); + assert!(gap.fixes().contains(&Fix::ExtendBoth)); + fix(&mut app, EndErrorKind::Gap, Fix::ExtendBoth); + assert!(near(ends(&app, a)[1], [10.2, 0.0])); + assert!(near(ends(&app, b)[0], [10.2, 0.0])); + let _ = app.update(Message::Undo); + assert!(near(ends(&app, a)[1], [10.0, 0.0]), "one undo step"); + assert!(near(ends(&app, b)[0], [10.2, 0.1]), "one undo step"); +} + +#[test] +fn an_arc_end_is_trimmed_along_its_circle() { + let (mut app, i) = app(); + let wall = line(&mut app, [0.0, -100.0], [0.0, 100.0]); + // A quarter arc about (10, 5) whose end runs 0.02 rad past the wall. + let arc = add( + &mut app, + EntityType::Arc(Arc::from_center_radius_angles( + Vector3::new(10.0, 5.0, 0.0), + 10.0, + std::f64::consts::FRAC_PI_2, + std::f64::consts::PI + 0.02, + )), + ); + let found = scan(&mut app, &[wall, arc]); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].kind, EndErrorKind::Overshoot); + fix(&mut app, EndErrorKind::Overshoot, Fix::Trim); + match app.tabs[i].scene.document.get_entity(arc) { + Some(EntityType::Arc(arc)) => { + let end = std::f64::consts::PI; + assert!((arc.end_angle.rem_euclid(std::f64::consts::TAU) - end).abs() < 1e-9); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn a_polyline_arc_end_keeps_its_circle_when_extended() { + let (mut app, i) = app(); + let wall = line(&mut app, [-100.0, 10.0], [100.0, 10.0]); + // From (20, 0) a straight segment to (10, 0), then an arc of radius 10 + // about (10, 10) that stops 0.03 rad short of the top wall. + let stop = -std::f64::consts::FRAC_PI_2 - (std::f64::consts::FRAC_PI_2 - 0.03); + let end = [10.0 + 10.0 * stop.cos(), 10.0 + 10.0 * stop.sin()]; + let mut polyline = LwPolyline::from_points(vec![ + Vector2::new(20.0, 0.0), + Vector2::new(10.0, 0.0), + Vector2::new(end[0], end[1]), + ]); + // Clockwise from -90° to `stop`. + let sweep = stop + std::f64::consts::FRAC_PI_2; + polyline.vertices[1].bulge = (sweep / 4.0).tan(); + let handle = add(&mut app, EntityType::LwPolyline(polyline)); + let found = scan(&mut app, &[wall, handle]); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].kind, EndErrorKind::Undershoot); + assert!(near(found[0].target, [0.0, 10.0]), "{found:?}"); + fix(&mut app, EndErrorKind::Undershoot, Fix::Extend); + match app.tabs[i].scene.document.get_entity(handle) { + Some(EntityType::LwPolyline(polyline)) => { + let last = polyline.vertices[2].location; + assert!(near([last.x, last.y], [0.0, 10.0])); + let quarter = (-std::f64::consts::FRAC_PI_2 / 4.0).tan(); + assert!((polyline.vertices[1].bulge - quarter).abs() < 1e-9); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn locked_layers_and_lines_off_the_xy_plane_are_not_scanned() { + let (mut app, i) = app(); + let objects = errors_drawing(&mut app); + { + let document = &mut app.tabs[i].scene.document; + let mut layer = document::tables::Layer::new("Locked"); + layer.handle = document.allocate_handle(); + layer.flags.locked = true; + document.layers.add(layer).unwrap(); + document + .get_entity_mut(objects[1]) + .unwrap() + .common_mut() + .layer = "Locked".into(); + if let Some(EntityType::Line(line)) = document.get_entity_mut(objects[2]) { + line.end.z = 1.0; + } + } + let kinds: Vec = scan(&mut app, &objects).iter().map(|f| f.kind).collect(); + assert_eq!(kinds, [EndErrorKind::Gap]); +} + +#[test] +fn a_fix_after_the_drawing_changed_changes_nothing() { + let (mut app, i) = app(); + let objects = errors_drawing(&mut app); + scan(&mut app, &objects); + // The overshooting line is moved away after the scan. + if let Some(EntityType::Line(line)) = app.tabs[i].scene.document.get_entity_mut(objects[1]) { + line.start.x -= 50.0; + line.end.x -= 50.0; + } + let before = ends(&app, objects[1]); + let undo = app.tabs[i].history.undo_stack.len(); + fix(&mut app, EndErrorKind::Overshoot, Fix::Trim); + assert_eq!(ends(&app, objects[1]), before); + assert_eq!(app.tabs[i].history.undo_stack.len(), undo); +} + +#[test] +fn select_objects_scans_what_the_user_selects() { + let (mut app, i) = app(); + let objects = errors_drawing(&mut app); + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::SelectObjects)); + let cmd = app.tabs[i].active_cmd.as_ref().expect("a selection prompt"); + assert_eq!(cmd.name(), "GEOMETRYCLEANUPOPEN"); + assert!(cmd.is_selection_gathering()); + let result = app.tabs[i] + .active_cmd + .as_mut() + .unwrap() + .on_selection_complete(objects.to_vec()); + let _ = app.apply_cmd_result(result); + assert_eq!(findings(&app).len(), 3); + assert!(app.tabs[i].scene.selected.is_empty()); +} + +#[test] +fn picking_an_error_selects_its_objects() { + let (mut app, i) = app(); + let objects = errors_drawing(&mut app); + let found = scan(&mut app, &objects); + let gap = found + .iter() + .position(|f| f.kind == EndErrorKind::Gap) + .unwrap(); + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::Pick(gap))); + assert_eq!(app.geometry_cleanup.picked, Some(gap)); + let selected = &app.tabs[i].scene.selected; + assert!(selected.contains(&objects[3]) && selected.contains(&objects[4])); + assert_eq!(selected.len(), 2); +} + +/// Open the palette and scan `objects` in it. +fn open_and_scan(app: &mut OpenCADStudio, objects: &[Handle]) { + let _ = app.dispatch_command("GEOMETRYCLEANUPOPEN"); + scan(app, objects); +} + +/// Move a line by hand, outside the palette. +fn shift(app: &mut OpenCADStudio, handle: Handle, dx: f64) { + let i = app.active_tab; + if let Some(EntityType::Line(line)) = app.tabs[i].scene.document.get_entity_mut(handle) { + line.start.x += dx; + line.end.x += dx; + } + app.tabs[i] + .scene + .bump_entities(&[(handle, crate::scene::ChangeKind::Modified)]); +} + +#[test] +fn the_open_palette_lists_an_error_again_after_its_repair_is_undone() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + open_and_scan(&mut app, &objects); + fix(&mut app, EndErrorKind::Overshoot, Fix::Trim); + assert!(!findings(&app) + .iter() + .any(|f| f.kind == EndErrorKind::Overshoot)); + let _ = app.update(Message::Undo); + assert!(findings(&app) + .iter() + .any(|f| f.kind == EndErrorKind::Overshoot)); +} + +#[test] +fn the_open_palette_scans_again_after_an_edit_and_keeps_the_picked_error() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + open_and_scan(&mut app, &objects); + let gap = findings(&app) + .iter() + .position(|f| f.kind == EndErrorKind::Gap) + .unwrap(); + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::Pick(gap))); + let picked = findings(&app)[gap]; + // The overshooting line is moved away from the wall. + shift(&mut app, objects[1], -50.0); + app.refresh_geometry_cleanup_if_stale(); + let now = findings(&app); + assert!( + !now.iter().any(|f| f.kind == EndErrorKind::Overshoot), + "{now:?}" + ); + let index = app.geometry_cleanup.picked.expect("still picked"); + assert!(now[index].same_error(&picked)); +} + +#[test] +fn the_palette_waits_for_a_running_command_before_it_scans_again() { + let (mut app, i) = app(); + let objects = errors_drawing(&mut app); + open_and_scan(&mut app, &objects); + let before = findings(&app); + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::SelectObjects)); + assert!(app.tabs[i].active_cmd.is_some()); + shift(&mut app, objects[1], -50.0); + app.refresh_geometry_cleanup_if_stale(); + assert_eq!(findings(&app), before, "no scan while the command runs"); + let _ = app.update(Message::CommandEscape); + assert!(app.tabs[i].active_cmd.is_none()); + assert_ne!(findings(&app), before, "the scan comes when it ends"); +} + +#[test] +fn a_closed_palette_does_not_scan_again() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + scan(&mut app, &objects); + let before = findings(&app); + shift(&mut app, objects[1], -50.0); + app.refresh_geometry_cleanup_if_stale(); + assert_eq!(findings(&app), before); +} + +fn picked(app: &OpenCADStudio) -> Option { + app.geometry_cleanup + .picked + .map(|index| findings(app)[index]) +} + +fn selected(app: &OpenCADStudio) -> Vec { + let mut handles: Vec = app.tabs[app.active_tab] + .scene + .selected + .iter() + .copied() + .collect(); + handles.sort_by_key(|handle| handle.value()); + handles +} + +/// The rows are Gap, Overshoot, Undershoot. A repair picks the next row, +/// or the row above it at the end, and selects its objects. +#[test] +fn a_repair_picks_the_next_row() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + let [_, _, under, left, right] = objects; + open_and_scan(&mut app, &objects); + fix(&mut app, EndErrorKind::Overshoot, Fix::Trim); + assert_eq!(picked(&app).map(|f| f.kind), Some(EndErrorKind::Undershoot)); + assert_eq!(selected(&app), [under]); + fix(&mut app, EndErrorKind::Undershoot, Fix::Extend); + assert_eq!(picked(&app).map(|f| f.kind), Some(EndErrorKind::Gap)); + assert_eq!(selected(&app), [left, right]); + fix(&mut app, EndErrorKind::Gap, Fix::Stretch); + assert_eq!(picked(&app), None, "no error is left"); +} + +#[test] +fn a_folded_type_is_skipped_by_the_next_pick() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + open_and_scan(&mut app, &objects); + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::Fold( + EndErrorKind::Undershoot, + ))); + fix(&mut app, EndErrorKind::Overshoot, Fix::Trim); + assert_eq!(picked(&app).map(|f| f.kind), Some(EndErrorKind::Gap)); +} + +#[test] +fn a_repair_that_fails_keeps_the_pick() { + let (mut app, _) = app(); + let objects = errors_drawing(&mut app); + open_and_scan(&mut app, &objects); + let gap = findings(&app) + .iter() + .position(|f| f.kind == EndErrorKind::Gap) + .unwrap(); + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::Pick(gap))); + // The overshoot is gone before its repair is pressed; the list is not + // scanned again in between, as in a palette that waits for a command. + let i = app.active_tab; + if let Some(EntityType::Line(line)) = app.tabs[i].scene.document.get_entity_mut(objects[1]) { + line.end.x = 10.0; + } + fix(&mut app, EndErrorKind::Overshoot, Fix::Trim); + assert_eq!(picked(&app).map(|f| f.kind), Some(EndErrorKind::Gap)); +} + +#[test] +fn opening_the_palette_scans_the_selected_objects_only_when_there_are_some() { + let (mut app, i) = app(); + let objects = errors_drawing(&mut app); + let _ = app.dispatch_command("GEOMETRYCLEANUPOPEN"); + assert!(app.geometry_cleanup.scan.is_none(), "nothing was selected"); + for &handle in &objects { + app.tabs[i].scene.select_entity(handle, false); + } + let _ = app.dispatch_command("GEOMETRYCLEANUPOPEN"); + assert_eq!(findings(&app).len(), 3); +} + +#[test] +fn folding_a_type_again_unfolds_it() { + let (mut app, _) = app(); + let fold = |app: &mut OpenCADStudio| { + let _ = app.update(Message::GeometryCleanup(GeometryCleanupMsg::Fold( + EndErrorKind::Gap, + ))); + }; + fold(&mut app); + assert_eq!(app.geometry_cleanup.folded, [EndErrorKind::Gap]); + fold(&mut app); + assert!(app.geometry_cleanup.folded.is_empty()); +} + +#[test] +fn move_takes_the_whole_object_across_a_gap_in_x_and_y() { + let (mut app, _) = app(); + let a = line(&mut app, [-40.0, 5.0], [10.0, 5.0]); + let b = line(&mut app, [10.2, 5.1], [60.0, 5.1]); + let kinds: Vec = scan(&mut app, &[a, b]).iter().map(|f| f.kind).collect(); + assert_eq!(kinds, [EndErrorKind::Gap]); + fix(&mut app, EndErrorKind::Gap, Fix::Move); + let moved = ends(&app, a); + assert!( + near(moved[0], [-39.8, 5.1]) && near(moved[1], [10.2, 5.1]), + "{moved:?}" + ); +} + +#[test] +fn a_repair_that_the_error_does_not_offer_changes_nothing() { + let (mut app, i) = app(); + let objects = errors_drawing(&mut app); + scan(&mut app, &objects); + let undo = app.tabs[i].history.undo_stack.len(); + fix(&mut app, EndErrorKind::Gap, Fix::Trim); + assert_eq!(ends(&app, objects[3]), [[-60.0, 0.0], [-40.0, 0.0]]); + assert_eq!(app.tabs[i].history.undo_stack.len(), undo); +} + +#[test] +fn arcs_and_polylines_off_the_world_xy_plane_are_not_read() { + use crate::modules::manage::geometry_cleanup::cleanup_curve; + let arc = Arc::from_center_radius_angles(Vector3::new(1.0, 2.0, 0.0), 5.0, 0.0, 1.0); + let polyline = LwPolyline::from_points(vec![Vector2::new(0.0, 0.0), Vector2::new(5.0, 0.0)]); + assert!(cleanup_curve(&EntityType::Arc(arc.clone())).is_some()); + assert!(cleanup_curve(&EntityType::LwPolyline(polyline.clone())).is_some()); + for normal in [ + Vector3::new(0.0, 0.0, -1.0), + Vector3::new(0.6, 0.0, 0.8), + Vector3::new(0.0, 0.6, 0.8), + ] { + let mut tilted = arc.clone(); + tilted.normal = normal; + assert!( + cleanup_curve(&EntityType::Arc(tilted)).is_none(), + "{normal:?}" + ); + let mut tilted = polyline.clone(); + tilted.normal = normal; + assert!( + cleanup_curve(&EntityType::LwPolyline(tilted)).is_none(), + "{normal:?}" + ); + } + let mut raised = arc; + raised.center.z = 1.0; + assert!(cleanup_curve(&EntityType::Arc(raised)).is_none()); + let mut raised = polyline; + raised.elevation = 1.0; + assert!(cleanup_curve(&EntityType::LwPolyline(raised)).is_none()); +} + +#[test] +fn a_two_point_polyline_is_extended_at_its_end() { + let (mut app, i) = app(); + let wall = line(&mut app, [10.0, -100.0], [10.0, 100.0]); + let handle = add( + &mut app, + EntityType::LwPolyline(LwPolyline::from_points(vec![ + Vector2::new(0.0, 0.0), + Vector2::new(9.7, 0.0), + ])), + ); + let kinds: Vec = scan(&mut app, &[wall, handle]) + .iter() + .map(|f| f.kind) + .collect(); + assert_eq!(kinds, [EndErrorKind::Undershoot]); + fix(&mut app, EndErrorKind::Undershoot, Fix::Extend); + match app.tabs[i].scene.document.get_entity(handle) { + Some(EntityType::LwPolyline(polyline)) => { + let last = polyline.vertices[1].location; + assert!(near([last.x, last.y], [10.0, 0.0]), "{last:?}"); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn stretch_moves_the_grip_at_the_end_that_it_repairs() { + use crate::modules::manage::geometry_cleanup::stretched; + for (start, end, to) in [ + ([10.0, 5.0], [20.0, 5.0], [25.0, 5.0]), + ([5.0, 10.0], [5.0, 20.0], [5.0, 25.0]), + ] { + let entity = EntityType::Line(Line::from_points( + Vector3::new(start[0], start[1], 0.0), + Vector3::new(end[0], end[1], 0.0), + )); + match stretched(&entity, false, to) { + Some(EntityType::Line(line)) => { + assert!(near([line.start.x, line.start.y], start), "{line:?}"); + assert!(near([line.end.x, line.end.y], to), "{line:?}"); + } + other => panic!("{other:?}"), + } + } +} + +#[test] +fn the_same_error_is_the_same_type_at_the_same_end_of_the_same_object() { + let error = Finding { + kind: EndErrorKind::Gap, + handle: Handle::new(1), + at_start: true, + location: [0.0, 0.0], + target: [0.1, 0.0], + other: None, + corner: None, + deviation: 0.1, + }; + let moved = Finding { + location: [1.0, 1.0], + deviation: 0.2, + ..error + }; + assert!(error.same_error(&moved)); + for other in [ + Finding { + kind: EndErrorKind::Overshoot, + ..error + }, + Finding { + handle: Handle::new(2), + ..error + }, + Finding { + at_start: false, + ..error + }, + ] { + assert!(!error.same_error(&other), "{other:?}"); + } +} diff --git a/src/app/commands/mod.rs b/src/app/commands/mod.rs index a2f5c37ba3..66f849dc7a 100644 --- a/src/app/commands/mod.rs +++ b/src/app/commands/mod.rs @@ -34,6 +34,9 @@ mod bvisibility; mod count; mod dash; mod dgn_import; +mod geometry_cleanup; +#[cfg(test)] +mod geometry_cleanup_tests; mod ifc_plan; pub(in crate::app) use dgn_import::read_reference_drawings; mod dim; @@ -871,6 +874,9 @@ impl OpenCADStudio { if let Some(t) = self.dispatch_count(cmd, i) { return Some(t); } + if let Some(t) = self.dispatch_geometry_cleanup(cmd, i) { + return Some(t); + } if let Some(t) = self.dispatch_attout(cmd, i) { return Some(t); } diff --git a/src/app/dock/update.rs b/src/app/dock/update.rs index 0e3da6d5bd..912ba5e1b4 100644 --- a/src/app/dock/update.rs +++ b/src/app/dock/update.rs @@ -625,6 +625,7 @@ impl OpenCADStudio { } PanelId::PointCloudManager => self.pc_manager.show = true, PanelId::Count => self.set_count_palette(true), + PanelId::GeometryCleanup => self.geometry_cleanup.show = true, PanelId::BricscadVisibility => self.set_bricscad_visibility_panel(true), PanelId::SheetSetManager => self.show_sheet_set_manager(true), PanelId::Layers => { @@ -723,6 +724,7 @@ impl OpenCADStudio { self.count_palette.show = false; self.ribbon.set_count_palette(false); } + PanelId::GeometryCleanup => self.geometry_cleanup.show = false, PanelId::BricscadVisibility => self.bricscad_visibility.show = false, PanelId::SheetSetManager => { self.sheet_set.show = false; @@ -875,6 +877,7 @@ impl OpenCADStudio { PanelId::NodeGraph => self.show_node_graph, PanelId::PointCloudManager => self.pc_manager.show, PanelId::Count => self.count_palette.show, + PanelId::GeometryCleanup => self.geometry_cleanup.show, PanelId::BricscadVisibility => self.bricscad_visibility.show, PanelId::SheetSetManager => self.sheet_set.show, PanelId::Layers => self.show_layers, diff --git a/src/app/dock/view.rs b/src/app/dock/view.rs index 21324d7bed..5b84578e89 100644 --- a/src/app/dock/view.rs +++ b/src/app/dock/view.rs @@ -731,6 +731,12 @@ impl OpenCADStudio { width, chrome, ), + crate::ui::dock::PanelId::GeometryCleanup => crate::ui::window::geometry_cleanup::view( + &self.geometry_cleanup, + tab.id, + width, + chrome, + ), crate::ui::dock::PanelId::PointCloudManager => crate::ui::window::pc_manager::view( &self.pc_manager, &tab.scene.document, diff --git a/src/app/message.rs b/src/app/message.rs index c7fb3192ae..790a00b31d 100644 --- a/src/app/message.rs +++ b/src/app/message.rs @@ -2699,6 +2699,8 @@ pub enum Message { /// A click or search in the Point Cloud Manager. PcManager(crate::ui::window::pc_manager::PcManagerMsg), Count(crate::ui::window::count_palette::CountMsg), + /// The Geometry Cleanup palette. + GeometryCleanup(crate::ui::window::geometry_cleanup::GeometryCleanupMsg), /// The Visibility States palette of a BricsCAD parametric block. BricscadVisibility(crate::ui::window::bricscad_visibility::VisMsg), /// The LayerWalk pallet (LAYWALK). diff --git a/src/app/mod.rs b/src/app/mod.rs index ffc84ae2bf..c3835e4f37 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1465,6 +1465,8 @@ pub(super) struct OpenCADStudio { /// Point Cloud Manager palette (POINTCLOUDMANAGER). pub(crate) pc_manager: crate::ui::window::pc_manager::PcManager, pub(crate) count_palette: crate::ui::window::count_palette::CountPalette, + /// The Geometry Cleanup palette (GEOMETRYCLEANUPOPEN). + pub(crate) geometry_cleanup: crate::ui::window::geometry_cleanup::GeometryCleanupPalette, pub(crate) bricscad_visibility: crate::ui::window::bricscad_visibility::VisibilityPanel, /// The QuickCalc pallet (QUICKCALC / QC). pub(crate) quick_calc: crate::ui::window::quick_calc::QuickCalcPalette, @@ -3198,6 +3200,7 @@ impl OpenCADStudio { show_browser: false, pc_manager: Default::default(), count_palette: Default::default(), + geometry_cleanup: Default::default(), bricscad_visibility: Default::default(), quick_calc: Default::default(), assistant: Default::default(), diff --git a/src/app/update/dispatch.rs b/src/app/update/dispatch.rs index 5794c166da..1de391eb28 100644 --- a/src/app/update/dispatch.rs +++ b/src/app/update/dispatch.rs @@ -1943,6 +1943,7 @@ impl OpenCADStudio { Message::PdfShxDialog(message) => self.update_pdf_shx_dialog(message), Message::PcManager(message) => self.update_pc_manager(message), Message::Count(message) => self.on_count(message), + Message::GeometryCleanup(message) => self.on_geometry_cleanup(message), Message::BricscadVisibility(message) => self.on_bricscad_visibility(message), Message::Laywalk(message) => self.on_layer_walk(message), Message::QuickCalc(message) => self.on_quick_calc(message), diff --git a/src/app/update/mod.rs b/src/app/update/mod.rs index 257937733c..aeef9603fd 100644 --- a/src/app/update/mod.rs +++ b/src/app/update/mod.rs @@ -1279,6 +1279,8 @@ impl OpenCADStudio { self.refresh_xref_manager_if_stale(); // Count mode recolours its references after the drawing changes. self.refresh_count_if_stale(); + // The Geometry Cleanup palette scans its objects again. + self.refresh_geometry_cleanup_if_stale(); // Let V4 plugins observe selection changes that happened while handling // this message (picking, window select, QSELECT, SELECTALL, grip edits, // and plugin request draining). diff --git a/src/locale_catalog.rs b/src/locale_catalog.rs index ff04649857..bec3d0a74c 100644 --- a/src/locale_catalog.rs +++ b/src/locale_catalog.rs @@ -3568,6 +3568,22 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static "OVERKILL: {} object(s) checked, no duplicates found." => Some(("manage", "overkill-checked-no-duplicates")), "OVERKILL: {} object(s) checked, {} removed, {} modified." => Some(("manage", "overkill-checked-removed-modified")), "Overkill" => Some(("manage", "overkill")), + "Geometry Cleanup" => Some(("manage", "geometry-cleanup")), + "This error cannot be fixed that way." => Some(("manage", "geometry-cleanup-cannot-fix")), + "Select objects to find gaps, overshoots and undershoots." => Some(("manage", "geometry-cleanup-empty")), + "The error is no longer in the drawing." => Some(("manage", "geometry-cleanup-error-gone")), + "Geometry Cleanup: {} error(s) found." => Some(("manage", "geometry-cleanup-found")), + "No errors found." => Some(("manage", "geometry-cleanup-no-errors")), + "Overshoot" => Some(("manage", "geometry-cleanup-overshoot")), + "Remaining Errors: {}" => Some(("manage", "geometry-cleanup-remaining")), + "Rescan" => Some(("manage", "geometry-cleanup-rescan")), + "Lengthen the end along its own line or arc to the object it stops short of." => Some(("manage", "geometry-cleanup-tip-extend")), + "Lengthen both ends along their own lines to the corner where they meet." => Some(("manage", "geometry-cleanup-tip-extend-both")), + "Move the whole object so that its end meets the other end." => Some(("manage", "geometry-cleanup-tip-move")), + "Move only this end onto the other end. The rest of the object stays." => Some(("manage", "geometry-cleanup-tip-stretch")), + "Cut the end back to the object it crosses." => Some(("manage", "geometry-cleanup-tip-trim")), + "Tolerance: {}" => Some(("manage", "geometry-cleanup-tolerance")), + "Undershoot" => Some(("manage", "geometry-cleanup-undershoot")), "Override Center X" => Some(("properties", "override-center-x")), "Override Center Y" => Some(("properties", "override-center-y")), "Override Center Z" => Some(("properties", "override-center-z")), diff --git a/src/modules/manage/geometry_cleanup.rs b/src/modules/manage/geometry_cleanup.rs new file mode 100644 index 0000000000..5489f11b24 --- /dev/null +++ b/src/modules/manage/geometry_cleanup.rs @@ -0,0 +1,196 @@ +//! Geometry Cleanup (GEOMETRYCLEANUPOPEN): the objects it reads, and the +//! edits that repair an end. The scan itself is +//! `ocs_geom::geom2d::cleanup`; the palette is `ui::window::geometry_cleanup`. + +use document::types::Vector3; +use document::{Document, EntityType, Handle}; +use glam::DVec3; +use ocs_geom::geom2d::Curve; + +use crate::command::{CadCommand, CmdResult}; +use crate::entities::traits::EntityTypeOps; +use crate::entities::transform::EntityTransform; +use crate::modules::{IconKind, ModuleEvent, ToolDef}; + +pub const ICON: IconKind = + IconKind::Svg(include_bytes!("../../../assets/icons/geometry_cleanup.svg")); + +pub fn tool() -> ToolDef { + ToolDef { + id: "GEOMETRYCLEANUPOPEN", + label: "Geometry Cleanup", + icon: ICON, + event: ModuleEvent::Command("GEOMETRYCLEANUPOPEN".to_string()), + } +} + +inventory::submit!(crate::command::CommandRegistration { + names: &["GEOMETRYCLEANUPOPEN", "GEOMETRYCLEANUPCLOSE"] +}); + +/// Nearer than this to zero counts as zero: a Z, an elevation, the X and Y +/// of a normal. +const FLAT: f64 = 1e-9; + +fn on_xy(v: Vector3) -> bool { + v.z.abs() <= FLAT +} + +fn up(normal: Vector3) -> bool { + normal.x.abs() <= FLAT && normal.y.abs() <= FLAT && normal.z > 0.0 +} + +/// The curve that Geometry Cleanup reads for an entity: a line, an arc or a +/// LWPOLYLINE that lies on the world XY plane. `None` for anything else. +pub fn cleanup_curve(entity: &EntityType) -> Option { + match entity { + EntityType::Line(line) if on_xy(line.start) && on_xy(line.end) => { + Some(Curve::Line(ocs_geom::geom2d::Line { + start: [line.start.x, line.start.y], + end: [line.end.x, line.end.y], + })) + } + EntityType::Arc(arc) if up(arc.normal) && on_xy(arc.center) => { + Some(crate::entities::curve::arc_curve(arc).curve) + } + EntityType::LwPolyline(polyline) + if up(polyline.normal) && polyline.elevation.abs() <= FLAT => + { + crate::entities::curve::lwpolyline_curve(polyline).map(|curve| curve.curve) + } + _ => None, + } +} + +/// Whether Geometry Cleanup may read and change `handle`: a supported curve +/// in model space, on a layer that is not locked or frozen. +pub fn is_candidate(document: &Document, handle: Handle) -> bool { + let Some(entity) = document.get_entity(handle) else { + return false; + }; + let model = document.block_records.get("*Model_Space").map(|r| r.handle); + let layer_ok = document + .layers + .get(&entity.common().layer) + .is_none_or(|layer| !layer.is_locked() && !layer.is_frozen()); + model == Some(entity.common().owner_handle) && layer_ok && cleanup_curve(entity).is_some() +} + +/// `entity` with the end at its start (`at_start`) or its end moved to +/// `to` along its own line or circle: the Trim and Extend repairs. `to` is +/// a point on that line or circle. +pub fn moved_along(entity: &EntityType, at_start: bool, to: [f64; 2]) -> Option { + let mut result = entity.clone(); + match &mut result { + EntityType::Line(line) => { + let point = if at_start { + &mut line.start + } else { + &mut line.end + }; + point.x = to[0]; + point.y = to[1]; + } + EntityType::Arc(arc) => { + let angle = (to[1] - arc.center.y).atan2(to[0] - arc.center.x); + if at_start { + arc.start_angle = angle; + } else { + arc.end_angle = angle; + } + } + EntityType::LwPolyline(polyline) => { + let n = polyline.vertices.len(); + if n < 2 { + return None; + } + // The end vertex and the segment it ends. + let (vertex, segment) = if at_start { (0, 0) } else { (n - 1, n - 2) }; + let from = polyline.vertices[segment].location; + let next = polyline.vertices[segment + 1].location; + let bulge = polyline.vertices[segment].bulge; + if let Some(arc) = + ocs_geom::geom2d::BulgeArc::from_bulge([from.x, from.y], [next.x, next.y], bulge) + { + // Keep the circle: the moved end goes round it the same way. + let angle = |p: [f64; 2]| (p[1] - arc.center[1]).atan2(p[0] - arc.center[0]); + let (a, b) = if at_start { + (angle(to), arc.end_angle) + } else { + (arc.start_angle, angle(to)) + }; + let turn = arc.sweep.signum(); + let sweep = turn * (turn * (b - a)).rem_euclid(std::f64::consts::TAU); + if sweep.abs() <= FLAT { + return None; + } + polyline.vertices[segment].bulge = (sweep / 4.0).tan(); + } + polyline.vertices[vertex].location.x = to[0]; + polyline.vertices[vertex].location.y = to[1]; + } + _ => return None, + } + Some(result) +} + +/// `entity` with its end grip at the start or the end moved to `to`: the +/// Stretch repair, which does what a drag of that grip does. +pub fn stretched(entity: &EntityType, at_start: bool, to: [f64; 2]) -> Option { + let curve = cleanup_curve(entity)?; + let end = curve.point_at(if at_start { 0.0 } else { 1.0 }); + let grip = EntityTypeOps::grips(entity) + .into_iter() + .filter(|grip| !grip.is_midpoint) + .min_by(|a, b| { + let d = |g: &crate::scene::model::object::GripDef| { + (g.world.x - end[0]).hypot(g.world.y - end[1]) + }; + d(a).total_cmp(&d(b)) + })?; + let mut result = entity.clone(); + EntityTypeOps::apply_grip( + &mut result, + grip.id, + crate::scene::model::object::GripApply::Absolute(DVec3::new(to[0], to[1], 0.0)), + ); + Some(result) +} + +/// `entity` moved by `by`: the Move repair. +pub fn moved(entity: &EntityType, by: [f64; 2]) -> EntityType { + let mut result = entity.clone(); + EntityTypeOps::apply_transform( + &mut result, + &EntityTransform::Translate(DVec3::new(by[0], by[1], 0.0)), + ); + result +} + +/// "Select objects" in the palette: a selection, then the scan. +pub struct SelectObjects; + +impl CadCommand for SelectObjects { + fn name(&self) -> &'static str { + "GEOMETRYCLEANUPOPEN" + } + fn prompt(&self) -> String { + "Select objects:".into() + } + fn is_selection_gathering(&self) -> bool { + true + } + fn on_selection_complete(&mut self, handles: Vec) -> CmdResult { + if handles.is_empty() { + return CmdResult::Cancel; + } + let list: Vec = handles.iter().map(|h| format!("{:X}", h.value())).collect(); + CmdResult::Dispatch(format!("_GEOMETRYCLEANUPSCAN {}", list.join(","))) + } + fn on_point(&mut self, _: DVec3) -> CmdResult { + CmdResult::NeedPoint + } + fn on_enter(&mut self) -> CmdResult { + CmdResult::Cancel + } +} diff --git a/src/modules/manage/mod.rs b/src/modules/manage/mod.rs index 8024bb3b88..e198f7160e 100644 --- a/src/modules/manage/mod.rs +++ b/src/modules/manage/mod.rs @@ -7,6 +7,7 @@ pub mod gapcheck; mod cui_export; mod cui_import; mod find_nonpurgeable; +pub mod geometry_cleanup; mod options; mod overkill; mod purge; @@ -75,6 +76,7 @@ impl CadModule for ManageModule { RibbonItem::LargeTool(find_nonpurgeable::tool()), RibbonItem::Tool(purge::tool()), RibbonItem::Tool(overkill::tool()), + RibbonItem::Tool(geometry_cleanup::tool()), RibbonItem::Tool(audit::tool()), ], }, diff --git a/src/modules/registry.rs b/src/modules/registry.rs index a69deee277..6ce2bfcfda 100644 --- a/src/modules/registry.rs +++ b/src/modules/registry.rs @@ -216,6 +216,7 @@ const COMMAND_ICON_ALIASES: &[(&str, &str)] = &[ ("COUNT", "COUNTLIST"), ("COUNTPALETTE", "COUNTLIST"), ("COUNTCLOSE", "COUNTLIST"), + ("GEOMETRYCLEANUPCLOSE", "GEOMETRYCLEANUPOPEN"), ("-SCALELISTEDIT", "SCALELISTEDIT"), ("ANNOUPDATE", "SCALELISTEDIT"), ("ANNORESET", "SCALELISTEDIT"), diff --git a/src/ui/dock.rs b/src/ui/dock.rs index ec458c5d15..a53397cb4d 100644 --- a/src/ui/dock.rs +++ b/src/ui/dock.rs @@ -133,6 +133,8 @@ pub enum PanelId { PointCloudManager, /// Block counts (COUNTLIST). Count, + /// Gaps, overshoots and undershoots (GEOMETRYCLEANUPOPEN). + GeometryCleanup, /// Visibility states of a BricsCAD parametric block (VISIBILITYSTATESPANELOPEN). BricscadVisibility, /// The open sheet sets: subsets and sheets. @@ -153,7 +155,7 @@ pub enum PanelId { impl PanelId { /// Every panel, in the order the pallet menu lists them. - pub const ALL: [PanelId; 18] = [ + pub const ALL: [PanelId; 19] = [ PanelId::Properties, PanelId::GraphicAttributes, PanelId::BlockPalette, @@ -165,6 +167,7 @@ impl PanelId { PanelId::NodeGraph, PanelId::PointCloudManager, PanelId::Count, + PanelId::GeometryCleanup, PanelId::BricscadVisibility, PanelId::SheetSetManager, PanelId::Layers, @@ -188,6 +191,7 @@ impl PanelId { PanelId::NodeGraph => "Node Graph", PanelId::PointCloudManager => "Point Cloud Manager", PanelId::Count => "Count", + PanelId::GeometryCleanup => "Geometry Cleanup", PanelId::BricscadVisibility => "Visibility States", PanelId::SheetSetManager => "Sheet Set Manager", PanelId::Layers => "Layer Manager", @@ -215,6 +219,7 @@ impl PanelId { PanelId::NodeGraph => crate::ui::icons::NODE_GRAPH, PanelId::PointCloudManager => include_bytes!("../../assets/icons/pc_attach.svg"), PanelId::Count => include_bytes!("../../assets/icons/data_extract.svg"), + PanelId::GeometryCleanup => crate::ui::window::geometry_cleanup::ICON, PanelId::BricscadVisibility => include_bytes!("../../assets/icons/ui/eye.svg"), PanelId::SheetSetManager => include_bytes!("../../assets/icons/sheetset.svg"), PanelId::Layers => include_bytes!("../../assets/icons/layers/panel.svg"), @@ -240,6 +245,7 @@ impl PanelId { PanelId::NodeGraph => 220.0, PanelId::PointCloudManager => 280.0, PanelId::Count => 280.0, + PanelId::GeometryCleanup => 280.0, PanelId::BricscadVisibility => 280.0, PanelId::SheetSetManager => 280.0, PanelId::Layers => 560.0, diff --git a/src/ui/window/geometry_cleanup.rs b/src/ui/window/geometry_cleanup.rs new file mode 100644 index 0000000000..a803a516ba --- /dev/null +++ b/src/ui/window/geometry_cleanup.rs @@ -0,0 +1,282 @@ +//! The Geometry Cleanup palette (GEOMETRYCLEANUPOPEN): the errors that a +//! scan of the selected objects found, by type, with the repairs of the one +//! that is picked. The scan is `ocs_geom::geom2d::cleanup`; the handlers are +//! in `app::commands::geometry_cleanup`. + +use crate::app::Message; +use crate::ui::dock::PanelId; +use crate::ui::kit; +use crate::ui::style::kit_metrics as km; +use document::Handle; +use iced::widget::{button, column, container, row, text, Space}; +use iced::{Element, Fill, Padding}; +use ocs_geom::geom2d::cleanup::EndErrorKind; + +pub const ICON: &[u8] = include_bytes!("../../../assets/icons/geometry_cleanup.svg"); + +/// The error types, in the order of the tree. +pub const KINDS: [EndErrorKind; 3] = [ + EndErrorKind::Gap, + EndErrorKind::Overshoot, + EndErrorKind::Undershoot, +]; + +pub fn kind_label(kind: EndErrorKind) -> &'static str { + match kind { + EndErrorKind::Gap => "Gap", + EndErrorKind::Overshoot => "Overshoot", + EndErrorKind::Undershoot => "Undershoot", + } +} + +/// A repair of one error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Fix { + /// Cut the end back to the crossing (an overshoot). + Trim, + /// Run the end on to what it falls short of (an undershoot). + Extend, + /// Move only the end onto the other end (a gap). + Stretch, + /// Move the whole object so that its end meets the other end (a gap). + Move, + /// Run both ends on to where their lines cross (a gap at a corner). + ExtendBoth, +} + +impl Fix { + /// What the repair changes, for its tooltip. + pub fn tip(self) -> &'static str { + match self { + Fix::Trim => "Cut the end back to the object it crosses.", + Fix::Extend => { + "Lengthen the end along its own line or arc to the object it stops short of." + } + Fix::Stretch => "Move only this end onto the other end. The rest of the object stays.", + Fix::Move => "Move the whole object so that its end meets the other end.", + Fix::ExtendBoth => { + "Lengthen both ends along their own lines to the corner where they meet." + } + } + } + + pub fn label(self) -> &'static str { + match self { + Fix::Trim => "Trim", + Fix::Extend | Fix::ExtendBoth => "Extend", + Fix::Stretch => "Stretch", + Fix::Move => "Move", + } + } +} + +/// One error of a scan, with the objects in place of curve indices. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Finding { + pub kind: EndErrorKind, + pub handle: Handle, + pub at_start: bool, + pub location: [f64; 2], + pub target: [f64; 2], + /// A gap's other end. + pub other: Option<(Handle, bool)>, + /// A gap's corner, for Extend. + pub corner: Option<[f64; 2]>, + pub deviation: f64, +} + +impl Finding { + /// Whether `other` is the same error: the same type at the same end. + pub fn same_error(&self, other: &Finding) -> bool { + self.kind == other.kind && self.handle == other.handle && self.at_start == other.at_start + } + + /// The repairs that this error offers. + pub fn fixes(&self) -> Vec { + match self.kind { + EndErrorKind::Overshoot => vec![Fix::Trim], + EndErrorKind::Undershoot => vec![Fix::Extend], + EndErrorKind::Gap => { + let mut fixes = Vec::new(); + if self.corner.is_some() { + fixes.push(Fix::ExtendBoth); + } + fixes.push(Fix::Stretch); + // Moving a polyline so that one end meets its other end + // cannot close it. + if self.other.is_some_and(|(other, _)| other != self.handle) { + fixes.push(Fix::Move); + } + fixes + } + } + } +} + +/// The result of the last scan. +#[derive(Debug, Clone, Default)] +pub struct Scan { + /// The drawing tab that was scanned. + pub tab: u64, + /// Its geometry epoch at the scan: the palette scans again when the + /// drawing has changed since. + pub epoch: u64, + /// The objects that were selected for the scan. + pub objects: Vec, + pub tolerance: f64, + pub findings: Vec, +} + +#[derive(Debug, Default)] +pub struct GeometryCleanupPalette { + pub show: bool, + pub scan: Option, + /// The index in the scan's findings of the picked error. + pub picked: Option, + /// The error types whose list is folded. + pub folded: Vec, +} + +#[derive(Debug, Clone)] +pub enum GeometryCleanupMsg { + SelectObjects, + Rescan, + /// Pick an error: zoom to it and show its repairs. + Pick(usize), + Fix(usize, Fix), + Fold(EndErrorKind), +} + +/// The errors of a scan by type, in the order of the tree: each type with +/// the indices of its errors in `scan.findings`. Types with no error are +/// left out. +pub fn groups(scan: &Scan) -> Vec<(EndErrorKind, Vec)> { + KINDS + .into_iter() + .map(|kind| { + let indices = (0..scan.findings.len()) + .filter(|&index| scan.findings[index].kind == kind) + .collect::>(); + (kind, indices) + }) + .filter(|(_, indices)| !indices.is_empty()) + .collect() +} + +/// The rows that the palette shows, top to bottom: the errors of the types +/// that are not folded. +pub fn rows(palette: &GeometryCleanupPalette, scan: &Scan) -> Vec { + groups(scan) + .into_iter() + .filter(|(kind, _)| !palette.folded.contains(kind)) + .flat_map(|(_, indices)| indices) + .collect() +} + +fn msg(m: GeometryCleanupMsg) -> Message { + Message::GeometryCleanup(m) +} + +fn coordinates(p: [f64; 2]) -> String { + format!("{:.4}, {:.4}", p[0], p[1]) +} + +pub fn view<'a>( + palette: &'a GeometryCleanupPalette, + tab: u64, + width: f32, + chrome: crate::ui::dock::Chrome, +) -> Element<'a, Message> { + let title_bar = crate::ui::dock::title_bar( + PanelId::GeometryCleanup, + crate::t!("Geometry Cleanup").into_owned(), + chrome, + ); + let scan = palette.scan.as_ref().filter(|scan| scan.tab == tab); + let tools = row![ + kit::text_button( + crate::t!("Select Objects").into_owned(), + Some(msg(GeometryCleanupMsg::SelectObjects)), + scan.is_none(), + ), + kit::text_button( + crate::t!("Rescan").into_owned(), + scan.map(|_| msg(GeometryCleanupMsg::Rescan)), + false, + ), + Space::new().width(Fill), + ] + .spacing(km::TOOL_GAP) + .align_y(iced::Center); + + let Some(scan) = scan else { + return kit::palette( + title_bar, + column![ + kit::band(tools), + kit::empty_state(crate::t!( + "Select objects to find gaps, overshoots and undershoots." + )), + ], + width, + ); + }; + + let mut list = column![]; + if scan.findings.is_empty() { + list = list.push(kit::empty_state(crate::t!("No errors found."))); + } else { + list = list.push(kit::name_text( + crate::tf!("Remaining Errors: {}", scan.findings.len()).into_owned(), + )); + } + for (kind, indices) in groups(scan) { + let folded = palette.folded.contains(&kind); + list = list.push(kit::category_bar( + format!("{}: {}", crate::t!(kind_label(kind)), indices.len()), + folded, + msg(GeometryCleanupMsg::Fold(kind)), + )); + if folded { + continue; + } + for index in indices { + let finding = &scan.findings[index]; + list = list.push( + kit::tree_row(coordinates(finding.location)) + .depth(1) + .selected(palette.picked == Some(index)) + .trailing(fix_buttons(index, finding)) + .on_press(msg(GeometryCleanupMsg::Pick(index))) + .view(), + ); + } + } + + let body = column![ + kit::band(tools), + kit::name_text(crate::tf!("Tolerance: {}", scan.tolerance).into_owned()), + container(kit::scroll_area(list)).height(Fill), + ]; + kit::palette(title_bar, body, width) +} + +/// The repairs of one error, at the end of its row. +fn fix_buttons<'a>(index: usize, finding: &Finding) -> Element<'a, Message> { + let mut fixes = row![].spacing(km::TOOL_GAP / 2.0).align_y(iced::Center); + for fix in finding.fixes() { + let press = button( + text(crate::t!(fix.label()).into_owned()).size(crate::ui::style::text::UI_SMALL), + ) + .padding(Padding::from([0, 4])) + .height(km::ROW_H - 2.0) + .style(kit::text_button_style(false)) + .on_press(msg(GeometryCleanupMsg::Fix(index, fix))); + fixes = fixes.push(kit::tooltip( + press, + crate::t!(fix.tip()).into_owned(), + kit::TipPosition::Bottom, + )); + } + fixes.into() +} diff --git a/src/ui/window/mod.rs b/src/ui/window/mod.rs index d9bead8e92..ef09480280 100644 --- a/src/ui/window/mod.rs +++ b/src/ui/window/mod.rs @@ -31,6 +31,7 @@ pub mod field_dialog; pub mod find_replace; pub mod geographic_location; pub mod geometric_tolerance; +pub mod geometry_cleanup; pub mod gradient_editor; pub mod graphic_attributes; pub mod hatch_dialogs;