1use crate::KnotDirection;
61use crate::{NurbsSurface, Vec3};
62
63#[derive(Clone, Debug, PartialEq)]
66pub enum Irregularity {
67 Collapses { u: f64, v: f64 },
69 FoldsOver { u: f64, v: f64 },
71 Uncertified { u: f64, v: f64, reason: String },
73}
74
75impl std::fmt::Display for Irregularity {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 match self {
78 Self::Collapses { u, v } => write!(f, "the normal vanishes at ({u:.6}, {v:.6})"),
79 Self::FoldsOver { u, v } => write!(f, "the normal turns back near ({u:.6}, {v:.6})"),
80 Self::Uncertified { u, v, reason } => write!(f, "regularity not certified near ({u:.6}, {v:.6}): {reason}"),
81 }
82 }
83}
84
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub struct RegularityReport {
88 pub pieces: usize,
89 pub boxes: usize,
90 pub creases: usize,
91}
92
93const BOX_BUDGET: usize = 400_000;
95const MAX_DEPTH: u32 = 40;
97const WITNESS_SIZE: f64 = 1.0 / 1024.0;
100const VANISHING: f64 = 1e-9;
103const MARGIN: f64 = 1e-13;
105
106pub fn certify_regular(surface: &NurbsSurface) -> Result<RegularityReport, Irregularity> {
108 let uncertified = |reason: String| Irregularity::Uncertified { u: f64::NAN, v: f64::NAN, reason };
109 let [u0, u1] = surface.domain_u().map_err(&uncertified)?;
110 let [v0, v1] = surface.domain_v().map_err(&uncertified)?;
111 let (p, q) = (surface.degree_u, surface.degree_v);
112 if p == 0 || q == 0 {
113 return Err(uncertified(format!("degree ({p}, {q}) has no normal")));
114 }
115 for (knots, degree, name) in [(&surface.knots_u, p, "u"), (&surface.knots_v, q, "v")] {
116 let n = knots.len();
117 if knots[..=degree].iter().any(|k| *k != knots[0]) || knots[n - degree - 1..].iter().any(|k| *k != knots[n - 1]) {
118 return Err(uncertified(format!("the {name} knot vector is not clamped")));
119 }
120 }
121 let rational = {
122 let w0 = surface.control_points[0][0].w;
123 surface.control_points.iter().flatten().any(|point| point.w != w0)
124 };
125 if surface.control_points.iter().flatten().any(|point| !(point.w > 0.0) || !point.w.is_finite()) {
126 return Err(uncertified("a weight is not positive".into()));
127 }
128 let (breaks_u, insert_u) = breaks(&surface.knots_u, p, u0, u1);
131 let (breaks_v, insert_v) = breaks(&surface.knots_v, q, v0, v1);
132 let refined = surface
133 .refine_knots(KnotDirection::U, &insert_u)
134 .and_then(|refined| refined.refine_knots(KnotDirection::V, &insert_v))
135 .map_err(|error| uncertified(error.to_string()))?;
136 let (pieces_u, pieces_v) = (breaks_u.len() - 1, breaks_v.len() - 1);
137 if refined.control_points.len() != pieces_u * p + 1 || refined.control_points.iter().any(|row| row.len() != pieces_v * q + 1) {
138 return Err(uncertified("the refined net does not split into Bézier pieces".into()));
139 }
140 let mut report = RegularityReport::default();
141 let mut normals: Vec<Vec<Grid<Vec3>>> = Vec::with_capacity(pieces_u);
142 for a in 0..pieces_u {
143 let mut row = Vec::with_capacity(pieces_v);
144 for b in 0..pieces_v {
145 let net: Vec<Vec<crate::Vec4>> =
146 (0..=p).map(|i| refined.control_points[a * p + i][b * q..=b * q + q].to_vec()).collect();
147 let normal = piece_normal(&net, p, q, rational);
148 let piece = Piece {
149 u: [breaks_u[a], breaks_u[a + 1]],
150 v: [breaks_v[b], breaks_v[b + 1]],
151 corners: [
152 a == 0 && b == 0,
153 a == pieces_u - 1 && b == 0,
154 a == 0 && b == pieces_v - 1,
155 a == pieces_u - 1 && b == pieces_v - 1,
156 ],
157 };
158 certify_piece(surface, &normal, &piece, &mut report)?;
159 report.pieces += 1;
160 row.push(normal);
161 }
162 normals.push(row);
163 }
164 let multiplicity = |knots: &[f64], value: f64| knots.iter().filter(|k| **k == value).count();
166 for a in 0..pieces_u.saturating_sub(1) {
167 if multiplicity(&surface.knots_u, breaks_u[a + 1]) < p {
168 continue;
169 }
170 for b in 0..pieces_v {
171 let (before, after) = (&normals[a][b], &normals[a + 1][b]);
172 let left: Vec<Vec3> = (0..=before.n).map(|j| before.at(before.m, j)).collect();
173 let right: Vec<Vec3> = (0..=after.n).map(|j| after.at(0, j)).collect();
174 report.creases += 1;
175 certify_crease(&left, &right, breaks_v[b], breaks_v[b + 1])
176 .map_err(|t| Irregularity::FoldsOver { u: breaks_u[a + 1], v: t })?;
177 }
178 }
179 for b in 0..pieces_v.saturating_sub(1) {
180 if multiplicity(&surface.knots_v, breaks_v[b + 1]) < q {
181 continue;
182 }
183 for a in 0..pieces_u {
184 let (before, after) = (&normals[a][b], &normals[a][b + 1]);
185 let below: Vec<Vec3> = (0..=before.m).map(|i| before.at(i, before.n)).collect();
186 let above: Vec<Vec3> = (0..=after.m).map(|i| after.at(i, 0)).collect();
187 report.creases += 1;
188 certify_crease(&below, &above, breaks_u[a], breaks_u[a + 1])
189 .map_err(|s| Irregularity::FoldsOver { u: s, v: breaks_v[b + 1] })?;
190 }
191 }
192 Ok(report)
193}
194
195fn breaks(knots: &[f64], degree: usize, start: f64, end: f64) -> (Vec<f64>, Vec<f64>) {
198 let mut values: Vec<f64> = Vec::new();
199 let mut insert = Vec::new();
200 for &knot in knots {
201 if knot < start || knot > end || values.last() == Some(&knot) {
202 continue;
203 }
204 values.push(knot);
205 if knot > start && knot < end {
206 let have = knots.iter().filter(|k| **k == knot).count();
207 insert.extend(std::iter::repeat(knot).take(degree.saturating_sub(have)));
208 }
209 }
210 (values, insert)
211}
212
213struct Piece {
217 u: [f64; 2],
218 v: [f64; 2],
219 corners: [bool; 4],
220}
221
222#[derive(Clone, Debug)]
225struct Grid<T> {
226 m: usize,
227 n: usize,
228 c: Vec<T>,
229}
230
231trait Linear: Copy {
232 fn zero() -> Self;
233 fn plus(self, other: Self) -> Self;
234 fn times(self, factor: f64) -> Self;
235}
236
237impl Linear for f64 {
238 fn zero() -> Self {
239 0.0
240 }
241 fn plus(self, other: Self) -> Self {
242 self + other
243 }
244 fn times(self, factor: f64) -> Self {
245 self * factor
246 }
247}
248
249impl Linear for Vec3 {
250 fn zero() -> Self {
251 Vec3::new(0.0, 0.0, 0.0)
252 }
253 fn plus(self, other: Self) -> Self {
254 self.add(other)
255 }
256 fn times(self, factor: f64) -> Self {
257 self.scale(factor)
258 }
259}
260
261fn binomial(n: usize, k: usize) -> f64 {
262 let k = k.min(n - k);
263 (0..k).fold(1.0, |value, i| value * (n - i) as f64 / (i + 1) as f64)
264}
265
266impl<T: Linear> Grid<T> {
267 fn at(&self, i: usize, j: usize) -> T {
268 self.c[i * (self.n + 1) + j]
269 }
270
271 fn du(&self) -> Grid<T> {
273 let (m, n) = (self.m, self.n);
274 let c = (0..m)
275 .flat_map(|i| (0..=n).map(move |j| (i, j)))
276 .map(|(i, j)| self.at(i + 1, j).plus(self.at(i, j).times(-1.0)).times(m as f64))
277 .collect();
278 Grid { m: m - 1, n, c }
279 }
280
281 fn dv(&self) -> Grid<T> {
283 let (m, n) = (self.m, self.n);
284 let c = (0..=m)
285 .flat_map(|i| (0..n).map(move |j| (i, j)))
286 .map(|(i, j)| self.at(i, j + 1).plus(self.at(i, j).times(-1.0)).times(n as f64))
287 .collect();
288 Grid { m, n: n - 1, c }
289 }
290
291 fn plus(&self, other: &Grid<T>) -> Grid<T> {
292 debug_assert!(self.m == other.m && self.n == other.n);
293 Grid { m: self.m, n: self.n, c: self.c.iter().zip(&other.c).map(|(a, b)| a.plus(*b)).collect() }
294 }
295
296 fn halves(&self, along_u: bool) -> (Grid<T>, Grid<T>) {
298 let (m, n) = (self.m, self.n);
299 let mut low = self.clone();
300 let mut high = self.clone();
301 let (count, length) = if along_u { (n + 1, m + 1) } else { (m + 1, n + 1) };
302 let index = |line: usize, k: usize| if along_u { k * (n + 1) + line } else { line * (n + 1) + k };
303 let mut work = vec![T::zero(); length];
304 for line in 0..count {
305 for (k, slot) in work.iter_mut().enumerate() {
306 *slot = self.c[index(line, k)];
307 }
308 for level in 0..length {
309 low.c[index(line, level)] = work[0];
310 high.c[index(line, length - 1 - level)] = work[length - 1 - level];
311 for k in 0..length - 1 - level {
312 work[k] = work[k].plus(work[k + 1]).times(0.5);
313 }
314 }
315 }
316 (low, high)
317 }
318
319 fn value(&self, s: f64, t: f64) -> T {
321 let rows: Vec<T> = (0..=self.m)
322 .map(|i| casteljau(&(0..=self.n).map(|j| self.at(i, j)).collect::<Vec<_>>(), t))
323 .collect();
324 casteljau(&rows, s)
325 }
326}
327
328fn casteljau<T: Linear>(points: &[T], t: f64) -> T {
329 let mut work = points.to_vec();
330 for level in 1..work.len() {
331 for k in 0..work.len() - level {
332 work[k] = work[k].times(1.0 - t).plus(work[k + 1].times(t));
333 }
334 }
335 work[0]
336}
337
338fn product<A: Linear, B: Linear, C: Linear>(a: &Grid<A>, b: &Grid<B>, combine: impl Fn(A, B) -> C) -> Grid<C> {
340 let (m, n) = (a.m + b.m, a.n + b.n);
341 let mut c = vec![C::zero(); (m + 1) * (n + 1)];
342 for i in 0..=a.m {
343 for j in 0..=a.n {
344 for k in 0..=b.m {
345 for l in 0..=b.n {
346 let factor = binomial(a.m, i) * binomial(b.m, k) / binomial(m, i + k) * binomial(a.n, j)
347 * binomial(b.n, l)
348 / binomial(n, j + l);
349 let slot = &mut c[(i + k) * (n + 1) + j + l];
350 *slot = slot.plus(combine(a.at(i, j), b.at(k, l)).times(factor));
351 }
352 }
353 }
354 }
355 Grid { m, n, c }
356}
357
358fn piece_normal(net: &[Vec<crate::Vec4>], p: usize, q: usize, rational: bool) -> Grid<Vec3> {
361 let cells = |f: &dyn Fn(&crate::Vec4) -> Vec3| Grid {
362 m: p,
363 n: q,
364 c: net.iter().flat_map(|row| row.iter().map(f)).collect::<Vec<Vec3>>(),
365 };
366 if !rational {
367 let points = cells(&|point| Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w));
368 return product(&points.du(), &points.dv(), Vec3::cross);
369 }
370 let points = cells(&|point| Vec3::new(point.x, point.y, point.z));
371 let weights = Grid { m: p, n: q, c: net.iter().flat_map(|row| row.iter().map(|point| point.w)).collect::<Vec<f64>>() };
372 let (pu, pv) = (points.du(), points.dv());
373 let first = product(&weights, &product(&pu, &pv, Vec3::cross), |w, n| n.scale(w));
374 let second = product(&weights.dv(), &product(&points, &pu, Vec3::cross), |w, n| n.scale(w));
375 let third = product(&weights.du(), &product(&pv, &points, Vec3::cross), |w, n| n.scale(w));
376 first.plus(&second).plus(&third)
377}
378
379struct Cell {
381 normal: Grid<Vec3>,
382 s: [f64; 2],
383 t: [f64; 2],
384 depth: u32,
385}
386
387fn certify_piece(
388 surface: &NurbsSurface,
389 normal: &Grid<Vec3>,
390 piece: &Piece,
391 report: &mut RegularityReport,
392) -> Result<(), Irregularity> {
393 let scale = normal.c.iter().map(|c| c.length()).fold(0.0_f64, f64::max);
394 let at = |s: f64, t: f64| (piece.u[0] + (piece.u[1] - piece.u[0]) * s, piece.v[0] + (piece.v[1] - piece.v[0]) * t);
395 if !(scale > 0.0) || !scale.is_finite() {
396 let (u, v) = at(0.5, 0.5);
397 return Err(Irregularity::Collapses { u, v });
398 }
399 let vanishes = |s: f64, t: f64| {
404 let (u, v) = at(s, t);
405 match surface.deriv1(u, v) {
406 Ok((_, su, sv)) => !(su.cross(sv).length() > VANISHING * su.length() * sv.length()),
407 Err(_) => true,
408 }
409 };
410 let mut stack = vec![Cell { normal: normal.clone(), s: [0.0, 1.0], t: [0.0, 1.0], depth: 0 }];
411 while let Some(cell) = stack.pop() {
412 report.boxes += 1;
413 let grid = &cell.normal;
414 let (m, n) = (grid.m, grid.n);
415 let corner_index = [(0, 0), (m, 0), (0, n), (m, n)];
418 let corner_st = |k: usize| (if k % 2 == 0 { cell.s[0] } else { cell.s[1] }, if k < 2 { cell.t[0] } else { cell.t[1] });
419 let exempt = |k: usize| {
420 let (s, t) = ([cell.s[0], cell.s[1], cell.s[0], cell.s[1]][k], [cell.t[0], cell.t[0], cell.t[1], cell.t[1]][k]);
421 let piece_corner = match (s, t) {
422 (s, t) if s == 0.0 && t == 0.0 => Some(0),
423 (s, t) if s == 1.0 && t == 0.0 => Some(1),
424 (s, t) if s == 0.0 && t == 1.0 => Some(2),
425 (s, t) if s == 1.0 && t == 1.0 => Some(3),
426 _ => None,
427 };
428 piece_corner.is_some_and(|c| piece.corners[c])
429 };
430 let mut reference = grid.value(0.5, 0.5);
431 if !(reference.length() > VANISHING * scale) {
432 reference = grid.c.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, c| sum.add(*c));
433 }
434 let largest = grid.c.iter().map(|c| c.length()).fold(0.0_f64, f64::max);
435 if reference.length() > 0.0 && largest > 0.0 {
436 let direction = reference.scale(1.0 / reference.length());
437 let margin = MARGIN * largest;
438 let dots: Vec<f64> = grid.c.iter().map(|c| c.dot(direction)).collect();
439 let certified = if dots.iter().all(|d| *d > margin) {
440 true
441 } else {
442 let corner_ok = (0..4).all(|k| {
448 let (ci, cj) = corner_index[k];
449 dots[ci * (n + 1) + cj] > margin || (exempt(k) && vanishes(corner_st(k).0, corner_st(k).1))
450 });
451 let side_ok = |side: &dyn Fn(usize) -> Option<usize>| (0..=m.max(n)).filter_map(side).any(|index| dots[index] > margin);
452 corner_ok
453 && dots.iter().all(|d| *d >= -margin)
454 && side_ok(&|j| (j <= n).then_some(j))
455 && side_ok(&|j| (j <= n).then_some(m * (n + 1) + j))
456 && side_ok(&|i| (i <= m).then_some(i * (n + 1)))
457 && side_ok(&|i| (i <= m).then_some(i * (n + 1) + n))
458 };
459 if certified {
460 continue;
461 }
462 }
463 let corner_point = |k: usize| {
465 let s = if k % 2 == 0 { cell.s[0] } else { cell.s[1] };
466 let t = if k < 2 { cell.t[0] } else { cell.t[1] };
467 at(s, t)
468 };
469 let corners: Vec<(usize, Vec3)> = (0..4).filter(|&k| !exempt(k)).map(|k| (k, grid.at(corner_index[k].0, corner_index[k].1))).collect();
470 if let Some(&(k, _)) = corners.iter().find(|(k, _)| vanishes(corner_st(*k).0, corner_st(*k).1)) {
471 let (u, v) = corner_point(k);
472 return Err(Irregularity::Collapses { u, v });
473 }
474 let small = cell.s[1] - cell.s[0] <= WITNESS_SIZE && cell.t[1] - cell.t[0] <= WITNESS_SIZE;
475 if small && corners.iter().any(|(_, a)| corners.iter().any(|(_, b)| a.dot(*b) < 0.0)) {
476 let (u, v) = at(0.5 * (cell.s[0] + cell.s[1]), 0.5 * (cell.t[0] + cell.t[1]));
477 return Err(Irregularity::FoldsOver { u, v });
478 }
479 if cell.depth >= MAX_DEPTH || report.boxes >= BOX_BUDGET {
480 let (u, v) = at(0.5 * (cell.s[0] + cell.s[1]), 0.5 * (cell.t[0] + cell.t[1]));
481 let reason = if cell.depth >= MAX_DEPTH { "the subdivision reached its depth limit" } else { "the subdivision budget is spent" };
482 return Err(Irregularity::Uncertified { u, v, reason: reason.into() });
483 }
484 let along_u = cell.s[1] - cell.s[0] >= cell.t[1] - cell.t[0];
485 let (low, high) = grid.halves(along_u);
486 let (first, second) = if along_u {
487 let mid = 0.5 * (cell.s[0] + cell.s[1]);
488 (
489 Cell { normal: low, s: [cell.s[0], mid], t: cell.t, depth: cell.depth + 1 },
490 Cell { normal: high, s: [mid, cell.s[1]], t: cell.t, depth: cell.depth + 1 },
491 )
492 } else {
493 let mid = 0.5 * (cell.t[0] + cell.t[1]);
494 (
495 Cell { normal: low, s: cell.s, t: [cell.t[0], mid], depth: cell.depth + 1 },
496 Cell { normal: high, s: cell.s, t: [mid, cell.t[1]], depth: cell.depth + 1 },
497 )
498 };
499 stack.push(second);
500 stack.push(first);
501 }
502 Ok(())
503}
504
505fn certify_crease(before: &[Vec3], after: &[Vec3], start: f64, end: f64) -> Result<(), f64> {
509 let to_grid = |c: &[Vec3]| Grid { m: 0, n: c.len() - 1, c: c.to_vec() };
510 let dot = product(&to_grid(before), &to_grid(after), |a, b| a.dot(b));
511 let mut stack = vec![(dot, [0.0_f64, 1.0_f64], 0_u32)];
512 while let Some((grid, range, depth)) = stack.pop() {
513 let largest = grid.c.iter().map(|c| c.abs()).fold(0.0_f64, f64::max);
514 if grid.c.iter().all(|c| *c > MARGIN * largest) {
515 continue;
516 }
517 let place = |r: f64| start + (end - start) * r;
518 if let Some(r) = [(grid.c[0], range[0]), (grid.c[grid.n], range[1])].iter().find(|(c, _)| *c <= 0.0).map(|(_, r)| *r) {
520 return Err(place(r));
521 }
522 if depth >= MAX_DEPTH {
523 return Err(place(0.5 * (range[0] + range[1])));
524 }
525 let mid = 0.5 * (range[0] + range[1]);
526 let (low, high) = grid.halves(false);
527 stack.push((high, [mid, range[1]], depth + 1));
528 stack.push((low, [range[0], mid], depth + 1));
529 }
530 Ok(())
531}
532