Skip to main content

brep_geometry/geometry/surface/
refine.rs

1//! Exact knot insertion and refinement on a tensor-product NURBS surface
2//! (Golovanov ยง3.16 builds the deformable surface on a refined control net;
3//! Piegl & Tiller A5.3 / A5.5).
4//!
5//! Boehm's algorithm runs on the homogeneous control points `(wx, wy, wz, w)`
6//! the surface stores, so rational surfaces refine exactly: the refined surface
7//! is the same point set with the same parameterization. Insertion in u runs
8//! the same one-knot blend down every column, in v along every row; the blend
9//! coefficients depend only on the knot vector, so every column (row) is refined
10//! by one alpha table and the net stays rectangular even where a whole row of
11//! poles coincides (a sphere's pole).
12//!
13//! Unlike [`crate::NurbsCurve::insert_knot`], nothing is clamped or capped in
14//! silence: a parameter outside the domain, a non-finite one, or one whose
15//! multiplicity would exceed the degree is refused by name, and the caller is
16//! told how many control rows it now has.
17
18use super::NurbsSurface;
19use crate::curve::KNOT_IDENTITY_TOL;
20use crate::Vec4;
21
22/// Which parameter direction a knot is inserted in.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum KnotDirection {
25    /// The first parameter: inserting adds control ROWS (`control_points[i]`).
26    U,
27    /// The second parameter: inserting adds control COLUMNS (`control_points[i][j]`).
28    V,
29}
30
31/// Why a knot refinement was refused. The surface is never changed in part.
32#[derive(Clone, Debug, PartialEq)]
33pub enum KnotRefinementRefusal {
34    /// The parameter is NaN or infinite.
35    NonFinite { direction: KnotDirection },
36    /// The parameter lies outside the closed domain `[start, end]`.
37    OutsideDomain { direction: KnotDirection, parameter: f64, start: f64, end: f64 },
38    /// The knot would occur more than `degree` times in the interior (the
39    /// surface would come apart there), or more than `degree + 1` at an end.
40    MultiplicityExceeded { direction: KnotDirection, parameter: f64, existing: usize, requested: usize, limit: usize },
41    /// The input surface itself is invalid.
42    InvalidSurface(String),
43}
44
45impl std::fmt::Display for KnotRefinementRefusal {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            Self::NonFinite { direction } => write!(f, "knot refinement: non-finite {direction:?} parameter"),
49            Self::OutsideDomain { direction, parameter, start, end } => write!(
50                f,
51                "knot refinement: {direction:?} parameter {parameter} is outside the domain [{start}, {end}]"
52            ),
53            Self::MultiplicityExceeded { direction, parameter, existing, requested, limit } => write!(
54                f,
55                "knot refinement: {direction:?} knot {parameter} already occurs {existing} times; \
56                 {requested} more would exceed the limit {limit}"
57            ),
58            Self::InvalidSurface(message) => write!(f, "knot refinement: invalid surface: {message}"),
59        }
60    }
61}
62
63impl std::error::Error for KnotRefinementRefusal {}
64
65impl NurbsSurface {
66    /// Insert the knot `parameter` `count` times in `direction`. The result is
67    /// the same surface (point for point at every parameter) on a finer net:
68    /// `count` more rows (u) or columns (v). `count == 0` returns a copy.
69    /// A parameter within [`KNOT_IDENTITY_TOL`] of an existing knot is that knot.
70    pub fn insert_knot(
71        &self,
72        direction: KnotDirection,
73        parameter: f64,
74        count: usize,
75    ) -> Result<NurbsSurface, KnotRefinementRefusal> {
76        // No knot can take more than degree + 1 copies: refuse an oversized
77        // count before allocating it.
78        let degree = match direction {
79            KnotDirection::U => self.degree_u,
80            KnotDirection::V => self.degree_v,
81        };
82        if count > degree + 1 {
83            return Err(KnotRefinementRefusal::MultiplicityExceeded {
84                direction,
85                parameter,
86                existing: 0,
87                requested: count,
88                limit: degree + 1,
89            });
90        }
91        self.refine_knots(direction, &vec![parameter; count])
92    }
93
94    /// Insert every parameter of `parameters` (any order, repeats allowed) in
95    /// `direction`. All are checked before anything is inserted: a refusal
96    /// leaves no partial result.
97    pub fn refine_knots(
98        &self,
99        direction: KnotDirection,
100        parameters: &[f64],
101    ) -> Result<NurbsSurface, KnotRefinementRefusal> {
102        self.domain_u().map_err(KnotRefinementRefusal::InvalidSurface)?;
103        let (degree, knots) = match direction {
104            KnotDirection::U => (self.degree_u, &self.knots_u),
105            KnotDirection::V => (self.degree_v, &self.knots_v),
106        };
107        let start = knots[degree];
108        let end = knots[knots.len() - 1 - degree];
109        // Snap to existing knots, then check every multiplicity before inserting.
110        let mut snapped = Vec::with_capacity(parameters.len());
111        for &parameter in parameters {
112            if !parameter.is_finite() {
113                return Err(KnotRefinementRefusal::NonFinite { direction });
114            }
115            if parameter < start - KNOT_IDENTITY_TOL || parameter > end + KNOT_IDENTITY_TOL {
116                return Err(KnotRefinementRefusal::OutsideDomain { direction, parameter, start, end });
117            }
118            // Snap to the NEAREST knot inside the domain (or an earlier
119            // parameter of this call) within the identity tolerance; a knot
120            // outside [start, end] (an unclamped vector's leading or trailing
121            // knots) is never a candidate, so the knot vector stays sorted.
122            let clamped = parameter.clamp(start, end);
123            let value = knots[degree..knots.len() - degree]
124                .iter()
125                .chain(snapped.iter())
126                .copied()
127                .filter(|knot| (knot - clamped).abs() <= KNOT_IDENTITY_TOL)
128                .min_by(|a, b| (a - clamped).abs().total_cmp(&(b - clamped).abs()))
129                .unwrap_or(clamped);
130            snapped.push(value);
131        }
132        snapped.sort_by(f64::total_cmp);
133        let mut index = 0;
134        while index < snapped.len() {
135            let value = snapped[index];
136            let requested = snapped[index..].iter().take_while(|&&other| other == value).count();
137            let existing = knots.iter().filter(|&&knot| knot == value).count();
138            let at_end = value == start || value == end;
139            let limit = if at_end { degree + 1 } else { degree };
140            if existing + requested > limit {
141                return Err(KnotRefinementRefusal::MultiplicityExceeded {
142                    direction,
143                    parameter: value,
144                    existing,
145                    requested,
146                    limit,
147                });
148            }
149            index += requested;
150        }
151        let mut knots = knots.clone();
152        let mut net = self.control_points.clone();
153        for &value in &snapped {
154            let (alphas, span) = boehm_table(&knots, degree, value);
155            net = match direction {
156                KnotDirection::U => apply_u(&net, &alphas, span, degree),
157                KnotDirection::V => net.iter().map(|row| apply_line(row, &alphas, span, degree)).collect(),
158            };
159            knots.insert(span + 1, value);
160        }
161        let (knots_u, knots_v) = match direction {
162            KnotDirection::U => (knots, self.knots_v.clone()),
163            KnotDirection::V => (self.knots_u.clone(), knots),
164        };
165        NurbsSurface::new(self.degree_u, self.degree_v, knots_u, knots_v, net)
166            .map_err(KnotRefinementRefusal::InvalidSurface)
167    }
168}
169
170/// The span `k` (`knots[k] <= value < knots[k + 1]`, the last non-empty span
171/// at the domain end) and the `p` Boehm blend coefficients for inserting
172/// `value` once: new point `k - p + i` (`i = 1..=p`) is
173/// `alpha_i P[k-p+i] + (1 - alpha_i) P[k-p+i-1]`.
174fn boehm_table(knots: &[f64], degree: usize, value: f64) -> (Vec<f64>, usize) {
175    let count = knots.len() - degree - 1;
176    let mut span = degree;
177    for k in degree..count {
178        if knots[k] <= value {
179            span = k;
180        }
181    }
182    let alphas = (1..=degree)
183        .map(|i| {
184            let index = span - degree + i;
185            let denominator = knots[index + degree] - knots[index];
186            if denominator <= 0.0 { 0.0 } else { ((value - knots[index]) / denominator).clamp(0.0, 1.0) }
187        })
188        .collect();
189    (alphas, span)
190}
191
192fn blend(previous: Vec4, current: Vec4, alpha: f64) -> Vec4 {
193    current.scale(alpha).add(previous.scale(1.0 - alpha))
194}
195
196fn apply_line(points: &[Vec4], alphas: &[f64], span: usize, degree: usize) -> Vec<Vec4> {
197    let mut out = Vec::with_capacity(points.len() + 1);
198    out.extend_from_slice(&points[..=span - degree]);
199    for (i, alpha) in alphas.iter().enumerate() {
200        let index = span - degree + i + 1;
201        out.push(blend(points[index - 1], points[index], *alpha));
202    }
203    out.extend_from_slice(&points[span..]);
204    out
205}
206
207fn apply_u(net: &[Vec<Vec4>], alphas: &[f64], span: usize, degree: usize) -> Vec<Vec<Vec4>> {
208    let mut out = Vec::with_capacity(net.len() + 1);
209    out.extend(net[..=span - degree].iter().cloned());
210    for (i, alpha) in alphas.iter().enumerate() {
211        let index = span - degree + i + 1;
212        out.push(
213            net[index - 1]
214                .iter()
215                .zip(&net[index])
216                .map(|(previous, current)| blend(*previous, *current, *alpha))
217                .collect(),
218        );
219    }
220    out.extend(net[span..].iter().cloned());
221    out
222}
223
224impl NurbsSurface {
225    /// Raise the degree in `direction` to `target` exactly (Bezier
226    /// decomposition, binomial elevation per segment, surplus junction knots
227    /// removed: [`crate::coons::compat::elevate_degree`] on every column (u)
228    /// or row (v)). The same knot operations run on every line, so the lines
229    /// must come back on one knot vector; a line that does not is refused
230    /// rather than resampled. `target <= degree` returns a copy.
231    pub fn elevate_degree(&self, direction: KnotDirection, target: usize) -> Result<NurbsSurface, String> {
232        self.domain_u()?;
233        let (degree, knots) = match direction {
234            KnotDirection::U => (self.degree_u, &self.knots_u),
235            KnotDirection::V => (self.degree_v, &self.knots_v),
236        };
237        if target <= degree {
238            return Ok(self.clone());
239        }
240        let lines: Vec<Vec<Vec4>> = match direction {
241            KnotDirection::U => (0..self.control_points[0].len())
242                .map(|j| self.control_points.iter().map(|row| row[j]).collect())
243                .collect(),
244            KnotDirection::V => self.control_points.clone(),
245        };
246        let mut elevated_knots: Option<Vec<f64>> = None;
247        let mut elevated_lines = Vec::with_capacity(lines.len());
248        for line in lines {
249            let curve = crate::NurbsCurve::new(degree, knots.clone(), line)?;
250            let elevated = crate::coons::compat::elevate_degree(&curve, target)?;
251            match &elevated_knots {
252                None => elevated_knots = Some(elevated.knots.clone()),
253                Some(first) if *first == elevated.knots => {}
254                Some(_) => {
255                    return Err("elevate_degree: lines of the net came back on different knot vectors".into())
256                }
257            }
258            elevated_lines.push(elevated.control_points);
259        }
260        let elevated_knots = elevated_knots.ok_or("elevate_degree: empty net")?;
261        match direction {
262            KnotDirection::U => {
263                let rows = elevated_lines[0].len();
264                let net = (0..rows).map(|i| elevated_lines.iter().map(|line| line[i]).collect()).collect();
265                NurbsSurface::new(target, self.degree_v, elevated_knots, self.knots_v.clone(), net)
266            }
267            KnotDirection::V => {
268                NurbsSurface::new(self.degree_u, target, self.knots_u.clone(), elevated_knots, elevated_lines)
269            }
270        }
271    }
272}