Skip to main content

brep_kernel/geometry/
curve_chain.rs

1//! A chain of curves as one curve, and a surface cut along a parameter line.
2//!
3//! [`join_curve_chain`] makes one B-spline curve of curves that follow one
4//! another head to tail. Nothing is fitted: every piece is raised to the
5//! chain's highest degree (exactly), its knots are moved onto its own stretch
6//! of the joined parameter, and its homogeneous poles are scaled so the weights
7//! agree where it meets the piece before (which moves no point of it). The
8//! joints become knots of full multiplicity, so the joined curve is as smooth
9//! there as the chain is, and no smoother.
10//!
11//! [`split_surface`] cuts a surface along a parameter line into the two
12//! surfaces on either side, by knot insertion on every row of its poles.
13use crate::coons::compat::elevate_degree;
14use crate::{curve_arc_length, NurbsCurve, NurbsSurface, Vec3, Vec4};
15
16fn ends(curve: &NurbsCurve) -> Result<[Vec3; 2], String> {
17    let [t0, t1] = curve.domain()?;
18    Ok([curve.evaluate(t0)?, curve.evaluate(t1)?])
19}
20
21/// The chain `pieces` as one curve, piece `k` on a stretch of the parameter
22/// `spans[k]` long, the first starting at 0.
23pub(crate) fn join_curve_chain_on_spans(pieces: &[NurbsCurve], spans: &[f64]) -> Result<NurbsCurve, String> {
24    if pieces.is_empty() || spans.len() != pieces.len() {
25        return Err("joinCurveChain: a chain needs at least one curve, and a span for each".into());
26    }
27    if spans.iter().any(|span| !(span.is_finite() && *span > 0.0)) {
28        return Err("joinCurveChain: every piece's parameter span must be positive".into());
29    }
30    let degree = pieces.iter().map(|piece| piece.degree).max().expect("a piece");
31    let mut size = 0.0f64;
32    let origin = ends(&pieces[0])?[0];
33    for piece in pieces {
34        for pole in &piece.control_points {
35            size = size.max(Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w).sub(origin).length());
36        }
37    }
38    let mut knots = vec![0.0; degree + 1];
39    let mut poles: Vec<Vec4> = Vec::new();
40    let mut offset = 0.0;
41    for (index, piece) in pieces.iter().enumerate() {
42        let raised = if piece.degree == degree { piece.clone() } else { elevate_degree(piece, degree)? };
43        let [t0, t1] = raised.domain()?;
44        if index > 0 {
45            let gap = ends(&pieces[index - 1])?[1].sub(ends(piece)?[0]).length();
46            if gap > 1e-9 * size {
47                return Err(format!("joinCurveChain: curve {index} does not start where curve {} ends (gap {gap:.3e})", index - 1));
48            }
49        }
50        // the piece's interior knots on its stretch, then the joint (or the end) at full multiplicity
51        let scale = spans[index] / (t1 - t0);
52        let interior = &raised.knots[degree + 1..raised.knots.len() - degree - 1];
53        knots.extend(interior.iter().map(|knot| offset + (knot - t0) * scale));
54        offset += spans[index];
55        knots.extend(std::iter::repeat(offset).take(degree));
56        // the weights made to agree at the joint: a common factor moves no point of the piece
57        let factor = match poles.last() {
58            Some(last) => last.w / raised.control_points[0].w,
59            None => 1.0,
60        };
61        let scaled = raised.control_points.iter().map(|pole| Vec4 { x: pole.x * factor, y: pole.y * factor, z: pole.z * factor, w: pole.w * factor });
62        poles.extend(scaled.skip(usize::from(index > 0)));
63    }
64    knots.push(offset);
65    NurbsCurve::new(degree, knots, poles)
66}
67
68/// The chain `pieces`, curves that follow one another head to tail, as one
69/// curve: exactly the same points, each piece on a stretch of the parameter as
70/// long as the piece itself, so the joined curve runs at an even pace from
71/// piece to piece. Its joints are knots of full multiplicity (the curve is as
72/// smooth there as the chain is).
73///
74/// Refuses an empty chain and pieces that do not meet end to start.
75pub fn join_curve_chain(pieces: &[NurbsCurve]) -> Result<NurbsCurve, String> {
76    let mut spans = Vec::with_capacity(pieces.len());
77    for piece in pieces {
78        let [t0, t1] = piece.domain()?;
79        spans.push(curve_arc_length(piece, t0, t1)?);
80    }
81    join_curve_chain_on_spans(pieces, &spans)
82}
83
84/// `surface` cut along the parameter line `at` (a `v` line when `along_v`,
85/// else a `u` line) into the part before it and the part after it. Exact: knot
86/// insertion on each row of poles across the cut.
87pub fn split_surface(surface: &NurbsSurface, along_v: bool, at: f64) -> Result<(NurbsSurface, NurbsSurface), String> {
88    let net = &surface.control_points;
89    let (rows, columns) = (net.len(), net.first().map_or(0, Vec::len));
90    let (degree, knots, lines) = if along_v { (surface.degree_v, &surface.knots_v, rows) } else { (surface.degree_u, &surface.knots_u, columns) };
91    let (mut before, mut after) = (Vec::with_capacity(lines), Vec::with_capacity(lines));
92    for line in 0..lines {
93        let poles: Vec<Vec4> = if along_v { net[line].clone() } else { (0..rows).map(|row| net[row][line]).collect() };
94        let (first, second) = NurbsCurve::new(degree, knots.clone(), poles)?.split(at)?;
95        before.push(first);
96        after.push(second);
97    }
98    let part = |curves: &[NurbsCurve]| -> Result<NurbsSurface, String> {
99        let count = curves[0].control_points.len();
100        if along_v {
101            let net = curves.iter().map(|curve| curve.control_points.clone()).collect();
102            NurbsSurface::new(surface.degree_u, degree, surface.knots_u.clone(), curves[0].knots.clone(), net)
103        } else {
104            let net = (0..count).map(|row| curves.iter().map(|curve| curve.control_points[row]).collect()).collect();
105            NurbsSurface::new(degree, surface.degree_v, curves[0].knots.clone(), surface.knots_v.clone(), net)
106        }
107    };
108    Ok((part(&before)?, part(&after)?))
109}
110