1use crate::{FrameCurve, OutlinePiece, SolidTool, Vec3};
24
25pub const ENVELOPE: f64 = 1e6;
33
34pub fn upright_slot_on() -> bool {
37 crate::switch!("BREP_SWEEP_UPRIGHT_SLOT", false)
38}
39
40pub fn sweep_upright_along(tool: &SolidTool, path: &FrameCurve) -> Option<Result<crate::BrepSolid, crate::KernelRefusal>> {
45 upright_slot(tool, path).map(|slot| slot.solid())
46}
47
48#[derive(Clone, Debug)]
54pub struct UprightSlot {
55 pub origin: Vec3,
57 pub x: Vec3,
58 pub y: Vec3,
59 pub up: Vec3,
60 pub curve: [[f64; 2]; 4],
62 pub meridian: Vec<OutlinePiece>,
64 pub heights: [f64; 2],
66}
67
68fn turns_within(a: f64, lo: f64, hi: f64) -> impl Iterator<Item = f64> {
70 let tau = std::f64::consts::TAU;
71 let (first, last) = (((lo - a) / tau).ceil(), ((hi - a) / tau).floor());
72 let count = if first.is_finite() && last.is_finite() && last >= first && last - first < 1e6 { (last - first) as i64 + 1 } else { 0 };
73 (0..count).map(move |k| a + tau * (first + k as f64))
74}
75
76fn piece_extent(piece: &OutlinePiece) -> (f64, f64) {
79 match *piece {
80 OutlinePiece::Line { from, to } => (from[0].abs().max(to[0].abs()), from[1].abs().max(to[1].abs())),
81 OutlinePiece::Arc { centre, radius, start, end } => {
82 let (a, b) = (start.min(end), start.max(end));
83 let at = |t: f64| [centre[0] + radius * t.cos(), centre[1] + radius * t.sin()];
84 let mut points = vec![at(start), at(end)];
85 for k in [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, -std::f64::consts::FRAC_PI_2] {
86 points.extend(turns_within(k, a, b).take(1).map(at));
87 }
88 points.iter().fold((0.0f64, 0.0f64), |(r, h), p| (r.max(p[0].abs()), h.max(p[1].abs())))
89 }
90 OutlinePiece::Ellipse { .. } => (f64::INFINITY, f64::INFINITY),
91 }
92}
93
94fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
95 [a[0] - b[0], a[1] - b[1]]
96}
97
98fn dot(a: [f64; 2], b: [f64; 2]) -> f64 {
99 a[0] * b[0] + a[1] * b[1]
100}
101
102pub fn upright_slot(tool: &SolidTool, path: &FrameCurve) -> Option<UprightSlot> {
108 let SolidTool::Revolved { axis_origin, axis_direction, radial, meridian } = tool else { return None };
109 let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
110 let pieces_finite = meridian.iter().all(|piece| match *piece {
111 OutlinePiece::Line { from, to } => from.iter().chain(&to).all(|x| x.is_finite()),
112 OutlinePiece::Arc { centre, radius, start, end } => centre.iter().all(|x| x.is_finite()) && radius.is_finite() && start.is_finite() && end.is_finite(),
113 OutlinePiece::Ellipse { .. } => false,
114 });
115 if !(pieces_finite && path.control.iter().all(|p| finite(*p)) && finite(path.up) && finite(*axis_origin) && finite(*axis_direction) && finite(*radial)) {
116 return None;
117 }
118 let unit = |d: Vec3| -> Option<Vec3> {
120 let big = d.x.abs().max(d.y.abs()).max(d.z.abs());
121 if !(big > 0.0 && big.is_finite()) {
122 return None;
123 }
124 let n = d.scale(1.0 / big).normalized().ok()?;
125 ((n.length() - 1.0).abs() <= 1e-12).then_some(n)
126 };
127 let up = unit(path.up)?;
128 let axis = unit(*axis_direction)?;
129 let along = axis.dot(up).signum();
130 let start = path.control[0];
131 let (widest, tall) = meridian.iter().map(piece_extent).fold((0.0f64, 0.0f64), |(r, h), (pr, ph)| (r.max(pr), h.max(ph)));
135 if !(widest > 0.0 && widest.is_finite() && tall.is_finite()) {
136 return None;
137 }
138 if meridian.iter().any(|piece| matches!(*piece, OutlinePiece::Arc { radius, .. } if !(radius > 0.0 && radius <= ENVELOPE * widest))) {
141 return None;
142 }
143 let extent = path.control.iter().map(|p| p.sub(start).length()).fold(0.0f64, f64::max);
145 let one_turn = meridian.iter().all(|piece| match *piece {
146 OutlinePiece::Arc { start, end, .. } => (end - start).abs() <= std::f64::consts::TAU * (1.0 + 1e-12),
147 _ => true,
148 });
149 let sized = |x: f64| (1e-60..=1e60).contains(&x);
152 if !(one_turn && sized(widest) && sized(extent) && sized(tall.max(widest)) && tall <= ENVELOPE * widest && tall >= widest / ENVELOPE && extent <= ENVELOPE * widest && extent >= widest / ENVELOPE) {
153 return None;
154 }
155 let band = 1e-12 * widest;
156 if axis.cross(up).length() * tall.max(widest) > band {
157 return None;
158 }
159 let off = axis_origin.sub(start);
161 if off.sub(up.scale(off.dot(up))).length() > band {
162 return None;
163 }
164 if path.control.iter().any(|p| p.sub(start).dot(up).abs() > band) {
165 return None;
166 }
167 let radial_unit = unit(*radial)?;
170 if radial_unit.dot(axis).abs() > 1e-12 {
171 return None;
172 }
173 if path.control.iter().all(|p| p.sub(start).length() <= band) {
175 return None;
176 }
177 let lift = off.dot(up);
178 let meridian: Vec<OutlinePiece> = meridian
179 .iter()
180 .map(|piece| match *piece {
181 OutlinePiece::Line { from, to } => Some(OutlinePiece::Line { from: [from[0], lift + along * from[1]], to: [to[0], lift + along * to[1]] }),
182 OutlinePiece::Arc { centre, radius, start, end } => {
183 if along > 0.0 {
185 Some(OutlinePiece::Arc { centre: [centre[0], lift + centre[1]], radius, start, end })
186 } else {
187 Some(OutlinePiece::Arc { centre: [centre[0], lift - centre[1]], radius, start: -start, end: -end })
188 }
189 }
190 OutlinePiece::Ellipse { .. } => None,
191 })
192 .collect::<Option<_>>()?;
193 let tangent = path.control[1].sub(start);
194 let x = tangent.sub(up.scale(tangent.dot(up))).normalized().or_else(|_| up.perpendicular()).ok()?;
195 let y = up.cross(x);
196 let flat = |p: Vec3| [p.sub(start).dot(x), p.sub(start).dot(y)];
197 let mut slot = UprightSlot { origin: start, x, y, up, curve: path.control.map(flat), meridian, heights: [0.0; 2] };
198 if !slot.regular() {
199 return None;
200 }
201 let ends = slot.meridian.iter().flat_map(|piece| match *piece {
204 OutlinePiece::Line { from, to } => vec![from[1], to[1]],
205 OutlinePiece::Arc { centre, radius, start, end } => {
206 let mut hs = vec![centre[1] + radius * start.sin(), centre[1] + radius * end.sin()];
207 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))) {
208 hs.push(centre[1] + radius * a.sin());
209 }
210 hs
211 }
212 OutlinePiece::Ellipse { .. } => vec![],
213 });
214 let (low, high) = ends.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), h| (lo.min(h), hi.max(h)));
215 if !(high > low) {
216 return None;
217 }
218 slot.heights = [low, high];
219 if !slot.sections_are_discs() {
220 return None;
221 }
222 Some(slot)
223}
224
225impl UprightSlot {
226 fn sections_are_discs(&self) -> bool {
233 let [low, high] = self.heights;
234 let tol = 1e-12 * (high - low).abs().max(1e-300);
236 let tol_r = 1e-12 * self.widest().max(1e-300);
237 let ends = |piece: &OutlinePiece| -> Option<([f64; 2], [f64; 2])> {
238 match *piece {
239 OutlinePiece::Line { from, to } => Some((from, to)),
240 OutlinePiece::Arc { centre, radius, start, end } => Some((
241 [centre[0] + radius * start.cos(), centre[1] + radius * start.sin()],
242 [centre[0] + radius * end.cos(), centre[1] + radius * end.sin()],
243 )),
244 OutlinePiece::Ellipse { .. } => None,
245 }
246 };
247 let on_axis = |p: [f64; 2]| p[0].abs() <= tol_r;
248 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);
249 let Some(axis_index) = self.meridian.iter().position(axis_piece) else { return false };
250 let n = self.meridian.len();
252 let chain: Vec<&OutlinePiece> = (1..n).map(|k| &self.meridian[(axis_index + k) % n]).collect();
253 let Some((first, _)) = chain.first().and_then(|p| ends(p)) else { return false };
254 let Some((_, last)) = chain.last().and_then(|p| ends(p)) else { return false };
255 let Some((axis_from, axis_to)) = ends(&self.meridian[axis_index]) else { return false };
257 let same = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() <= tol_r && (a[1] - b[1]).abs() <= tol;
258 if !(same(first, axis_to) && same(last, axis_from)) {
259 return false;
260 }
261 let rising = last[1] > first[1];
263 let mut previous = first;
264 let last_index = chain.len() - 1;
265 for (index, piece) in chain.iter().enumerate() {
266 let Some((from, to)) = ends(piece) else { return false };
267 if (from[0] - previous[0]).abs() > tol_r || (from[1] - previous[1]).abs() > tol {
268 return false;
269 }
270 let monotone = match **piece {
271 OutlinePiece::Line { from, to } => {
274 let dh = to[1] - from[1];
275 if dh.abs() <= tol_r.min(tol) {
278 (index == 0 || index == last_index) && ((from[1] - low).abs() <= tol || (from[1] - high).abs() <= tol)
280 } else {
281 (dh > 0.0) == rising
282 }
283 }
284 OutlinePiece::Arc { radius, start, end, .. } => {
285 let (a, b) = (start.min(end), start.max(end));
287 let inner = 1e-12 * (b - a).abs().max(1.0);
288 let turns = turns_within(std::f64::consts::FRAC_PI_2, a + inner, b - inner)
289 .chain(turns_within(-std::f64::consts::FRAC_PI_2, a + inner, b - inner))
290 .next()
291 .is_some();
292 !turns && radius > 0.0 && ((to[1] - from[1] > 0.0) == rising || (to[1] - from[1]).abs() <= tol)
293 }
294 OutlinePiece::Ellipse { .. } => false,
295 };
296 if !monotone {
297 return false;
298 }
299 if index != last_index && on_axis(to) {
302 return false;
303 }
304 let off = match **piece {
309 OutlinePiece::Line { from, to } => from[0] >= -tol_r && to[0] >= -tol_r,
310 OutlinePiece::Arc { centre, radius, start, end } => {
311 let (a, b) = (start.min(end), start.max(end));
312 let inner = 1e-12 * (b - a).abs().max(1.0);
313 let ends_in = centre[0] + radius * start.cos() >= -tol_r && centre[0] + radius * end.cos() >= -tol_r;
316 ends_in && (turns_within(std::f64::consts::PI, a + inner, b - inner).next().is_none() || centre[0] - radius > tol_r)
317 }
318 OutlinePiece::Ellipse { .. } => false,
319 };
320 if !off {
321 return false;
322 }
323 previous = to;
324 }
325 true
326 }
327
328 fn regular(&self) -> bool {
332 let c = &self.curve;
333 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);
334 if !(polygon > 0.0) {
335 return false;
336 }
337 let speed2 = |t: f64| {
338 let d = self.derivative(t);
339 dot(d, d)
340 };
341 let slope = |t: f64| dot(self.derivative(t), self.second(t));
342 let mut least = speed2(0.0).min(speed2(1.0));
343 let n = 256;
344 let mut previous = slope(0.0);
345 for k in 1..=n {
346 let t1 = k as f64 / n as f64;
347 let current = slope(t1);
348 if (previous < 0.0) != (current < 0.0) {
349 let (mut a, mut b, mut sa) = ((k - 1) as f64 / n as f64, t1, previous);
350 for _ in 0..100 {
351 let m = 0.5 * (a + b);
352 let sm = slope(m);
353 if (sm < 0.0) == (sa < 0.0) {
354 a = m;
355 sa = sm;
356 } else {
357 b = m;
358 }
359 }
360 least = least.min(speed2(0.5 * (a + b)));
361 }
362 previous = current;
363 }
364 least.sqrt() >= 1e-4 * polygon
365 }
366
367 fn crossings(&self, h: f64) -> Vec<f64> {
369 let mut found: Vec<f64> = Vec::new();
370 for piece in &self.meridian {
371 match *piece {
372 OutlinePiece::Line { from, to } => {
373 let (a, b) = (from[1] - h, to[1] - h);
374 if a == 0.0 && b == 0.0 {
375 continue;
376 }
377 if (a <= 0.0 && b >= 0.0) || (a >= 0.0 && b <= 0.0) {
378 let s = a / (a - b);
379 found.push(from[0] + s * (to[0] - from[0]));
380 }
381 }
382 OutlinePiece::Arc { centre, radius, start, end } => {
383 let s = (h - centre[1]) / radius;
384 if s.abs() > 1.0 {
385 continue;
386 }
387 let base = s.asin();
388 for a in [base, std::f64::consts::PI - base] {
389 for angle in turns_within(a, start.min(end), start.max(end)) {
390 found.push(centre[0] + radius * angle.cos());
391 }
392 }
393 }
394 OutlinePiece::Ellipse { .. } => {}
395 }
396 }
397 let widest = found.iter().fold(0.0f64, |m, r| m.max(r.abs()));
399 let floor = 1e-12 * widest;
400 let mut off: Vec<f64> = found.into_iter().filter(|r| *r > floor).collect();
401 off.sort_by(f64::total_cmp);
402 off.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * a.abs());
403 off
404 }
405
406 pub fn radius(&self, h: f64) -> f64 {
408 if !(h >= self.heights[0] && h <= self.heights[1]) {
409 return 0.0;
410 }
411 self.crossings(h).last().copied().unwrap_or(0.0)
412 }
413
414 fn point(&self, t: f64) -> [f64; 2] {
415 let c = &self.curve;
416 let s = 1.0 - t;
417 let w = [s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t];
418 [(0..4).map(|k| w[k] * c[k][0]).sum(), (0..4).map(|k| w[k] * c[k][1]).sum()]
419 }
420
421 fn derivative(&self, t: f64) -> [f64; 2] {
422 let c = &self.curve;
423 let s = 1.0 - t;
424 let w = [3.0 * s * s, 6.0 * s * t, 3.0 * t * t];
425 let d = [sub(c[1], c[0]), sub(c[2], c[1]), sub(c[3], c[2])];
426 [(0..3).map(|k| w[k] * d[k][0]).sum(), (0..3).map(|k| w[k] * d[k][1]).sum()]
427 }
428
429 fn second(&self, t: f64) -> [f64; 2] {
430 let c = &self.curve;
431 let a = [c[2][0] - 2.0 * c[1][0] + c[0][0], c[2][1] - 2.0 * c[1][1] + c[0][1]];
432 let b = [c[3][0] - 2.0 * c[2][0] + c[1][0], c[3][1] - 2.0 * c[2][1] + c[1][1]];
433 [6.0 * ((1.0 - t) * a[0] + t * b[0]), 6.0 * ((1.0 - t) * a[1] + t * b[1])]
434 }
435
436 pub fn distance(&self, q: [f64; 2]) -> (f64, f64) {
444 let at = |t: f64| {
445 let r = sub(self.point(t), q);
446 dot(r, r)
447 };
448 let mut best = (at(0.0), 0.0);
449 let end = at(1.0);
450 if end < best.0 {
451 best = (end, 1.0);
452 }
453 for t in self.stationary(q) {
454 let d2 = at(t);
455 if d2 < best.0 {
456 best = (d2, t);
457 }
458 }
459 (best.0.sqrt(), best.1)
460 }
461
462 fn stationary(&self, q: [f64; 2]) -> Vec<f64> {
464 let c = &self.curve;
466 let mut g = [0.0f64; 6];
467 for k in 0..2 {
468 let (p0, p1, p2, p3) = (c[0][k], c[1][k], c[2][k], c[3][k]);
469 let a = [p0 - q[k], 3.0 * (p1 - p0), 3.0 * (p2 - 2.0 * p1 + p0), p3 - 3.0 * p2 + 3.0 * p1 - p0];
470 let d = [a[1], 2.0 * a[2], 3.0 * a[3]];
471 for i in 0..4 {
472 for j in 0..3 {
473 g[i + j] += a[i] * d[j];
474 }
475 }
476 }
477 let choose = |n: usize, r: usize| -> f64 { (0..r).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64) };
479 let mut bern = [0.0f64; 6];
480 for k in 0..6 {
481 bern[k] = (0..=k).map(|i| choose(k, i) / choose(5, i) * g[i]).sum();
482 }
483 let value = |t: f64| g.iter().rev().fold(0.0, |acc, &x| acc * t + x);
484 let size = bern.iter().fold(0.0f64, |m, b| m.max(b.abs()));
487 if !(size > 0.0 && size.is_finite()) {
488 return Vec::new();
489 }
490 let mut roots = Vec::new();
491 let mut spans = 0usize;
492 let mut stack: Vec<([f64; 6], f64, f64, u32)> = vec![(bern, 0.0, 1.0, 0)];
493 while let Some((b, lo, hi, depth)) = stack.pop() {
494 spans += 1;
496 if spans > 4096 {
497 roots.push(0.5 * (lo + hi));
498 continue;
499 }
500 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);
501 if changes == 0 {
502 continue;
503 }
504 let (glo, ghi) = (value(lo), value(hi));
505 if changes == 1 && (glo < 0.0) != (ghi < 0.0) {
506 let (mut a, mut z, mut ga) = (lo, hi, glo);
508 for _ in 0..200 {
509 let m = 0.5 * (a + z);
510 if m <= a || m >= z {
511 break;
512 }
513 let gm = value(m);
514 if gm == 0.0 {
515 a = m;
516 z = m;
517 break;
518 }
519 if (gm < 0.0) == (ga < 0.0) {
520 a = m;
521 ga = gm;
522 } else {
523 z = m;
524 }
525 }
526 let mut t = 0.5 * (a + z);
529 for _ in 0..4 {
530 let r = sub(self.point(t), q);
531 let d = self.derivative(t);
532 let slope = dot(d, d) + dot(r, self.second(t));
533 if !(slope != 0.0 && slope.is_finite()) {
534 break;
535 }
536 let next = t - dot(r, d) / slope;
537 if !(next >= lo && next <= hi) {
538 break;
539 }
540 t = next;
541 }
542 roots.push(t);
543 continue;
544 }
545 if depth >= 60 || hi - lo <= 1e-15 {
546 roots.push(0.5 * (lo + hi));
548 continue;
549 }
550 let mut left = [0.0f64; 6];
552 let mut right = [0.0f64; 6];
553 let mut work = b;
554 for level in 0..6 {
555 left[level] = work[0];
556 right[5 - level] = work[5 - level];
557 for i in 0..5 - level {
558 work[i] = 0.5 * (work[i] + work[i + 1]);
559 }
560 }
561 let mid = 0.5 * (lo + hi);
562 stack.push((right, mid, hi, depth + 1));
563 stack.push((left, lo, mid, depth + 1));
564 }
565 roots
566 }
567
568 pub fn contains(&self, p: Vec3) -> bool {
571 let r = p.sub(self.origin);
572 let h = r.dot(self.up);
573 if !(h >= self.heights[0] && h <= self.heights[1]) {
574 return false;
575 }
576 self.distance([r.dot(self.x), r.dot(self.y)]).0 <= self.radius(h)
578 }
579
580 pub fn level_loops(&self, rho: f64, cell: f64) -> Vec<Vec<[f64; 2]>> {
589 if !(cell > 0.0 && cell.is_finite() && rho >= 0.0 && rho.is_finite()) {
590 return Vec::new();
591 }
592 let (lo, hi) = self.curve.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), c| {
593 ([lo[0].min(c[0]), lo[1].min(c[1])], [hi[0].max(c[0]), hi[1].max(c[1])])
594 });
595 let pad = rho + 2.0 * cell;
596 let (x0, y0) = (lo[0] - pad, lo[1] - pad);
597 let (wx, wy) = (((hi[0] - lo[0] + 2.0 * pad) / cell).ceil(), ((hi[1] - lo[1] + 2.0 * pad) / cell).ceil());
598 if !(wx.is_finite() && wy.is_finite() && (wx + 1.0) * (wy + 1.0) <= 1e8) {
600 return Vec::new();
601 }
602 let (nx, ny) = (wx as usize + 1, wy as usize + 1);
603 let node = |i: usize, j: usize| [x0 + cell * i as f64, y0 + cell * j as f64];
604 let f = |p: [f64; 2]| self.distance(p).0 - rho;
605 let values: Vec<f64> = (0..ny).flat_map(|j| (0..nx).map(move |i| (i, j))).map(|(i, j)| f(node(i, j))).collect();
606 let value = |i: usize, j: usize| values[j * nx + i];
607 let crossing = |a: [f64; 2], b: [f64; 2]| -> [f64; 2] {
609 let (mut fa, mut lo, mut hi) = (f(a), 0.0f64, 1.0f64);
610 for _ in 0..60 {
611 let m = 0.5 * (lo + hi);
612 let fm = f([a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m]);
613 if (fm <= 0.0) == (fa <= 0.0) {
614 lo = m;
615 fa = fm;
616 } else {
617 hi = m;
618 }
619 }
620 let m = 0.5 * (lo + hi);
621 [a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m]
622 };
623 let h_edge = |i: usize, j: usize| 2 * (j * nx + i);
625 let v_edge = |i: usize, j: usize| 2 * (j * nx + i) + 1;
626 let mut next: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
627 for j in 0..ny - 1 {
628 for i in 0..nx - 1 {
629 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];
630 let edges = [h_edge(i, j), v_edge(i + 1, j), h_edge(i, j + 1), v_edge(i, j)];
632 let mut exits: Vec<usize> = Vec::new();
635 let mut entries: Vec<usize> = Vec::new();
636 for k in 0..4 {
637 let (a, b) = (inside[k], inside[(k + 1) % 4]);
638 if a && !b {
639 exits.push(k);
640 } else if !a && b {
641 entries.push(k);
642 }
643 }
644 match (exits.as_slice(), entries.as_slice()) {
645 ([e], [n]) => {
646 next.insert(edges[*n], edges[*e]);
647 }
648 ([e0, e1], [n0, n1]) => {
649 let middle = f([x0 + cell * (i as f64 + 0.5), y0 + cell * (j as f64 + 0.5)]) <= 0.0;
651 let pair = |n: usize, exits: [usize; 2]| -> usize {
653 let after = |e: usize| (e + 4 - n) % 4;
654 if middle { *exits.iter().max_by_key(|&&e| after(e)).unwrap() } else { *exits.iter().min_by_key(|&&e| after(e)).unwrap() }
655 };
656 next.insert(edges[*n0], edges[pair(*n0, [*e0, *e1])]);
657 next.insert(edges[*n1], edges[pair(*n1, [*e0, *e1])]);
658 }
659 _ => {}
660 }
661 }
662 }
663 let edge_point = |id: usize| -> [f64; 2] {
665 let (cell_id, vertical) = (id / 2, id % 2 == 1);
666 let (i, j) = (cell_id % nx, cell_id / nx);
667 let (a, b) = if vertical { (node(i, j), node(i, j + 1)) } else { (node(i, j), node(i + 1, j)) };
668 if f(a) <= 0.0 { crossing(a, b) } else { crossing(b, a) }
669 };
670 let mut loops = Vec::new();
671 let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
672 let mut starts: Vec<usize> = next.keys().copied().collect();
673 starts.sort_unstable();
674 for start in starts {
675 if seen.contains(&start) {
676 continue;
677 }
678 let mut ring = Vec::new();
679 let mut at = start;
680 while seen.insert(at) {
681 ring.push(edge_point(at));
682 match next.get(&at) {
683 Some(&n) => at = n,
684 None => break,
685 }
686 }
687 if ring.len() >= 3 {
688 ring.reverse();
691 loops.push(ring);
692 }
693 }
694 loops
695 }
696
697 pub fn level_area(&self, rho: f64, cell: f64) -> Option<f64> {
702 if !self.grid_fits(rho, cell) {
703 return None;
704 }
705 Some(
706 self.level_loops(rho, cell)
707 .iter()
708 .map(|ring| {
709 let n = ring.len();
710 0.5 * (0..n).map(|k| ring[k][0] * ring[(k + 1) % n][1] - ring[(k + 1) % n][0] * ring[k][1]).sum::<f64>()
711 })
712 .sum(),
713 )
714 }
715
716 fn grid_fits(&self, rho: f64, cell: f64) -> bool {
719 if !(cell > 0.0 && cell.is_finite() && rho >= 0.0 && rho.is_finite() && cell <= 0.25 * rho) {
722 return false;
723 }
724 let (lo, hi) = self.curve.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), c| {
725 ([lo[0].min(c[0]), lo[1].min(c[1])], [hi[0].max(c[0]), hi[1].max(c[1])])
726 });
727 let pad = rho + 2.0 * cell;
728 let (wx, wy) = (((hi[0] - lo[0] + 2.0 * pad) / cell).ceil(), ((hi[1] - lo[1] + 2.0 * pad) / cell).ceil());
729 wx.is_finite() && wy.is_finite() && (wx + 1.0) * (wy + 1.0) <= 1e8
730 }
731
732 pub fn volume(&self, h0: f64, h1: f64, cell: f64) -> Option<f64> {
740 let (a, b) = (h0.max(self.heights[0]), h1.min(self.heights[1]));
741 if !(b > a) {
742 return Some(0.0);
743 }
744 if !self.grid_fits(self.widest(), cell) {
745 return None;
746 }
747 const X: [f64; 4] = [0.1834346424956498, 0.5255324099163290, 0.7966664774136267, 0.9602898564975363];
750 const W: [f64; 4] = [0.3626837833783620, 0.3137066458778873, 0.2223810344533745, 0.1012285362903763];
751 let gauss = |f: &dyn Fn(f64) -> f64, lo: f64, hi: f64| -> f64 {
752 let mut total = 0.0;
753 for k in 0..4 {
754 let (s0, s1) = (lo + (hi - lo) * k as f64 / 4.0, lo + (hi - lo) * (k + 1) as f64 / 4.0);
755 let (mid, half) = (0.5 * (s0 + s1), 0.5 * (s1 - s0));
756 for i in 0..4 {
757 total += half * W[i] * (f(mid - half * X[i]) + f(mid + half * X[i]));
758 }
759 }
760 total
761 };
762 let mut total = 0.0;
763 for piece in &self.meridian {
764 match *piece {
765 OutlinePiece::Line { from, to } => {
766 let tol_r = 1e-12 * self.widest();
769 if from[0].abs() <= tol_r && to[0].abs() <= tol_r {
770 continue;
771 }
772 let dh = to[1] - from[1];
773 if dh == 0.0 {
774 continue;
775 }
776 let (s0, s1) = (((a - from[1]) / dh).clamp(0.0, 1.0), ((b - from[1]) / dh).clamp(0.0, 1.0));
777 let (lo, hi) = (s0.min(s1), s0.max(s1));
778 if hi <= lo {
779 continue;
780 }
781 let radius = |s: f64| from[0] + s * (to[0] - from[0]);
782 if from[0] == to[0] {
787 total += dh.abs() * (hi - lo) * self.level_area(from[0], cell)?;
788 } else {
789 total += dh.abs() * gauss(&|s| self.level_area(radius(s), cell).unwrap_or(f64::NAN), lo, hi);
790 }
791 }
792 OutlinePiece::Arc { centre, radius, start, end } => {
793 let (t0, t1) = (start.min(end), start.max(end));
796 let height = |t: f64| centre[1] + radius * t.sin();
797 let clip = |h: f64| -> f64 {
798 let (mut lo, mut hi) = (t0, t1);
800 let rising = height(t1) > height(t0);
801 for _ in 0..200 {
802 let m = 0.5 * (lo + hi);
803 if (height(m) < h) == rising { lo = m } else { hi = m }
804 }
805 0.5 * (lo + hi)
806 };
807 let (ha, hb) = (height(t0), height(t1));
808 let (hlo, hhi) = (ha.min(hb), ha.max(hb));
809 let (ca, cb) = (a.max(hlo), b.min(hhi));
810 if cb <= ca {
811 continue;
812 }
813 let (u0, u1) = (clip(ca), clip(cb));
814 let (lo, hi) = (u0.min(u1), u0.max(u1));
815 let f = |t: f64| self.level_area(centre[0] + radius * t.cos(), cell).unwrap_or(f64::NAN) * (radius * t.cos()).abs();
816 total += gauss(&f, lo, hi);
817 }
818 OutlinePiece::Ellipse { .. } => {}
819 }
820 }
821 total.is_finite().then_some(total)
822 }
823
824 fn section_reach(&self) -> f64 {
828 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));
829 self.meridian
830 .iter()
831 .filter_map(|piece| world_piece(piece, o, x, z).ok())
832 .flat_map(|curve| curve.control_points.into_iter())
833 .filter_map(|c| c.point().ok())
834 .map(|p| p.x.abs())
835 .fold(0.0f64, f64::max)
836 }
837
838 fn widest(&self) -> f64 {
840 self.meridian.iter().map(|piece| piece_extent(piece).0).fold(0.0f64, f64::max)
841 }
842}
843
844fn world_piece(piece: &OutlinePiece, foot: Vec3, out: Vec3, up: Vec3) -> Result<crate::NurbsCurve, String> {
848 let at = |p: [f64; 2]| foot.add(out.scale(p[0])).add(up.scale(p[1]));
849 match *piece {
850 OutlinePiece::Line { from, to } => crate::make_line(at(from), at(to)),
851 OutlinePiece::Arc { centre, radius, start, end } => {
852 let c = at(centre);
853 if end > start {
854 crate::make_arc(c, out, up, radius, start, end)
855 } else {
856 crate::make_arc(c, out, up, radius, end, start)?.reversed()
857 }
858 }
859 OutlinePiece::Ellipse { .. } => Err("an elliptic meridian piece".into()),
860 }
861}
862
863impl UprightSlot {
864 fn chain(&self) -> Option<Vec<OutlinePiece>> {
867 let tol_r = 1e-12 * self.widest();
868 let along_axis = |piece: &OutlinePiece| matches!(*piece, OutlinePiece::Line { from, to } if from[0].abs() <= tol_r && to[0].abs() <= tol_r);
869 let axis_index = self.meridian.iter().position(along_axis)?;
870 let n = self.meridian.len();
871 Some((1..n).map(|k| self.meridian[(axis_index + k) % n].clone()).collect())
872 }
873
874 fn tool_at(&self, t: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
877 let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
878 let p = self.point(t);
879 let foot = self.origin.add(self.x.scale(p[0])).add(self.y.scale(p[1]));
880 let curves: Vec<crate::NurbsCurve> = self.meridian.iter().map(|piece| world_piece(piece, foot, self.x, self.up)).collect::<Result<_, _>>().map_err(refuse)?;
881 crate::revolve_profile_brep(&curves, foot, self.up, std::f64::consts::TAU).map_err(|e| {
884 crate::KernelRefusal::input(crate::KernelStage::Collect, "upright_scale", format!("uprightStroke: the tool is outside the construction's range: the revolve builder declined it ({e})"))
885 })
886 }
887
888 fn section_at(&self, t: f64) -> Result<Vec<crate::NurbsCurve>, String> {
892 let chain = self.chain().ok_or("no axis piece")?;
893 let p = self.point(t);
894 let d = self.derivative(t);
895 let length = dot(d, d).sqrt();
896 if !(length > 0.0) {
897 return Err("the curve stops".into());
898 }
899 let normal = [-d[1] / length, d[0] / length];
900 let foot = self.origin.add(self.x.scale(p[0])).add(self.y.scale(p[1]));
901 let left = self.x.scale(normal[0]).add(self.y.scale(normal[1]));
902 let mut loop_curves: Vec<crate::NurbsCurve> = chain.iter().map(|piece| world_piece(piece, foot, left, self.up)).collect::<Result<_, _>>()?;
903 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<_, _>>()?;
904 loop_curves.extend(mirrored);
905 Ok(loop_curves)
906 }
907
908 fn world_piece_of_curve(&self, a: f64, b: f64) -> Result<crate::NurbsCurve, String> {
910 let split = |c: [[f64; 2]; 4], t: f64| -> ([[f64; 2]; 4], [[f64; 2]; 4]) {
911 let l = |x: [f64; 2], y: [f64; 2]| [x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t];
912 let (p01, p12, p23) = (l(c[0], c[1]), l(c[1], c[2]), l(c[2], c[3]));
913 let (p012, p123) = (l(p01, p12), l(p12, p23));
914 let m = l(p012, p123);
915 ([c[0], p01, p012, m], [m, p123, p23, c[3]])
916 };
917 let right = if a > 0.0 { split(self.curve, a).1 } else { self.curve };
918 let piece = if b < 1.0 { split(right, (b - a) / (1.0 - a)).0 } else { right };
919 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 };
920 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())
921 }
922
923 fn section_sweep(&self, a: f64, b: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
925 let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
926 let section = self.section_at(a).map_err(refuse)?;
927 let path = self.world_piece_of_curve(a, b).map_err(refuse)?;
928 let chain = crate::SweepPath::new(vec![path], Vec::new())?;
929 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")
930 }
931
932 pub fn pieces(&self) -> Vec<(f64, f64, bool)> {
937 let widest = self.section_reach().max(self.widest());
941 let c = &self.curve;
947 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);
948 let second_most = { let (a, b) = (self.second(0.0), self.second(1.0)); dot(a, a).sqrt().max(dot(b, b).sqrt()) };
949 let third = { let d = sub(self.second(1.0), self.second(0.0)); dot(d, d).sqrt() };
950 let cross = |t: f64| { let (d, dd) = (self.derivative(t), self.second(t)); (d[0] * dd[1] - d[1] * dd[0]).abs() };
951 let speed = |t: f64| dot(self.derivative(t), self.derivative(t)).sqrt();
952 let threshold = 0.99 / widest;
953 let may_be_tight = |a: f64, b: f64| -> bool {
954 let (m, h) = (0.5 * (a + b), 0.5 * (b - a));
955 let low = speed(m) - second_most * h;
956 if !(low > 0.0) {
957 return true;
958 }
959 (cross(m) + polygon * third * h) / (low * low * low) >= threshold
960 };
961 let is_tight_at = |t: f64| cross(t) / speed(t).powi(3) >= threshold;
962 let mut tight_spans: Vec<(f64, f64)> = Vec::new();
963 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();
964 let mut read = 0usize;
967 while let Some((a, b, depth)) = stack.pop() {
968 read += 1;
969 if !may_be_tight(a, b) {
970 continue;
971 }
972 if read > 1 << 20 || is_tight_at(0.5 * (a + b)) || depth >= 40 {
974 match tight_spans.last_mut() {
975 Some(last) if (last.1 - a).abs() <= 1e-15 => last.1 = b,
976 _ => tight_spans.push((a, b)),
977 }
978 continue;
979 }
980 let m = 0.5 * (a + b);
981 stack.push((m, b, depth + 1));
982 stack.push((a, m, depth + 1));
983 }
984 let mut runs: Vec<(f64, f64, bool)> = Vec::new();
986 let mut at = 0.0;
987 for (a, b) in tight_spans {
988 if a > at {
989 runs.push((at, a, false));
990 }
991 runs.push((a, b, true));
992 at = b;
993 }
994 if at < 1.0 {
995 runs.push((at, 1.0, false));
996 }
997 let heading = |t: f64| {
1000 let d = self.derivative(t);
1001 d[1].atan2(d[0])
1002 };
1003 let most = 150f64.to_radians();
1004 let mut pieces = Vec::new();
1005 for (a, b, is_tight) in runs {
1006 if !(b > a) {
1007 continue;
1008 }
1009 let steps = 2048;
1010 let mut turn = 0.0;
1011 let mut previous = heading(a);
1012 let mut start = a;
1013 for k in 1..=steps {
1014 let t = a + (b - a) * k as f64 / steps as f64;
1015 let h = heading(t);
1016 let mut delta = h - previous;
1017 while delta > std::f64::consts::PI { delta -= std::f64::consts::TAU; }
1018 while delta < -std::f64::consts::PI { delta += std::f64::consts::TAU; }
1019 turn += delta.abs();
1020 previous = h;
1021 if turn >= most && k < steps {
1022 pieces.push((start, t, is_tight));
1023 start = t;
1024 turn = 0.0;
1025 }
1026 }
1027 pieces.push((start, b, is_tight));
1028 }
1029 pieces
1030 }
1031
1032 pub fn solid(&self) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1037 let small_arc = self.meridian.iter().any(|piece| matches!(*piece, OutlinePiece::Arc { radius, .. } if radius < 1e-6));
1041 let widest = self.widest();
1042 if small_arc || !(5e-2..=1e6).contains(&widest) {
1043 return Err(crate::KernelRefusal::input(
1044 crate::KernelStage::Collect,
1045 "upright_scale",
1046 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)"),
1047 ));
1048 }
1049 let pieces = self.pieces();
1050 if let Some(&(a, b, _)) = pieces.iter().find(|p| p.2) {
1053 return Err(crate::KernelRefusal::unsupported(
1054 crate::KernelStage::Collect,
1055 "upright_tight_turn",
1056 format!("uprightStroke: the curve turns tighter than the tool reaches over [{a:.4}, {b:.4}]; its folded concave wall is not built"),
1057 ));
1058 }
1059 let mut whole = self.tool_at(0.0)?;
1063 for (index, &(_, b, _)) in pieces.iter().enumerate() {
1064 whole = crate::boolean_operation_nary(&[whole, self.tool_at(b)?], crate::BooleanOperation::Union)
1065 .map_err(|e| e.with_message(|m| format!("{m} (adding the tool at break {index}, t = {b})")))?;
1066 }
1067 for (index, &(a, b, _)) in pieces.iter().enumerate() {
1068 whole = crate::boolean_operation_nary(&[whole, self.section_sweep(a, b)?], crate::BooleanOperation::Union)
1069 .map_err(|e| e.with_message(|m| format!("{m} (adding sweep {index} of {}, [{a}, {b}])", pieces.len())))?;
1070 }
1071 Ok(whole)
1072 }
1073
1074 pub fn stroke(&self, a: f64, b: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
1080 let refuse = |message: String| crate::KernelRefusal::internal(crate::KernelStage::Collect, "upright_stroke", format!("uprightStroke: {message}"));
1081 if !(0.0 <= a && a < b && b <= 1.0) {
1082 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]")));
1083 }
1084 let section = self.section_at(a).map_err(refuse)?;
1085 let path = self.world_piece_of_curve(a, b).map_err(refuse)?;
1086 let chain = crate::SweepPath::new(vec![path], Vec::new())?;
1087 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")?;
1088 crate::boolean_operation_nary(&[swept, self.tool_at(a)?, self.tool_at(b)?], crate::BooleanOperation::Union)
1089 }
1090}
1091