brep_geometry/geometry/surface/
refine.rs1use super::NurbsSurface;
19use crate::curve::KNOT_IDENTITY_TOL;
20use crate::Vec4;
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum KnotDirection {
25 U,
27 V,
29}
30
31#[derive(Clone, Debug, PartialEq)]
33pub enum KnotRefinementRefusal {
34 NonFinite { direction: KnotDirection },
36 OutsideDomain { direction: KnotDirection, parameter: f64, start: f64, end: f64 },
38 MultiplicityExceeded { direction: KnotDirection, parameter: f64, existing: usize, requested: usize, limit: usize },
41 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 pub fn insert_knot(
71 &self,
72 direction: KnotDirection,
73 parameter: f64,
74 count: usize,
75 ) -> Result<NurbsSurface, KnotRefinementRefusal> {
76 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 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 let mut snapped = Vec::with_capacity(parameters.len());
111 for ¶meter 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 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
170fn 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 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}