1use crate::{FrameCurve, OutlinePiece, SolidTool, Vec3};
24
25#[path = "solid_sweep_upright_direct.rs"]
26mod direct;
27pub use direct::upright_direct_on;
28
29pub const ENVELOPE: f64 = 1e6;
37
38pub fn upright_slot_on() -> bool {
45 crate::switch!("BREP_SWEEP_UPRIGHT_SLOT", true)
46}
47
48pub fn sweep_upright_along(tool: &SolidTool, path: &FrameCurve) -> Option<Result<crate::BrepSolid, crate::KernelRefusal>> {
53 upright_slot(tool, path).map(|slot| slot.solid())
54}
55
56#[derive(Clone, Debug)]
62pub struct UprightSlot {
63 pub origin: Vec3,
65 pub x: Vec3,
66 pub y: Vec3,
67 pub up: Vec3,
68 pub curve: [[f64; 2]; 4],
70 pub meridian: Vec<OutlinePiece>,
72 pub heights: [f64; 2],
74}
75
76fn turns_within(a: f64, lo: f64, hi: f64) -> impl Iterator<Item = f64> {
78 let tau = std::f64::consts::TAU;
79 let (first, last) = (((lo - a) / tau).ceil(), ((hi - a) / tau).floor());
80 let count = if first.is_finite() && last.is_finite() && last >= first && last - first < 1e6 { (last - first) as i64 + 1 } else { 0 };
81 (0..count).map(move |k| a + tau * (first + k as f64))
82}
83
84fn piece_extent(piece: &OutlinePiece) -> (f64, f64) {
87 match *piece {
88 OutlinePiece::Line { from, to } => (from[0].abs().max(to[0].abs()), from[1].abs().max(to[1].abs())),
89 OutlinePiece::Arc { centre, radius, start, end } => {
90 let (a, b) = (start.min(end), start.max(end));
91 let at = |t: f64| [centre[0] + radius * t.cos(), centre[1] + radius * t.sin()];
92 let mut points = vec![at(start), at(end)];
93 for k in [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, -std::f64::consts::FRAC_PI_2] {
94 points.extend(turns_within(k, a, b).take(1).map(at));
95 }
96 points.iter().fold((0.0f64, 0.0f64), |(r, h), p| (r.max(p[0].abs()), h.max(p[1].abs())))
97 }
98 OutlinePiece::Ellipse { .. } => (f64::INFINITY, f64::INFINITY),
99 }
100}
101
102fn sign_bound_on() -> bool {
106 crate::switch!("BREP_UPRIGHT_SIGN_BOUND", true)
107}
108
109fn convex_hull(points: &[[f64; 2]]) -> Vec<[f64; 2]> {
111 let mut p: Vec<[f64; 2]> = points.to_vec();
112 p.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
113 p.dedup();
114 if p.len() < 3 {
115 return p;
116 }
117 let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
118 let mut hull: Vec<[f64; 2]> = Vec::new();
119 for pass in 0..2 {
120 let start = hull.len();
121 let ordered: Vec<[f64; 2]> = if pass == 0 { p.clone() } else { p.iter().rev().copied().collect() };
122 for q in ordered {
123 while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], q) <= 0.0 {
124 hull.pop();
125 }
126 hull.push(q);
127 }
128 hull.pop();
129 }
130 hull
131}
132
133fn hull_distance(hull: &[[f64; 2]], q: [f64; 2]) -> f64 {
136 let n = hull.len();
137 let segment = |a: [f64; 2], b: [f64; 2]| -> f64 {
138 let (d, r) = (sub(b, a), sub(q, a));
139 let len2 = dot(d, d);
140 let s = if len2 > 0.0 { (dot(r, d) / len2).clamp(0.0, 1.0) } else { 0.0 };
141 let e = [r[0] - s * d[0], r[1] - s * d[1]];
142 dot(e, e).sqrt()
143 };
144 if n == 1 {
145 return segment(hull[0], hull[0]);
146 }
147 let inside = n >= 3 && (0..n).all(|k| {
148 let (a, b) = (hull[k], hull[(k + 1) % n]);
149 (b[0] - a[0]) * (q[1] - a[1]) - (b[1] - a[1]) * (q[0] - a[0]) >= 0.0
150 });
151 if inside {
152 return 0.0;
153 }
154 (0..n).map(|k| segment(hull[k], hull[(k + 1) % n])).fold(f64::INFINITY, f64::min)
155}
156
157fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
158 [a[0] - b[0], a[1] - b[1]]
159}
160
161fn dot(a: [f64; 2], b: [f64; 2]) -> f64 {
162 a[0] * b[0] + a[1] * b[1]
163}
164
165pub fn upright_slot(tool: &SolidTool, path: &FrameCurve) -> Option<UprightSlot> {
171 let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else { return None };
172 let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
173 let pieces_finite = meridian.iter().all(|piece| match *piece {
174 OutlinePiece::Line { from, to } => from.iter().chain(&to).all(|x| x.is_finite()),
175 OutlinePiece::Arc { centre, radius, start, end } => centre.iter().all(|x| x.is_finite()) && radius.is_finite() && start.is_finite() && end.is_finite(),
176 OutlinePiece::Ellipse { .. } => false,
177 });
178 if !(pieces_finite && path.control.iter().all(|p| finite(*p)) && finite(path.up) && finite(*axis_origin) && finite(*axis_direction) && finite(*radial)) {
179 return None;
180 }
181 let unit = |d: Vec3| -> Option<Vec3> {
183 let big = d.x.abs().max(d.y.abs()).max(d.z.abs());
184 if !(big > 0.0 && big.is_finite()) {
185 return None;
186 }
187 let n = d.scale(1.0 / big).normalized().ok()?;
188 ((n.length() - 1.0).abs() <= 1e-12).then_some(n)
189 };
190 let up = unit(path.up)?;
191 let axis = unit(*axis_direction)?;
192 let along = axis.dot(up).signum();
193 let start = path.control[0];
194 let (widest, tall) = meridian.iter().map(piece_extent).fold((0.0f64, 0.0f64), |(r, h), (pr, ph)| (r.max(pr), h.max(ph)));
198 if !(widest > 0.0 && widest.is_finite() && tall.is_finite()) {
199 return None;
200 }
201 if meridian.iter().any(|piece| matches!(*piece, OutlinePiece::Arc { radius, .. } if !(radius > 0.0 && radius <= ENVELOPE * widest))) {
204 return None;
205 }
206 let extent = path.control.iter().map(|p| p.sub(start).length()).fold(0.0f64, f64::max);
208 let one_turn = meridian.iter().all(|piece| match *piece {
209 OutlinePiece::Arc { start, end, .. } => (end - start).abs() <= std::f64::consts::TAU * (1.0 + 1e-12),
210 _ => true,
211 });
212 let sized = |x: f64| (1e-60..=1e60).contains(&x);
215 if !(one_turn && sized(widest) && sized(extent) && sized(tall.max(widest)) && tall <= ENVELOPE * widest && tall >= widest / ENVELOPE && extent <= ENVELOPE * widest && extent >= widest / ENVELOPE) {
216 return None;
217 }
218 let band = 1e-12 * widest;
219 if axis.cross(up).length() * tall.max(widest) > band {
220 return None;
221 }
222 let off = axis_origin.sub(start);
224 if off.sub(up.scale(off.dot(up))).length() > band {
225 return None;
226 }
227 if path.control.iter().any(|p| p.sub(start).dot(up).abs() > band) {
228 return None;
229 }
230 let radial_unit = unit(*radial)?;
233 if radial_unit.dot(axis).abs() > 1e-12 {
234 return None;
235 }
236 if path.control.iter().all(|p| p.sub(start).length() <= band) {
238 return None;
239 }
240 let lift = off.dot(up);
241 let meridian: Vec<OutlinePiece> = meridian
242 .iter()
243 .map(|piece| match *piece {
244 OutlinePiece::Line { from, to } => Some(OutlinePiece::Line { from: [from[0], lift + along * from[1]], to: [to[0], lift + along * to[1]] }),
245 OutlinePiece::Arc { centre, radius, start, end } => {
246 if along > 0.0 {
248 Some(OutlinePiece::Arc { centre: [centre[0], lift + centre[1]], radius, start, end })
249 } else {
250 Some(OutlinePiece::Arc { centre: [centre[0], lift - centre[1]], radius, start: -start, end: -end })
251 }
252 }
253 OutlinePiece::Ellipse { .. } => None,
254 })
255 .collect::<Option<_>>()?;
256 let tangent = path.control[1].sub(start);
257 let x = tangent.sub(up.scale(tangent.dot(up))).normalized().or_else(|_| up.perpendicular()).ok()?;
258 let y = up.cross(x);
259 let flat = |p: Vec3| [p.sub(start).dot(x), p.sub(start).dot(y)];
260 let mut slot = UprightSlot { origin: start, x, y, up, curve: path.control.map(flat), meridian, heights: [0.0; 2] };
261 if !slot.regular() {
262 return None;
263 }
264 let ends = slot.meridian.iter().flat_map(|piece| match *piece {
267 OutlinePiece::Line { from, to } => vec![from[1], to[1]],
268 OutlinePiece::Arc { centre, radius, start, end } => {
269 let mut hs = vec![centre[1] + radius * start.sin(), centre[1] + radius * end.sin()];
270 for a in turns_within(std::f64::consts::FRAC_PI_2, start.min(end), start.max(end)).chain(turns_within(-std::f64::consts::FRAC_PI_2, start.min(end), start.max(end))) {
271 hs.push(centre[1] + radius * a.sin());
272 }
273 hs
274 }
275 OutlinePiece::Ellipse { .. } => vec![],
276 });
277 let (low, high) = ends.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), h| (lo.min(h), hi.max(h)));
278 if !(high > low) {
279 return None;
280 }
281 slot.heights = [low, high];
282 if !slot.sections_are_discs() {
283 return None;
284 }
285 Some(slot)
286}
287
288impl UprightSlot {
289 fn sections_are_discs(&self) -> bool {
296 let [low, high] = self.heights;
297 let tol = 1e-12 * (high - low).abs().max(1e-300);
299 let tol_r = 1e-12 * self.widest().max(1e-300);
300 let ends = |piece: &OutlinePiece| -> Option<([f64; 2], [f64; 2])> {
301 match *piece {
302 OutlinePiece::Line { from, to } => Some((from, to)),
303 OutlinePiece::Arc { centre, radius, start, end } => Some((
304 [centre[0] + radius * start.cos(), centre[1] + radius * start.sin()],
305 [centre[0] + radius * end.cos(), centre[1] + radius * end.sin()],
306 )),
307 OutlinePiece::Ellipse { .. } => None,
308 }
309 };
310 let on_axis = |p: [f64; 2]| p[0].abs() <= tol_r;
311 let axis_piece = |piece: &OutlinePiece| matches!(*piece, OutlinePiece::Line { from, to } if on_axis(from) && on_axis(to) && (from[1] - to[1]).abs() >= high - low - tol);
312 let Some(axis_index) = self.meridian.iter().position(axis_piece) else { return false };
313 let n = self.meridian.len();
315 let chain: Vec<&OutlinePiece> = (1..n).map(|k| &self.meridian[(axis_index + k) % n]).collect();
316 let Some((first, _)) = chain.first().and_then(|p| ends(p)) else { return false };
317 let Some((_, last)) = chain.last().and_then(|p| ends(p)) else { return false };
318 let Some((axis_from, axis_to)) = ends(&self.meridian[axis_index]) else { return false };
320 let same = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() <= tol_r && (a[1] - b[1]).abs() <= tol;
321 if !(same(first, axis_to) && same(last, axis_from)) {
322 return false;
323 }
324 let rising = last[1] > first[1];
326 let mut previous = first;
327 let last_index = chain.len() - 1;
328 for (index, piece) in chain.iter().enumerate() {
329 let Some((from, to)) = ends(piece) else { return false };
330 if (from[0] - previous[0]).abs() > tol_r || (from[1] - previous[1]).abs() > tol {
331 return false;
332 }
333 let monotone = match **piece {
334 OutlinePiece::Line { from, to } => {
337 let dh = to[1] - from[1];
338 if dh.abs() <= tol_r.min(tol) {
341 (index == 0 || index == last_index) && ((from[1] - low).abs() <= tol || (from[1] - high).abs() <= tol)
343 } else {
344 (dh > 0.0) == rising
345 }
346 }
347 OutlinePiece::Arc { radius, start, end, .. } => {
348 let (a, b) = (start.min(end), start.max(end));
350 let inner = 1e-12 * (b - a).abs().max(1.0);
351 let turns = turns_within(std::f64::consts::FRAC_PI_2, a + inner, b - inner)
352 .chain(turns_within(-std::f64::consts::FRAC_PI_2, a + inner, b - inner))
353 .next()
354 .is_some();
355 !turns && radius > 0.0 && ((to[1] - from[1] > 0.0) == rising || (to[1] - from[1]).abs() <= tol)
356 }
357 OutlinePiece::Ellipse { .. } => false,
358 };
359 if !monotone {
360 return false;
361 }
362 if index != last_index && on_axis(to) {
365 return false;
366 }
367 let off = match **piece {
372 OutlinePiece::Line { from, to } => from[0] >= -tol_r && to[0] >= -tol_r,
373 OutlinePiece::Arc { centre, radius, start, end } => {
374 let (a, b) = (start.min(end), start.max(end));
375 let inner = 1e-12 * (b - a).abs().max(1.0);
376 let ends_in = centre[0] + radius * start.cos() >= -tol_r && centre[0] + radius * end.cos() >= -tol_r;
379 ends_in && (turns_within(std::f64::consts::PI, a + inner, b - inner).next().is_none() || centre[0] - radius > tol_r)
380 }
381 OutlinePiece::Ellipse { .. } => false,
382 };
383 if !off {
384 return false;
385 }
386 previous = to;
387 }
388 true
389 }
390
391 fn regular(&self) -> bool {
395 let c = &self.curve;
396 let polygon = (0..3).map(|k| sub(c[k + 1], c[k])).map(|d| 3.0 * dot(d, d).sqrt()).fold(0.0f64, f64::max);
397 if !(polygon > 0.0) {
398 return false;
399 }
400 let speed2 = |t: f64| {
401 let d = self.derivative(t);
402 dot(d, d)
403 };
404 let slope = |t: f64| dot(self.derivative(t), self.second(t));
405 let mut least = speed2(0.0).min(speed2(1.0));
406 let n = 256;
407 let mut previous = slope(0.0);
408 for k in 1..=n {
409 let t1 = k as f64 / n as f64;
410 let current = slope(t1);
411 if (previous < 0.0) != (current < 0.0) {
412 let (mut a, mut b, mut sa) = ((k - 1) as f64 / n as f64, t1, previous);
413 for _ in 0..100 {
414 let m = 0.5 * (a + b);
415 let sm = slope(m);
416 if (sm < 0.0) == (sa < 0.0) {
417 a = m;
418 sa = sm;
419 } else {
420 b = m;
421 }
422 }
423 least = least.min(speed2(0.5 * (a + b)));
424 }
425 previous = current;
426 }
427 least.sqrt() >= 1e-4 * polygon
428 }
429
430 fn crossings(&self, h: f64) -> Vec<f64> {
432 let mut found: Vec<f64> = Vec::new();
433 for piece in &self.meridian {
434 match *piece {
435 OutlinePiece::Line { from, to } => {
436 let (a, b) = (from[1] - h, to[1] - h);
437 if a == 0.0 && b == 0.0 {
438 continue;
439 }
440 if (a <= 0.0 && b >= 0.0) || (a >= 0.0 && b <= 0.0) {
441 let s = a / (a - b);
442 found.push(from[0] + s * (to[0] - from[0]));
443 }
444 }
445 OutlinePiece::Arc { centre, radius, start, end } => {
446 let s = (h - centre[1]) / radius;
447 if s.abs() > 1.0 {
448 continue;
449 }
450 let base = s.asin();
451 for a in [base, std::f64::consts::PI - base] {
452 for angle in turns_within(a, start.min(end), start.max(end)) {
453 found.push(centre[0] + radius * angle.cos());
454 }
455 }
456 }
457 OutlinePiece::Ellipse { .. } => {}
458 }
459 }
460 let widest = found.iter().fold(0.0f64, |m, r| m.max(r.abs()));
462 let floor = 1e-12 * widest;
463 let mut off: Vec<f64> = found.into_iter().filter(|r| *r > floor).collect();
464 off.sort_by(f64::total_cmp);
465 off.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * a.abs());
466 off
467 }
468
469 pub fn radius(&self, h: f64) -> f64 {
471 if !(h >= self.heights[0] && h <= self.heights[1]) {
472 return 0.0;
473 }
474 self.crossings(h).last().copied().unwrap_or(0.0)
475 }
476
477 fn point(&self, t: f64) -> [f64; 2] {
478 let c = &self.curve;
479 let s = 1.0 - t;
480 let w = [s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t];
481 [(0..4).map(|k| w[k] * c[k][0]).sum(), (0..4).map(|k| w[k] * c[k][1]).sum()]
482 }
483
484 fn derivative(&self, t: f64) -> [f64; 2] {
485 let c = &self.curve;
486 let s = 1.0 - t;
487 let w = [3.0 * s * s, 6.0 * s * t, 3.0 * t * t];
488 let d = [sub(c[1], c[0]), sub(c[2], c[1]), sub(c[3], c[2])];
489 [(0..3).map(|k| w[k] * d[k][0]).sum(), (0..3).map(|k| w[k] * d[k][1]).sum()]
490 }
491
492 fn second(&self, t: f64) -> [f64; 2] {
493 let c = &self.curve;
494 let a = [c[2][0] - 2.0 * c[1][0] + c[0][0], c[2][1] - 2.0 * c[1][1] + c[0][1]];
495 let b = [c[3][0] - 2.0 * c[2][0] + c[1][0], c[3][1] - 2.0 * c[2][1] + c[1][1]];
496 [6.0 * ((1.0 - t) * a[0] + t * b[0]), 6.0 * ((1.0 - t) * a[1] + t * b[1])]
497 }
498
499 pub fn distance(&self, q: [f64; 2]) -> (f64, f64) {
507 let at = |t: f64| {
508 let r = sub(self.point(t), q);
509 dot(r, r)
510 };
511 let mut best = (at(0.0), 0.0);
512 let end = at(1.0);
513 if end < best.0 {
514 best = (end, 1.0);
515 }
516 for t in self.stationary(q) {
517 let d2 = at(t);
518 if d2 < best.0 {
519 best = (d2, t);
520 }
521 }
522 (best.0.sqrt(), best.1)
523 }
524
525 fn stationary(&self, q: [f64; 2]) -> Vec<f64> {
527 let c = &self.curve;
529 let mut g = [0.0f64; 6];
530 for k in 0..2 {
531 let (p0, p1, p2, p3) = (c[0][k], c[1][k], c[2][k], c[3][k]);
532 let a = [p0 - q[k], 3.0 * (p1 - p0), 3.0 * (p2 - 2.0 * p1 + p0), p3 - 3.0 * p2 + 3.0 * p1 - p0];
533 let d = [a[1], 2.0 * a[2], 3.0 * a[3]];
534 for i in 0..4 {
535 for j in 0..3 {
536 g[i + j] += a[i] * d[j];
537 }
538 }
539 }
540 let choose = |n: usize, r: usize| -> f64 { (0..r).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64) };
542 let mut bern = [0.0f64; 6];
543 for k in 0..6 {
544 bern[k] = (0..=k).map(|i| choose(k, i) / choose(5, i) * g[i]).sum();
545 }
546 let value = |t: f64| g.iter().rev().fold(0.0, |acc, &x| acc * t + x);
547 let size = bern.iter().fold(0.0f64, |m, b| m.max(b.abs()));
550 if !(size > 0.0 && size.is_finite()) {
551 return Vec::new();
552 }
553 let mut roots = Vec::new();
554 let mut spans = 0usize;
555 let mut stack: Vec<([f64; 6], f64, f64, u32)> = vec![(bern, 0.0, 1.0, 0)];
556 while let Some((b, lo, hi, depth)) = stack.pop() {
557 spans += 1;
559 if spans > 4096 {
560 roots.push(0.5 * (lo + hi));
561 continue;
562 }
563 let changes = (0..5).filter(|&i| (b[i] < 0.0) != (b[i + 1] < 0.0) || b[i] == 0.0).count() + usize::from(b[5] == 0.0);
564 if changes == 0 {
565 continue;
566 }
567 let (glo, ghi) = (value(lo), value(hi));
568 if changes == 1 && (glo < 0.0) != (ghi < 0.0) {
569 let (mut a, mut z, mut ga) = (lo, hi, glo);
571 for _ in 0..200 {
572 let m = 0.5 * (a + z);
573 if m <= a || m >= z {
574 break;
575 }
576 let gm = value(m);
577 if gm == 0.0 {
578 a = m;
579 z = m;
580 break;
581 }
582 if (gm < 0.0) == (ga < 0.0) {
583 a = m;
584 ga = gm;
585 } else {
586 z = m;
587 }
588 }
589 let mut t = 0.5 * (a + z);
592 for _ in 0..4 {
593 let r = sub(self.point(t), q);
594 let d = self.derivative(t);
595 let slope = dot(d, d) + dot(r, self.second(t));
596 if !(slope != 0.0 && slope.is_finite()) {
597 break;
598 }
599 let next = t - dot(r, d) / slope;
600 if !(next >= lo && next <= hi) {
601 break;
602 }
603 t = next;
604 }
605 roots.push(t);
606 continue;
607 }
608 if depth >= 60 || hi - lo <= 1e-15 {
609 roots.push(0.5 * (lo + hi));
611 continue;
612 }
613 let mut left = [0.0f64; 6];
615 let mut right = [0.0f64; 6];
616 let mut work = b;
617 for level in 0..6 {
618 left[level] = work[0];
619 right[5 - level] = work[5 - level];
620 for i in 0..5 - level {
621 work[i] = 0.5 * (work[i] + work[i + 1]);
622 }
623 }
624 let mid = 0.5 * (lo + hi);
625 stack.push((right, mid, hi, depth + 1));
626 stack.push((left, lo, mid, depth + 1));
627 }
628 roots
629 }
630
631 pub fn contains(&self, p: Vec3) -> bool {
634 let r = p.sub(self.origin);
635 let h = r.dot(self.up);
636 if !(h >= self.heights[0] && h <= self.heights[1]) {
637 return false;
638 }
639 self.distance([r.dot(self.x), r.dot(self.y)]).0 <= self.radius(h)
641 }
642
643 pub fn level_loops(&self, rho: f64, cell: f64) -> Vec<Vec<[f64; 2]>> {
652 if !(cell > 0.0 && cell.is_finite() && rho >= 0.0 && rho.is_finite()) {
653 return Vec::new();
654 }
655 let (lo, hi) = self.curve.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), c| {
656 ([lo[0].min(c[0]), lo[1].min(c[1])], [hi[0].max(c[0]), hi[1].max(c[1])])
657 });
658 let pad = rho + 2.0 * cell;
659 let (x0, y0) = (lo[0] - pad, lo[1] - pad);
660 let (wx, wy) = (((hi[0] - lo[0] + 2.0 * pad) / cell).ceil(), ((hi[1] - lo[1] + 2.0 * pad) / cell).ceil());
661 if !(wx.is_finite() && wy.is_finite() && (wx + 1.0) * (wy + 1.0) <= 1e8) {
663 return Vec::new();
664 }
665 let (nx, ny) = (wx as usize + 1, wy as usize + 1);
666 let node = |i: usize, j: usize| [x0 + cell * i as f64, y0 + cell * j as f64];
667 let f = |p: [f64; 2]| self.distance(p).0 - rho;
668 let bound = sign_bound_on().then(|| {
675 let samples: Vec<[f64; 2]> = (0..=32).map(|k| self.point(k as f64 / 32.0)).collect();
676 let hull = convex_hull(&self.curve);
677 let scale = rho + (hi[0] - lo[0]).abs() + (hi[1] - lo[1]).abs();
678 (samples, hull, 1e-9 * scale)
679 });
680 let sign = |p: [f64; 2]| -> f64 {
681 if let Some((samples, hull, margin)) = &bound {
682 if hull_distance(hull, p) > rho + margin {
683 return 1.0;
684 }
685 if samples.iter().any(|&c| {
686 let r = sub(c, p);
687 dot(r, r).sqrt() < rho - margin
688 }) {
689 return -1.0;
690 }
691 }
692 f(p)
693 };
694 let values: Vec<f64> = (0..ny).flat_map(|j| (0..nx).map(move |i| (i, j))).map(|(i, j)| sign(node(i, j))).collect();
695 let value = |i: usize, j: usize| values[j * nx + i];
696 let crossing = |a: [f64; 2], b: [f64; 2]| -> [f64; 2] {
698 let (mut fa, mut lo, mut hi) = (f(a), 0.0f64, 1.0f64);
699 for _ in 0..60 {
700 let m = 0.5 * (lo + hi);
701 let fm = f([a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m]);
702 if (fm <= 0.0) == (fa <= 0.0) {
703 lo = m;
704 fa = fm;
705 } else {
706 hi = m;
707 }
708 }
709 let m = 0.5 * (lo + hi);
710 [a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m]
711 };
712 let h_edge = |i: usize, j: usize| 2 * (j * nx + i);
714 let v_edge = |i: usize, j: usize| 2 * (j * nx + i) + 1;
715 let mut next: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
716 for j in 0..ny - 1 {
717 for i in 0..nx - 1 {
718 let inside = [value(i, j) <= 0.0, value(i + 1, j) <= 0.0, value(i + 1, j + 1) <= 0.0, value(i, j + 1) <= 0.0];
719 let edges = [h_edge(i, j), v_edge(i + 1, j), h_edge(i, j + 1), v_edge(i, j)];
721 let mut exits: Vec<usize> = Vec::new();
724 let mut entries: Vec<usize> = Vec::new();
725 for k in 0..4 {
726 let (a, b) = (inside[k], inside[(k + 1) % 4]);
727 if a && !b {
728 exits.push(k);
729 } else if !a && b {
730 entries.push(k);
731 }
732 }
733 match (exits.as_slice(), entries.as_slice()) {
734 ([e], [n]) => {
735 next.insert(edges[*n], edges[*e]);
736 }
737 ([e0, e1], [n0, n1]) => {
738 let middle = f([x0 + cell * (i as f64 + 0.5), y0 + cell * (j as f64 + 0.5)]) <= 0.0;
740 let pair = |n: usize, exits: [usize; 2]| -> usize {
742 let after = |e: usize| (e + 4 - n) % 4;
743 if middle { *exits.iter().max_by_key(|&&e| after(e)).unwrap() } else { *exits.iter().min_by_key(|&&e| after(e)).unwrap() }
744 };
745 next.insert(edges[*n0], edges[pair(*n0, [*e0, *e1])]);
746 next.insert(edges[*n1], edges[pair(*n1, [*e0, *e1])]);
747 }
748 _ => {}
749 }
750 }
751 }
752 let edge_point = |id: usize| -> [f64; 2] {
754 let (cell_id, vertical) = (id / 2, id % 2 == 1);
755 let (i, j) = (cell_id % nx, cell_id / nx);
756 let (a, b) = if vertical { (node(i, j), node(i, j + 1)) } else { (node(i, j), node(i + 1, j)) };
757 if f(a) <= 0.0 { crossing(a, b) } else { crossing(b, a) }
758 };
759 let mut loops = Vec::new();
760 let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
761 let mut starts: Vec<usize> = next.keys().copied().collect();
762 starts.sort_unstable();
763 for start in starts {
764 if seen.contains(&start) {
765 continue;
766 }
767 let mut ring = Vec::new();
768 let mut at = start;
769 while seen.insert(at) {
770 ring.push(edge_point(at));
771 match next.get(&at) {
772 Some(&n) => at = n,
773 None => break,
774 }
775 }
776 if ring.len() >= 3 {
777 ring.reverse();
780 loops.push(ring);
781 }
782 }
783 loops
784 }
785
786 pub fn level_area(&self, rho: f64, cell: f64) -> Option<f64> {
791 if !self.grid_fits(rho, cell) {
792 return None;
793 }
794 Some(
795 self.level_loops(rho, cell)
796 .iter()
797 .map(|ring| {
798 let n = ring.len();
799 0.5 * (0..n).map(|k| ring[k][0] * ring[(k + 1) % n][1] - ring[(k + 1) % n][0] * ring[k][1]).sum::<f64>()
800 })
801 .sum(),
802 )
803 }
804
805 fn grid_fits(&self, rho: f64, cell: f64) -> bool {
808 if !(cell > 0.0 && cell.is_finite() && rho >= 0.0 && rho.is_finite() && cell <= 0.25 * rho) {
811 return false;
812 }
813 let (lo, hi) = self.curve.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), c| {
814 ([lo[0].min(c[0]), lo[1].min(c[1])], [hi[0].max(c[0]), hi[1].max(c[1])])
815 });
816 let pad = rho + 2.0 * cell;
817 let (wx, wy) = (((hi[0] - lo[0] + 2.0 * pad) / cell).ceil(), ((hi[1] - lo[1] + 2.0 * pad) / cell).ceil());
818 wx.is_finite() && wy.is_finite() && (wx + 1.0) * (wy + 1.0) <= 1e8
819 }
820
821 pub fn volume(&self, h0: f64, h1: f64, cell: f64) -> Option<f64> {
829 let (a, b) = (h0.max(self.heights[0]), h1.min(self.heights[1]));
830 if !(b > a) {
831 return Some(0.0);
832 }
833 if !self.grid_fits(self.widest(), cell) {
834 return None;
835 }
836 const X: [f64; 4] = [0.1834346424956498, 0.5255324099163290, 0.7966664774136267, 0.9602898564975363];
839 const W: [f64; 4] = [0.3626837833783620, 0.3137066458778873, 0.2223810344533745, 0.1012285362903763];
840 let gauss = |f: &dyn Fn(f64) -> f64, lo: f64, hi: f64| -> f64 {
841 let mut total = 0.0;
842 for k in 0..4 {
843 let (s0, s1) = (lo + (hi - lo) * k as f64 / 4.0, lo + (hi - lo) * (k + 1) as f64 / 4.0);
844 let (mid, half) = (0.5 * (s0 + s1), 0.5 * (s1 - s0));
845 for i in 0..4 {
846 total += half * W[i] * (f(mid - half * X[i]) + f(mid + half * X[i]));
847 }
848 }
849 total
850 };
851 let mut total = 0.0;
852 for piece in &self.meridian {
853 match *piece {
854 OutlinePiece::Line { from, to } => {
855 let tol_r = 1e-12 * self.widest();
858 if from[0].abs() <= tol_r && to[0].abs() <= tol_r {
859 continue;
860 }
861 let dh = to[1] - from[1];
862 if dh == 0.0 {
863 continue;
864 }
865 let (s0, s1) = (((a - from[1]) / dh).clamp(0.0, 1.0), ((b - from[1]) / dh).clamp(0.0, 1.0));
866 let (lo, hi) = (s0.min(s1), s0.max(s1));
867 if hi <= lo {
868 continue;
869 }
870 let radius = |s: f64| from[0] + s * (to[0] - from[0]);
871 if from[0] == to[0] {
876 total += dh.abs() * (hi - lo) * self.level_area(from[0], cell)?;
877 } else {
878 total += dh.abs() * gauss(&|s| self.level_area(radius(s), cell).unwrap_or(f64::NAN), lo, hi);
879 }
880 }
881 OutlinePiece::Arc { centre, radius, start, end } => {
882 let (t0, t1) = (start.min(end), start.max(end));
885 let height = |t: f64| centre[1] + radius * t.sin();
886 let clip = |h: f64| -> f64 {
887 let (mut lo, mut hi) = (t0, t1);
889 let rising = height(t1) > height(t0);
890 for _ in 0..200 {
891 let m = 0.5 * (lo + hi);
892 if (height(m) < h) == rising { lo = m } else { hi = m }
893 }
894 0.5 * (lo + hi)
895 };
896 let (ha, hb) = (height(t0), height(t1));
897 let (hlo, hhi) = (ha.min(hb), ha.max(hb));
898 let (ca, cb) = (a.max(hlo), b.min(hhi));
899 if cb <= ca {
900 continue;
901 }
902 let (u0, u1) = (clip(ca), clip(cb));
903 let (lo, hi) = (u0.min(u1), u0.max(u1));
904 let f = |t: f64| self.level_area(centre[0] + radius * t.cos(), cell).unwrap_or(f64::NAN) * (radius * t.cos()).abs();
905 total += gauss(&f, lo, hi);
906 }
907 OutlinePiece::Ellipse { .. } => {}
908 }
909 }
910 total.is_finite().then_some(total)
911 }
912
913 fn section_reach(&self) -> f64 {
917 let (o, x, z) = (Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
918 self.meridian
919 .iter()
920 .filter_map(|piece| world_piece(piece, o, x, z).ok())
921 .flat_map(|curve| curve.control_points.into_iter())
922 .filter_map(|c| c.point().ok())
923 .map(|p| p.x.abs())
924 .fold(0.0f64, f64::max)
925 }
926
927 fn widest(&self) -> f64 {
929 self.meridian.iter().map(|piece| piece_extent(piece).0).fold(0.0f64, f64::max)
930 }
931}
932
933fn world_piece(piece: &OutlinePiece, foot: Vec3, out: Vec3, up: Vec3) -> Result<crate::NurbsCurve, String> {
937 let at = |p: [f64; 2]| foot.add(out.scale(p[0])).add(up.scale(p[1]));
938 match *piece {
939 OutlinePiece::Line { from, to } => crate::make_line(at(from), at(to)),
940 OutlinePiece::Arc { centre, radius, start, end } => {
941 let c = at(centre);
942 if end > start {
943 crate::make_arc(c, out, up, radius, start, end)
944 } else {
945 crate::make_arc(c, out, up, radius, end, start)?.reversed()
946 }
947 }
948 OutlinePiece::Ellipse { .. } => Err("an elliptic meridian piece".into()),
949 }
950}
951
952impl UprightSlot {
953 fn chain(&self) -> Option<Vec<OutlinePiece>> {
956 let tol_r = 1e-12 * self.widest();
957 let along_axis = |piece: &OutlinePiece| matches!(*piece, OutlinePiece::Line { from, to } if from[0].abs() <= tol_r && to[0].abs() <= tol_r);
958 let axis_index = self.meridian.iter().position(along_axis)?;
959 let n = self.meridian.len();
960 Some((1..n).map(|k| self.meridian[(axis_index + k) % n].clone()).collect())
961 }
962
963 fn tool_at(&self, t: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
966 let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
967 let p = self.point(t);
968 let foot = self.origin.add(self.x.scale(p[0])).add(self.y.scale(p[1]));
969 let curves: Vec<crate::NurbsCurve> = self.meridian.iter().map(|piece| world_piece(piece, foot, self.x, self.up)).collect::<Result<_, _>>().map_err(refuse)?;
970 crate::revolve_profile_brep(&curves, foot, self.up, std::f64::consts::TAU).map_err(|e| {
973 crate::KernelRefusal::input(crate::KernelStage::Collect, "upright_scale", format!("uprightStroke: the tool is outside the construction's range: the revolve builder declined it ({e})"))
974 })
975 }
976
977 fn section_at(&self, t: f64) -> Result<Vec<crate::NurbsCurve>, String> {
981 let chain = self.chain().ok_or("no axis piece")?;
982 let p = self.point(t);
983 let d = self.derivative(t);
984 let length = dot(d, d).sqrt();
985 if !(length > 0.0) {
986 return Err("the curve stops".into());
987 }
988 let normal = [-d[1] / length, d[0] / length];
989 let foot = self.origin.add(self.x.scale(p[0])).add(self.y.scale(p[1]));
990 let left = self.x.scale(normal[0]).add(self.y.scale(normal[1]));
991 let mut loop_curves: Vec<crate::NurbsCurve> = chain.iter().map(|piece| world_piece(piece, foot, left, self.up)).collect::<Result<_, _>>()?;
992 let mirrored: Vec<crate::NurbsCurve> = chain.iter().rev().map(|piece| world_piece(piece, foot, left.scale(-1.0), self.up).and_then(|c| c.reversed())).collect::<Result<_, _>>()?;
993 loop_curves.extend(mirrored);
994 Ok(loop_curves)
995 }
996
997 fn world_piece_of_curve(&self, a: f64, b: f64) -> Result<crate::NurbsCurve, String> {
999 let split = |c: [[f64; 2]; 4], t: f64| -> ([[f64; 2]; 4], [[f64; 2]; 4]) {
1000 let l = |x: [f64; 2], y: [f64; 2]| [x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t];
1001 let (p01, p12, p23) = (l(c[0], c[1]), l(c[1], c[2]), l(c[2], c[3]));
1002 let (p012, p123) = (l(p01, p12), l(p12, p23));
1003 let m = l(p012, p123);
1004 ([c[0], p01, p012, m], [m, p123, p23, c[3]])
1005 };
1006 let right = if a > 0.0 { split(self.curve, a).1 } else { self.curve };
1007 let piece = if b < 1.0 { split(right, (b - a) / (1.0 - a)).0 } else { right };
1008 let world = |p: [f64; 2]| crate::Vec4 { x: self.origin.x + self.x.x * p[0] + self.y.x * p[1], y: self.origin.y + self.x.y * p[0] + self.y.y * p[1], z: self.origin.z + self.x.z * p[0] + self.y.z * p[1], w: 1.0 };
1009 crate::NurbsCurve::new(3, vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], piece.iter().map(|p| world(*p)).collect())
1010 }
1011
1012 fn section_sweep(&self, a: f64, b: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1014 let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
1015 let section = self.section_at(a).map_err(refuse)?;
1016 let path = self.world_piece_of_curve(a, b).map_err(refuse)?;
1017 let chain = crate::SweepPath::new(vec![path], Vec::new())?;
1018 crate::sweep_profile_along_chain(§ion, &chain, 0.0, None, None, crate::SectionPlacement::Rigid, "an upright tool's section along one piece of a cubic")
1019 }
1020
1021 pub fn pieces(&self) -> Vec<(f64, f64, bool)> {
1026 let widest = self.section_reach().max(self.widest());
1030 let c = &self.curve;
1036 let polygon = (0..3).map(|k| 3.0 * dot(sub(c[k + 1], c[k]), sub(c[k + 1], c[k])).sqrt()).fold(0.0f64, f64::max);
1037 let second_most = { let (a, b) = (self.second(0.0), self.second(1.0)); dot(a, a).sqrt().max(dot(b, b).sqrt()) };
1038 let third = { let d = sub(self.second(1.0), self.second(0.0)); dot(d, d).sqrt() };
1039 let cross = |t: f64| { let (d, dd) = (self.derivative(t), self.second(t)); (d[0] * dd[1] - d[1] * dd[0]).abs() };
1040 let speed = |t: f64| dot(self.derivative(t), self.derivative(t)).sqrt();
1041 let threshold = 0.99 / widest;
1042 let may_be_tight = |a: f64, b: f64| -> bool {
1043 let (m, h) = (0.5 * (a + b), 0.5 * (b - a));
1044 let low = speed(m) - second_most * h;
1045 if !(low > 0.0) {
1046 return true;
1047 }
1048 (cross(m) + polygon * third * h) / (low * low * low) >= threshold
1049 };
1050 let is_tight_at = |t: f64| cross(t) / speed(t).powi(3) >= threshold;
1051 let mut tight_spans: Vec<(f64, f64)> = Vec::new();
1052 let mut stack: Vec<(f64, f64, u32)> = (0..256).rev().map(|k| (k as f64 / 256.0, (k + 1) as f64 / 256.0, 0)).collect();
1053 let mut read = 0usize;
1056 while let Some((a, b, depth)) = stack.pop() {
1057 read += 1;
1058 if !may_be_tight(a, b) {
1059 continue;
1060 }
1061 if read > 1 << 20 || is_tight_at(0.5 * (a + b)) || depth >= 40 {
1063 match tight_spans.last_mut() {
1064 Some(last) if (last.1 - a).abs() <= 1e-15 => last.1 = b,
1065 _ => tight_spans.push((a, b)),
1066 }
1067 continue;
1068 }
1069 let m = 0.5 * (a + b);
1070 stack.push((m, b, depth + 1));
1071 stack.push((a, m, depth + 1));
1072 }
1073 let mut runs: Vec<(f64, f64, bool)> = Vec::new();
1075 let mut at = 0.0;
1076 for (a, b) in tight_spans {
1077 if a > at {
1078 runs.push((at, a, false));
1079 }
1080 runs.push((a, b, true));
1081 at = b;
1082 }
1083 if at < 1.0 {
1084 runs.push((at, 1.0, false));
1085 }
1086 let heading = |t: f64| {
1089 let d = self.derivative(t);
1090 d[1].atan2(d[0])
1091 };
1092 let most = 150f64.to_radians();
1093 let mut pieces = Vec::new();
1094 for (a, b, is_tight) in runs {
1095 if !(b > a) {
1096 continue;
1097 }
1098 let steps = 2048;
1099 let mut turn = 0.0;
1100 let mut previous = heading(a);
1101 let mut start = a;
1102 for k in 1..=steps {
1103 let t = a + (b - a) * k as f64 / steps as f64;
1104 let h = heading(t);
1105 let mut delta = h - previous;
1106 while delta > std::f64::consts::PI { delta -= std::f64::consts::TAU; }
1107 while delta < -std::f64::consts::PI { delta += std::f64::consts::TAU; }
1108 turn += delta.abs();
1109 previous = h;
1110 if turn >= most && k < steps {
1111 pieces.push((start, t, is_tight));
1112 start = t;
1113 turn = 0.0;
1114 }
1115 }
1116 pieces.push((start, b, is_tight));
1117 }
1118 pieces
1119 }
1120
1121 pub fn turns_tighter(&self) -> bool {
1125 self.pieces().iter().any(|p| p.2)
1126 }
1127
1128 pub fn direct_solid(&self) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1131 let solid = direct::direct_solid(self)?;
1132 if let Some(issue) = solid.validate().first() {
1133 return Err(crate::KernelRefusal::unsupported(crate::KernelStage::Collect, "upright_direct_invalid", format!("uprightDirect: the solid does not validate: {}", issue.message)));
1134 }
1135 Ok(solid)
1136 }
1137
1138 pub fn solid(&self) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1143 let small_arc = self.meridian.iter().any(|piece| matches!(*piece, OutlinePiece::Arc { radius, .. } if radius < 1e-6));
1147 let widest = self.widest();
1148 if small_arc || !(5e-2..=1e6).contains(&widest) {
1149 return Err(crate::KernelRefusal::input(
1150 crate::KernelStage::Collect,
1151 "upright_scale",
1152 format!("uprightStroke: a tool {widest:e} wide is outside the construction's range (5e-2 to 1e6, its arcs at least 1e-6: the revolve builder reads 1e-3 from the axis)"),
1153 ));
1154 }
1155 let pieces = self.pieces();
1156 if let Some(&(a, b, _)) = pieces.iter().find(|p| p.2) {
1161 let declined = if direct::upright_direct_on() {
1162 match self.direct_solid() {
1163 Ok(solid) => return Ok(solid),
1164 Err(e) => format!(" (the direct build declined: {})", e.message),
1165 }
1166 } else {
1167 String::new()
1168 };
1169 return Err(crate::KernelRefusal::unsupported(
1170 crate::KernelStage::Collect,
1171 "upright_tight_turn",
1172 format!("uprightStroke: the curve turns tighter than the tool reaches over [{a:.4}, {b:.4}]; its folded concave wall is not built{declined}"),
1173 ));
1174 }
1175 let mut whole = self.tool_at(0.0)?;
1179 for (index, &(_, b, _)) in pieces.iter().enumerate() {
1180 whole = crate::boolean_operation_nary(&[whole, self.tool_at(b)?], crate::BooleanOperation::Union)
1181 .map_err(|e| e.with_message(|m| format!("{m} (adding the tool at break {index}, t = {b})")))?;
1182 }
1183 for (index, &(a, b, _)) in pieces.iter().enumerate() {
1184 whole = crate::boolean_operation_nary(&[whole, self.section_sweep(a, b)?], crate::BooleanOperation::Union)
1185 .map_err(|e| e.with_message(|m| format!("{m} (adding sweep {index} of {}, [{a}, {b}])", pieces.len())))?;
1186 }
1187 Ok(whole)
1188 }
1189
1190 pub fn stroke(&self, a: f64, b: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1196 let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
1197 if !(0.0 <= a && a < b && b <= 1.0) {
1198 return Err(crate::KernelRefusal::input(crate::KernelStage::Collect, "upright_stroke_range", format!("uprightStroke: the piece [{a}, {b}] is not within the curve's [0, 1]")));
1199 }
1200 let section = self.section_at(a).map_err(refuse)?;
1201 let path = self.world_piece_of_curve(a, b).map_err(refuse)?;
1202 let chain = crate::SweepPath::new(vec![path], Vec::new())?;
1203 let swept = crate::sweep_profile_along_chain(§ion, &chain, 0.0, None, None, crate::SectionPlacement::Rigid, "an upright tool's section along one piece of a cubic")?;
1204 crate::boolean_operation_nary(&[swept, self.tool_at(a)?, self.tool_at(b)?], crate::BooleanOperation::Union)
1205 }
1206}
1207