Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

24.0 KB
Raw Blame
//! Associative offsets keep their output entity ids while their source curves move.
use crate::{ConstraintKind, CurveKind, Shape, Sketch, SketchError, intersections};
use serde::{Deserialize, Serialize};
use solidcore_record::Vec2;
use solidcraft_geom::prelude::*;

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OffsetChain {
    pub sources: Vec<(String, bool)>,
    pub outputs: Vec<String>,
    pub distance: f64,
    pub closed: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub topology: Option<crate::offset_topology::OffsetTopology>,
}

impl OffsetChain {
    /// Includes reserved corner roles that may temporarily disappear from the boundary.
    pub fn owns_output(&self, output: &str) -> bool {
        self.outputs.iter().any(|id| id == output) || self.topology.as_ref().is_some_and(|t| t.roles.iter().any(|r| r.output == output))
    }
}

impl Sketch {
    /// The signed distance of the association that owns an output (including retired roles).
    pub fn offset_distance(&self, output: &str) -> Option<f64> {
        self.offsets
            .iter()
            .find(|o| o.owns_output(output))
            .map(|o| o.distance)
            .or_else(|| self.freeform_offsets.iter().find(|o| o.output == output).map(|o| o.distance))
    }

    /// A Parallel between an offset line and the source it follows (#4464). The association
    /// keeps them parallel already, and the output's points are held during a solve, so solving
    /// it would only pin the source to the output's current direction. It drives again once
    /// Break releases the output.
    pub(crate) fn follows_its_source(&self, kind: &ConstraintKind) -> bool {
        let ConstraintKind::Parallel { a, b } = *kind else {
            return false;
        };
        let (Some(a), Some(b)) = (self.curves.get(a).map(|c| c.id.as_str()), self.curves.get(b).map(|c| c.id.as_str())) else {
            return false;
        };
        self.offsets.iter().any(|o| {
            o.sources.iter().enumerate().any(|(i, (source, _))| {
                let output = match &o.topology {
                    Some(t) => t.roles.get(i).map(|r| r.output.as_str()),
                    None => o.outputs.get(i).map(String::as_str),
                };
                output.is_some_and(|output| (source == a && output == b) || (source == b && output == a))
            })
        })
    }

    /// An arc an offset made round its source's own centre (#6569). Its ends are held while the
    /// sketch solves, so its own condition, both ends as far from the centre, only tied that
    /// centre (and the source with it) to the middle of the held ends: a slot offset by 1 mm
    /// could no longer be moved by the dimension that places it. The source's own arc keeps the
    /// centre, and the offset is rebuilt from the source after the solve.
    pub(crate) fn offset_arc_follows_source(&self, curve: usize) -> bool {
        if self.offsets.is_empty() {
            return false;
        }
        let Some(arc) = self.curves.get(curve) else { return false };
        let CurveKind::Arc { c: centre, .. } = arc.kind else { return false };
        let output = |id: &str| self.offsets.iter().any(|o| o.owns_output(id));
        output(&arc.id) && self.curves.iter().enumerate().any(|(k, other)| k != curve && other.kind.uses(centre) && !output(&other.id))
    }

    /// A circle an offset made (#9264). The offset sets its radius from the source's after the
    /// solve, so the solve holds that radius instead of counting it as a free unknown.
    pub(crate) fn offset_circle_follows_source(&self, curve: usize) -> bool {
        let Some(circle) = self.curves.get(curve) else { return false };
        matches!(circle.kind, CurveKind::Circle { .. }) && self.offsets.iter().any(|o| o.owns_output(&circle.id))
    }

    /// Endpoints of a normal-distance annotation, evaluated from its source curve.
    pub fn offset_dimension_points(&self, output: &str) -> Option<(Vec2, Vec2)> {
        let (source, forward, distance) = self
            .offsets
            .iter()
            .find(|o| o.owns_output(output))
            .and_then(|o| o.sources.first().map(|(id, forward)| (id.as_str(), *forward, o.distance)))
            .or_else(|| self.freeform_offsets.iter().find(|o| o.output == output).map(|o| (o.source.as_str(), o.forward, o.distance)))?;
        let index = self.curve_index(source)?;
        let segment = self.exact_segs(index).unwrap_or_else(|| self.segs(index)).into_iter().next()?;
        let p = segment.point_at(0.5);
        let tangent = (segment.point_at(0.5001) - segment.point_at(0.4999)).normalized()?;
        Some((p, p + tangent.perp() * if forward { distance } else { -distance }))
    }
    /// Removing an output removes its relationship. A partial analytic chain
    /// deletion releases the surviving outputs, while retained dependents keep
    /// their source references so the command's refresh refuses broken sources.
    pub(crate) fn prune_offsets_for_removed_curves(&mut self, which: &[usize]) {
        let removed = which.iter().filter_map(|i| self.curves.get(*i).map(|curve| curve.id.clone())).collect::<std::collections::BTreeSet<_>>();
        if removed.is_empty() {
            return;
        }
        let released = self
            .offsets
            .iter()
            .filter(|offset| offset.outputs.iter().any(|id| removed.contains(id)))
            .flat_map(|offset| offset.outputs.iter().cloned().chain(offset.topology.iter().flat_map(|t| t.roles.iter().map(|r| r.output.clone()))))
            .chain(self.freeform_offsets.iter().filter(|offset| removed.contains(&offset.output)).map(|offset| offset.output.clone()))
            .collect::<std::collections::BTreeSet<_>>();
        self.offsets.retain(|offset| !offset.outputs.iter().any(|id| removed.contains(id)));
        self.freeform_offsets.retain(|offset| !removed.contains(&offset.output));
        self.constraints.retain(|c| !matches!(&c.kind, ConstraintKind::OffsetDistance { output, .. } if released.contains(output)));
        let points = self
            .curves
            .iter()
            .filter(|curve| released.contains(&curve.id))
            .flat_map(|curve| curve.kind.point_ids())
            .collect::<std::collections::BTreeSet<_>>();
        for index in points {
            if index != 0
                && self.curves.iter().all(|curve| !curve.kind.uses(index) || released.contains(&curve.id))
                && let Some(point) = self.points.get_mut(index)
            {
                point.fixed = false;
            }
        }
    }

    /// Retry a failed solve whose source edit was blocked by attachments to an offset's old
    /// fixed points. Seed the sources without those attachments, rebuild the offsets, then
    /// solve every attachment with the sources held. Nothing is adopted unless the complete
    /// sketch solves with its original constraints and orientation.
    pub fn solve_after_offset_edit(
        &mut self,
        old: &crate::DrivingValues,
        reference: Option<&[Vec2]>,
        analysis: crate::Analysis,
    ) -> Option<crate::SolveReport> {
        let source =
            |id: &str| self.offsets.iter().any(|o| o.sources.iter().any(|(s, _)| s == id)) || self.freeform_offsets.iter().any(|o| o.source == id);
        let output = |id: &str| self.offsets.iter().any(|o| o.owns_output(id)) || self.freeform_offsets.iter().any(|o| o.output == id);
        let source_points: std::collections::BTreeSet<usize> =
            self.curves.iter().filter(|c| source(&c.id)).flat_map(|c| c.kind.point_ids()).collect();
        let outputs: std::collections::BTreeSet<usize> = self.curves.iter().enumerate().filter(|(_, c)| output(&c.id)).map(|(i, _)| i).collect();
        let output_points: std::collections::BTreeSet<usize> =
            outputs.iter().filter_map(|i| self.curves.get(*i)).flat_map(|c| c.kind.point_ids()).filter(|p| !source_points.contains(p)).collect();
        let mut candidate = self.clone();
        candidate.constraints.retain(|c| {
            !c.kind.indices().1.iter().any(|i| outputs.contains(i)) && !self.constraint_points(&c.kind).iter().any(|p| output_points.contains(p))
        });
        if candidate.constraints.len() == self.constraints.len() {
            return None;
        }
        let before: Vec<Vec2> = reference.map_or_else(|| self.points.iter().map(|p| p.pos).collect(), <[Vec2]>::to_vec);
        if !crate::solve_after_edit_with_analysis(&mut candidate, old, Some(&before), crate::Analysis::StatusOnly).keeps_orientation() {
            return None;
        }
        candidate.constraints.clone_from(&self.constraints);
        candidate.refresh_offsets().ok()?;
        // Keep the freshly rebuilt offset exact while its attached geometry catches up.
        // Refresh may retire output curves or refine a dependent spline: resolve holds again.
        let hold = crate::Hold {
            points: candidate.curves.iter().filter(|c| source(&c.id)).flat_map(|c| c.kind.point_ids()).collect(),
            radii: candidate.curves.iter().enumerate().filter(|(_, c)| source(&c.id) || output(&c.id)).map(|(i, _)| i).collect(),
        };
        if !crate::solve_with(&mut candidate, &hold, Some(&before), crate::Analysis::StatusOnly, None).keeps_orientation() {
            // A cap tangent to an arc can land on the other tangency branch after a large
            // jump. Walk the held source and output points from their stored positions.
            // Their own dimensions are restored after the walk, not imposed at each step.
            let mut walking = candidate.clone();
            walking.constraints.retain(|c| candidate.constraint_points(&c.kind).iter().any(|p| !hold.points.contains(p)));
            for i in &hold.points {
                if let Some(p) = walking.points.get_mut(*i) {
                    p.fixed = true;
                }
            }
            for i in &hold.radii {
                if let Some(c) = walking.curves.get_mut(*i) {
                    c.fixed = true;
                }
            }
            let mut from = walking.clone();
            for (p, pos) in from.points.iter_mut().zip(&before) {
                p.pos = *pos;
            }
            crate::solve_after_link_move(&mut walking, &from, old, crate::Analysis::StatusOnly)?;
            for (p, q) in candidate.points.iter_mut().zip(&walking.points) {
                p.pos = q.pos;
            }
            for (c, d) in candidate.curves.iter_mut().zip(&walking.curves) {
                c.kind.clone_from(&d.kind);
            }
        }
        // Publish ordinary freedom/redundancy diagnostics, without the temporary holds.
        let report = crate::solve_after_edit_with_analysis(&mut candidate, old, Some(&before), analysis);
        if !report.keeps_orientation() {
            return None;
        }
        *self = candidate;
        Some(report)
    }

    pub fn refresh_offsets(&mut self) -> Result<(), SketchError> {
        if self.offsets.is_empty() && self.freeform_offsets.is_empty() {
            return Ok(());
        }
        let mut candidate = self.clone();
        let mut driven = std::collections::BTreeSet::new();
        for constraint in &self.constraints {
            if let ConstraintKind::OffsetDistance { output, value, reverse } = &constraint.kind {
                self.validate(&constraint.kind)?;
                let analytic = candidate.offsets.iter().position(|o| o.owns_output(output));
                let freeform = candidate.freeform_offsets.iter().position(|o| o.output == *output);
                let identity = analytic
                    .or_else(|| freeform.map(|i| candidate.offsets.len() + i))
                    .ok_or_else(|| SketchError::Invalid("missing offset dimension association".into()))?;
                if constraint.driven || !driven.insert(identity) {
                    return Err(SketchError::Invalid("an offset must have exactly one driving distance".into()));
                }
                let distance = if *reverse { -*value } else { *value };
                if let Some(offset) = analytic.and_then(|i| candidate.offsets.get_mut(i)) {
                    offset.distance = distance;
                }
                if let Some(offset) = freeform.and_then(|i| candidate.freeform_offsets.get_mut(i)) {
                    offset.distance = distance;
                }
            }
        }
        candidate.refresh_analytic_offsets()?;
        candidate.refresh_freeform_offsets()?;
        *self = candidate;
        Ok(())
    }

    fn refresh_analytic_offsets(&mut self) -> Result<(), SketchError> {
        for index in 0..self.offsets.len() {
            if self.refresh_convex_offset(index)? {
                continue;
            }
            let offset = self.offsets.get(index).cloned().ok_or_else(|| SketchError::Invalid("missing offset chain".into()))?;
            if offset.sources.len() != offset.outputs.len() || offset.sources.len() > 10_000 || !offset.distance.is_finite() {
                return Err(SketchError::Invalid("damaged offset chain".into()));
            }
            let bad = || SketchError::Invalid("an offset source vanished or changed shape".into());
            let mut pieces = Vec::new();
            let mut outline = Vec::new();
            for (id, forward) in &offset.sources {
                let i = self.curve_index(id).ok_or_else(bad)?;
                let kind = &self.curves.get(i).ok_or_else(bad)?.kind;
                let piece = match *kind {
                    CurveKind::Line { a, b } => {
                        let (a, b) = (self.point(a).ok_or_else(bad)?, self.point(b).ok_or_else(bad)?);
                        let (a, b) = if *forward { (a, b) } else { (b, a) };
                        outline.push((Shape::Line { a, b }, a, b, None));
                        let n = (b - a).normalized().ok_or_else(bad)?.perp() * offset.distance;
                        (Shape::Line { a: a + n, b: b + n }, a + n, b + n)
                    }
                    CurveKind::Arc { c, a, b } => {
                        let (c, a, b) = (self.point(c).ok_or_else(bad)?, self.point(a).ok_or_else(bad)?, self.point(b).ok_or_else(bad)?);
                        let start = (a - c).angle();
                        let sweep = ((b - c).angle() - start).rem_euclid(std::f64::consts::TAU);
                        outline.push((Shape::Round { c, r: c.dist(a), start, sweep }, a, b, Some(*forward)));
                        let r = c.dist(a) - if *forward { offset.distance } else { -offset.distance };
                        if r <= 1e-9 {
                            return Err(SketchError::Invalid("the offset collapses an arc".into()));
                        }
                        let a = c + (a - c).normalized().ok_or_else(bad)? * r;
                        let b = c + (b - c).normalized().ok_or_else(bad)? * r;
                        let (a, b) = if *forward { (a, b) } else { (b, a) };
                        (Shape::Round { c, r, start: 0.0, sweep: std::f64::consts::TAU }, a, b)
                    }
                    CurveKind::Circle { c, r } => {
                        let c = self.point(c).ok_or_else(bad)?;
                        let r = r - offset.distance;
                        if r <= 1e-9 {
                            return Err(SketchError::Invalid("the offset collapses a circle".into()));
                        }
                        let out = offset.outputs.first().and_then(|id| self.curve_index(id)).ok_or_else(bad)?;
                        if let Some(crate::Curve { kind: CurveKind::Circle { r: target, .. }, .. }) = self.curves.get_mut(out) {
                            *target = r;
                        } else {
                            return Err(bad());
                        }
                        let _ = c;
                        continue;
                    }
                    _ => return Err(bad()),
                };
                pieces.push(piece);
            }
            if pieces.is_empty() {
                continue;
            }
            // Which way a piece runs at `p`: a line along itself, an arc anticlockwise round its
            // centre when it follows its source forward.
            let along = |i: usize, piece: &(Shape, Vec2, Vec2), p: Vec2| match (&piece.0, outline.get(i).and_then(|o| o.3)) {
                (Shape::Line { a, b }, _) => *b - *a,
                (Shape::Round { c, .. }, Some(true)) => (p - *c).perp(),
                (Shape::Round { c, .. }, Some(false)) => (*c - p).perp(),
                _ => Vec2::new(0.0, 0.0),
            };
            let joint = |i: usize, j: usize| -> Result<Vec2, SketchError> {
                let (x, y) = (pieces.get(i).ok_or_else(bad)?, pieces.get(j).ok_or_else(bad)?);
                if x.2.dist(y.1) < 1e-6 {
                    return Ok(x.2);
                }
                let guess = (x.2 + y.1) * 0.5;
                let mut found = intersections(&x.0, &y.0);
                found.sort_by(|a, b| a.dist(guess).total_cmp(&b.dist(guess)));
                // Where the sources touch, as two tangent arcs do at a dog bone's notch (#10984),
                // both crossings are as far from the corner and rounding chose one. The pieces
                // overlap there: they meet where both are cut short, not where both run on and
                // cross into a loop.
                let cut_short = |p: Vec2| (p - x.2).dot(along(i, x, x.2)) < 0.0 && (p - y.1).dot(along(j, y, y.1)) > 0.0;
                match found.as_slice() {
                    [p, q, ..] if (q.dist(guess) - p.dist(guess)).abs() <= 1e-9 * (1.0 + p.dist(*q)) && !cut_short(*p) && cut_short(*q) => Ok(*q),
                    [p, ..] => Ok(*p),
                    [] => Err(SketchError::Invalid("the offset curves no longer meet".into())),
                }
            };
            let n = pieces.len();
            let mut joints = vec![if offset.closed { joint(n - 1, 0)? } else { pieces.first().ok_or_else(bad)?.1 }];
            for i in 0..n.saturating_sub(1) {
                joints.push(joint(i, i + 1)?);
            }
            if !offset.closed {
                joints.push(pieces.last().ok_or_else(bad)?.2);
            }
            if offset.closed && !crosses_itself(&outline, true) && crosses_itself(&cut_to_joints(&pieces, &outline, &joints), false) {
                return Err(SketchError::Invalid("the offset curves would cross".into()));
            }
            for (i, id) in offset.outputs.iter().enumerate() {
                let a = *joints.get(i).ok_or_else(bad)?;
                let b = *joints.get(if offset.closed { (i + 1) % n } else { i + 1 }).ok_or_else(bad)?;
                let shape = &pieces.get(i).ok_or_else(bad)?.0;
                if let Shape::Line { a: p, b: q } = shape
                    && (b - a).dot(*q - *p) <= 1e-9
                {
                    return Err(SketchError::Invalid("the offset curves would cross".into()));
                }
                let ci = self.curve_index(id).ok_or_else(bad)?;
                let kind = self.curves.get(ci).ok_or_else(bad)?.kind.clone();
                let (pa, pb) = match kind {
                    CurveKind::Line { a, b } => (a, b),
                    CurveKind::Arc { a, b, .. } => {
                        if offset.sources.get(i).is_some_and(|x| x.1) {
                            (a, b)
                        } else {
                            (b, a)
                        }
                    }
                    _ => return Err(bad()),
                };
                for (pi, pos) in [(pa, a), (pb, b)] {
                    if let Some(p) = self.points.get_mut(pi) {
                        p.pos = pos;
                        p.fixed = true;
                    }
                }
            }
        }
        Ok(())
    }
}

/// A piece of a closed outline: its shape, its two ends, and for an arc whether the chain follows
/// it forward.
type Outline = (Shape, Vec2, Vec2, Option<bool>);

/// The closed offset outline's pieces, each cut to its joints: a line between them, an arc
/// anticlockwise from one to the other the way its source runs (`outline`: anticlockwise when
/// followed forward).
fn cut_to_joints(pieces: &[(Shape, Vec2, Vec2)], outline: &[Outline], joints: &[Vec2]) -> Vec<Outline> {
    let n = pieces.len();
    (0..n)
        .filter_map(|i| {
            let (a, b) = (*joints.get(i)?, *joints.get((i + 1) % n)?);
            Some(match (pieces.get(i)?, outline.get(i)?.3) {
                ((Shape::Round { c, r, .. }, _, _), Some(ccw)) => {
                    let (from, to) = if ccw { (a, b) } else { (b, a) };
                    let start = (from - *c).angle();
                    (Shape::Round { c: *c, r: *r, start, sweep: ((to - *c).angle() - start).rem_euclid(std::f64::consts::TAU) }, a, b, Some(ccw))
                }
                _ => (Shape::Line { a, b }, a, b, None),
            })
        })
        .collect()
}

/// Whether a closed outline of lines and arcs crosses itself away from the ends its pieces
/// share: two of its pieces cross, or two lines lie along each other. With `touching`, pieces
/// that aren't neighbours meeting at all count too (an outline split where it crosses itself
/// only touches itself there). A simple outline whose offset crosses itself is refused, not drawn
/// as a loop: an inward offset wider than a neck of the shape pinches it into two, which one
/// outline can't be (an outline that already crosses or touches itself, a figure eight, keeps
/// its crossing offset). Outlines of more than 1000 pieces aren't checked.
fn crosses_itself(outline: &[Outline], touching: bool) -> bool {
    let n = outline.len();
    if !(2..=1000).contains(&n) {
        return false;
    }
    // Tolerances from the outline's own size, plus the coordinates' rounding.
    let ends = || outline.iter().flat_map(|(_, a, b, _)| [*a, *b]);
    let (lo, hi) = ends().fold((Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)), |(lo, hi), p| {
        (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
    });
    let reach = ends().fold(0.0f64, |m, p| m.max(p.x.abs()).max(p.y.abs()));
    let extent = (hi.x - lo.x).max(hi.y - lo.y).max(1e-9);
    let tol = 1e-9 * extent + 1e-12 * reach;
    let near = 1e-6 * extent + 1e-12 * reach;
    let bounds = |s: &Shape| match *s {
        Shape::Line { a, b } => (a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y)),
        Shape::Round { c, r, .. } => (c.x - r, c.y - r, c.x + r, c.y + r),
    };
    for i in 0..n {
        for j in i + 1..n {
            let (Some(x), Some(y)) = (outline.get(i), outline.get(j)) else { continue };
            let (bx, by) = (bounds(&x.0), bounds(&y.0));
            if bx.2 < by.0 - tol || by.2 < bx.0 - tol || bx.3 < by.1 - tol || by.3 < bx.1 - tol {
                continue;
            }
            let neighbours = j == i + 1 || (i == 0 && j == n - 1);
            // Neighbours meet at their shared end, where a tangent pair's crossings are rounding
            // noise.
            let shared: Vec<Vec2> = [x.1, x.2].into_iter().filter(|p| p.dist(y.1).min(p.dist(y.2)) <= tol).collect();
            let on = |piece: &Outline, p: Vec2, with_ends: bool| {
                piece.0.param_on(p, tol).is_some() || (with_ends && (piece.1.dist(p) <= tol || piece.2.dist(p) <= tol))
            };
            let with_ends = touching && !neighbours;
            if with_ends && !shared.is_empty() {
                return true;
            }
            if intersections(&x.0, &y.0)
                .into_iter()
                .any(|p| on(x, p, with_ends) && on(y, p, with_ends) && (with_ends || shared.iter().all(|s| s.dist(p) > near)))
            {
                return true;
            }
            // Two lines along one another: no crossing point, but they overlap.
            if let (Shape::Line { a, b }, Shape::Line { a: c, b: d }) = (x.0, y.0)
                && let Some(u) = (b - a).normalized()
            {
                let off = |p: Vec2| ((p - a).x * u.y - (p - a).y * u.x).abs();
                let along = |p: Vec2| (p - a).dot(u);
                let (s0, s1) = (along(c).min(along(d)), along(c).max(along(d)));
                if off(c) <= tol && off(d) <= tol && s1.min(a.dist(b)) - s0.max(0.0) > near {
                    return true;
                }
            }
        }
    }
    false
}