1use crate::{loft_profile_brep, KernelRefusal, KernelStage, NurbsCurve, SolidMotion, Vec3};
34
35pub const APEX_SWEEP_REFUSAL: &str = "sweepPyramidWithin";
37
38fn refuse(what: &'static str, message: String) -> KernelRefusal {
39 KernelRefusal::unsupported(KernelStage::Collect, what, format!("{APEX_SWEEP_REFUSAL}: {message}"))
40}
41
42fn input(what: &'static str, message: String) -> KernelRefusal {
43 KernelRefusal::input(KernelStage::Collect, what, format!("{APEX_SWEEP_REFUSAL}: {message}"))
44}
45
46#[derive(Clone, Debug)]
52pub struct Pyramid {
53 pub apex: Vec3,
54 pub axis: Vec3,
55 pub x_axis: Vec3,
56 pub at: f64,
57 pub section: Vec<[f64; 2]>,
58 pub from: f64,
59 pub to: f64,
60}
61
62type P2 = [f64; 2];
63
64fn rotate(v: Vec3, axis: Vec3, angle: f64) -> Vec3 {
65 let (c, s) = (angle.cos(), angle.sin());
66 v.scale(c).add(axis.cross(v).scale(s)).add(axis.scale(axis.dot(v) * (1.0 - c)))
67}
68
69struct Turns {
72 axes: Vec<(Vec3, f64)>,
73 t0: f64,
74 t1: f64,
75}
76
77impl Turns {
78 fn apply(&self, t: f64, v: Vec3) -> Vec3 {
79 self.axes.iter().fold(v, |v, &(a, w)| rotate(v, a, w * t))
80 }
81 fn invert(&self, t: f64, v: Vec3) -> Vec3 {
82 self.axes.iter().rev().fold(v, |v, &(a, w)| rotate(v, a, -w * t))
83 }
84 fn omega(&self, t: f64) -> Vec3 {
87 let mut total = Vec3::new(0.0, 0.0, 0.0);
88 for (k, &(a, w)) in self.axes.iter().enumerate() {
89 let carried = self.axes[k + 1..].iter().fold(a, |v, &(b, u)| rotate(v, b, u * t));
90 total = total.add(carried.scale(w));
91 }
92 total
93 }
94 fn rate(&self) -> f64 {
96 self.axes.iter().map(|(_, w)| w.abs()).sum::<f64>() * (1.0 + 1e-12)
97 }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq)]
102enum Kind {
103 Corner(usize),
104 Envelope(usize),
105 End(usize, bool),
107}
108
109struct Region {
110 turns: Turns,
111 corners: Vec<Vec3>,
113 normals: Vec<Vec3>,
115 m: Vec3,
117 e1: Vec3,
118 e2: Vec3,
119}
120
121impl Region {
122 fn chart(&self, d: Vec3) -> P2 {
123 let n = d.dot(self.m);
124 [d.dot(self.e1) / n, d.dot(self.e2) / n]
125 }
126 fn direction(&self, y: P2) -> Vec3 {
127 let d = self.m.add(self.e1.scale(y[0])).add(self.e2.scale(y[1]));
128 d.scale(1.0 / d.length())
129 }
130
131 fn foot(&self, k: usize, t: f64) -> f64 {
135 let n = self.corners.len();
136 let (a, b) = (self.turns.apply(t, self.corners[k]), self.turns.apply(t, self.corners[(k + 1) % n]));
137 let normal = self.turns.apply(t, self.normals[k]);
138 let w = self.turns.omega(t);
139 let g = normal.cross(w);
141 let (ga, gb) = (a.dot(g), b.dot(g));
142 if ga == gb { f64::NAN } else { ga / (ga - gb) }
143 }
144
145 fn eval(&self, kind: Kind, s: f64) -> P2 {
146 let n = self.corners.len();
147 let on_side = |k: usize, f: f64, t: f64| {
148 let (a, b) = (self.corners[k], self.corners[(k + 1) % n]);
149 self.turns.apply(t, a.scale(1.0 - f).add(b.scale(f)))
150 };
151 let d = match kind {
152 Kind::Corner(k) => self.turns.apply(s, self.corners[k]),
153 Kind::Envelope(k) => on_side(k, self.foot(k, s).clamp(0.0, 1.0), s),
154 Kind::End(k, end) => on_side(k, s, if end { self.turns.t1 } else { self.turns.t0 }),
155 };
156 self.chart(d)
157 }
158
159 fn member(&self, y: P2) -> Option<bool> {
165 let d = self.direction(y);
166 let (t0, t1) = (self.turns.t0, self.turns.t1);
167 let rate = self.turns.rate();
168 let floor = (t1 - t0) * 1e-12;
169 let mut t = t0;
170 for _ in 0..10_000_000 {
171 let p = self.turns.invert(t, d);
172 let outside = self.normals.iter().map(|n| p.dot(*n).clamp(-1.0, 1.0).asin()).fold(f64::NEG_INFINITY, f64::max);
173 if outside < 0.0 {
174 return Some(true);
175 }
176 if t >= t1 {
177 return Some(false);
178 }
179 t = (t + (outside / rate).max(floor)).min(t1);
180 }
181 None
182 }
183}
184
185#[derive(Clone, Copy, Debug)]
187struct Piece {
188 kind: Kind,
189 a: f64,
190 b: f64,
191}
192
193fn bisect(f: impl Fn(f64) -> f64, mut a: f64, mut b: f64) -> f64 {
195 let fa = f(a);
196 for _ in 0..200 {
197 let m = 0.5 * (a + b);
198 if m <= a || m >= b {
199 break;
200 }
201 if (f(m) < 0.0) == (fa < 0.0) { a = m } else { b = m }
202 }
203 0.5 * (a + b)
204}
205
206const SAMPLES: usize = 512;
207
208fn boundary(region: &Region) -> Result<Vec<Piece>, KernelRefusal> {
210 let n = region.corners.len();
211 let (t0, t1) = (region.turns.t0, region.turns.t1);
212 let mut candidates: Vec<Piece> = Vec::new();
215 for k in 0..n {
216 candidates.push(Piece { kind: Kind::Corner(k), a: t0, b: t1 });
217 candidates.push(Piece { kind: Kind::End(k, false), a: 0.0, b: 1.0 });
218 candidates.push(Piece { kind: Kind::End(k, true), a: 0.0, b: 1.0 });
219 let at = |i: usize| t0 + (t1 - t0) * i as f64 / SAMPLES as f64;
220 let on = |t: f64| { let f = region.foot(k, t); f.is_finite() && (0.0..=1.0).contains(&f) };
221 let mut start: Option<f64> = if on(t0) { Some(t0) } else { None };
222 for i in 1..=SAMPLES {
223 let (ta, tb) = (at(i - 1), at(i));
224 match (on(ta), on(tb)) {
225 (false, true) => start = Some(edge_of_run(region, k, ta, tb)),
226 (true, false) => {
227 let end = edge_of_run(region, k, ta, tb);
228 if let Some(s) = start.take() {
229 if end > s {
230 candidates.push(Piece { kind: Kind::Envelope(k), a: s, b: end });
231 }
232 }
233 }
234 _ => {}
235 }
236 }
237 if let Some(s) = start {
238 if t1 > s {
239 candidates.push(Piece { kind: Kind::Envelope(k), a: s, b: t1 });
240 }
241 }
242 }
243 let polyline = |p: &Piece| -> Vec<(f64, P2)> { (0..=SAMPLES).map(|i| { let s = p.a + (p.b - p.a) * i as f64 / SAMPLES as f64; (s, region.eval(p.kind, s)) }).collect() };
245 let lines: Vec<Vec<(f64, P2)>> = candidates.iter().map(polyline).collect();
246 let size = lines.iter().flatten().map(|(_, q)| q[0].abs().max(q[1].abs())).fold(0.0f64, f64::max).max(1e-3);
247 let mut cuts: Vec<Vec<f64>> = candidates.iter().map(|p| vec![p.a, p.b]).collect();
248 let index = |kind: Kind| candidates.iter().position(|c| c.kind == kind);
251 for i in 0..candidates.len() {
252 let Kind::Envelope(k) = candidates[i].kind else { continue };
253 for t in [candidates[i].a, candidates[i].b] {
254 let f = region.foot(k, t);
255 let (target, at) = if t == t0 {
256 (Kind::End(k, false), f.clamp(0.0, 1.0))
257 } else if t == t1 {
258 (Kind::End(k, true), f.clamp(0.0, 1.0))
259 } else if f < 0.5 {
260 (Kind::Corner(k), t)
261 } else {
262 (Kind::Corner((k + 1) % n), t)
263 };
264 if let Some(j) = index(target) {
265 cuts[j].push(at);
266 }
267 }
268 }
269 for i in 0..candidates.len() {
270 for j in i + 1..candidates.len() {
271 for w in 0..SAMPLES {
272 for v in 0..SAMPLES {
273 let (p0, p1, q0, q1) = (lines[i][w].1, lines[i][w + 1].1, lines[j][v].1, lines[j][v + 1].1);
274 if p0[0].max(p1[0]) < q0[0].min(q1[0]) || q0[0].max(q1[0]) < p0[0].min(p1[0]) || p0[1].max(p1[1]) < q0[1].min(q1[1]) || q0[1].max(q1[1]) < p0[1].min(p1[1]) {
276 continue;
277 }
278 let (r, s) = ([p1[0] - p0[0], p1[1] - p0[1]], [q1[0] - q0[0], q1[1] - q0[1]]);
279 let den = r[0] * s[1] - r[1] * s[0];
280 if den == 0.0 {
281 continue;
282 }
283 let (dx, dy) = (q0[0] - p0[0], q0[1] - p0[1]);
284 let (u, z) = ((dx * s[1] - dy * s[0]) / den, (dx * r[1] - dy * r[0]) / den);
285 if !(u > 1e-9 && u < 1.0 - 1e-9 && z > 1e-9 && z < 1.0 - 1e-9) {
288 continue;
289 }
290 let (sa, sb) = (lines[i][w].0 + u * (lines[i][w + 1].0 - lines[i][w].0), lines[j][v].0 + z * (lines[j][v + 1].0 - lines[j][v].0));
291 if let Some((sa, sb)) = newton(region, candidates[i], candidates[j], sa, sb, size) {
292 cuts[i].push(sa);
293 cuts[j].push(sb);
294 }
295 }
296 }
297 }
298 }
299 let eps = 1e-7 * size;
301 let mut kept: Vec<(Piece, P2, P2)> = Vec::new();
302 for (i, piece) in candidates.iter().enumerate() {
303 let mut c = cuts[i].clone();
304 c.sort_by(|x, y| x.total_cmp(y));
305 c.dedup_by(|x, y| (*x - *y).abs() <= 1e-12 * (piece.b - piece.a).abs().max(1e-300));
306 for w in c.windows(2) {
307 let (a, b) = (w[0], w[1]);
308 if !(b > a) {
309 continue;
310 }
311 let m = 0.5 * (a + b);
312 let h = 1e-6 * (b - a);
313 let (y, ya, yb) = (region.eval(piece.kind, m), region.eval(piece.kind, m - h), region.eval(piece.kind, m + h));
314 let (dx, dy) = (yb[0] - ya[0], yb[1] - ya[1]);
315 let l = dx.hypot(dy);
316 if !(l > 0.0) {
317 continue;
318 }
319 let left = [-dy / l, dx / l];
320 let read = |q: P2| region.member(q).ok_or_else(|| refuse("apex_member", format!("membership at ({:.6}, {:.6}) does not settle", q[0], q[1])));
321 let (inside_left, inside_right) = (read([y[0] + left[0] * eps, y[1] + left[1] * eps])?, read([y[0] - left[0] * eps, y[1] - left[1] * eps])?);
322 if inside_left == inside_right {
323 continue;
324 }
325 let stretch = if inside_left { Piece { kind: piece.kind, a, b } } else { Piece { kind: piece.kind, a: b, b: a } };
326 kept.push((stretch, region.eval(piece.kind, stretch.a), region.eval(piece.kind, stretch.b)));
327 }
328 }
329 if kept.is_empty() {
331 return Err(refuse("apex_empty", "the section sweeps no region".into()));
332 }
333 let close = 1e-7 * size;
334 let gap = |p: P2, q: P2| (p[0] - q[0]).hypot(p[1] - q[1]);
335 let mut used = vec![false; kept.len()];
336 let mut chain = vec![0usize];
337 used[0] = true;
338 loop {
339 let end = kept[*chain.last().unwrap()].2;
340 if gap(end, kept[chain[0]].1) <= close && chain.len() > 1 {
341 break;
342 }
343 let next = (0..kept.len()).filter(|&j| !used[j]).min_by(|&x, &y| gap(end, kept[x].1).total_cmp(&gap(end, kept[y].1)));
344 match next {
345 Some(j) if gap(end, kept[j].1) <= close => {
346 used[j] = true;
347 chain.push(j);
348 }
349 _ => return Err(refuse("apex_open", format!("the region's boundary does not close (at ({:.6}, {:.6}))", end[0], end[1]))),
350 }
351 }
352 if used.iter().any(|u| !u) {
353 return Err(refuse("apex_loops", format!("the region's boundary is more than one loop ({} stretches left)", used.iter().filter(|u| !**u).count())));
354 }
355 Ok(chain.into_iter().map(|j| kept[j].0).collect())
356}
357
358fn edge_of_run(region: &Region, k: usize, ta: f64, tb: f64) -> f64 {
362 let (fa, fb) = (region.foot(k, ta), region.foot(k, tb));
363 let bound = if fa.is_finite() && fb.is_finite() && (fa < 0.0 || fb < 0.0) && !(fa > 1.0 || fb > 1.0) { 0.0 } else { 1.0 };
364 bisect(|t| region.foot(k, t) - bound, ta, tb)
365}
366
367fn newton(region: &Region, p: Piece, q: Piece, mut sa: f64, mut sb: f64, size: f64) -> Option<(f64, f64)> {
370 let (lo_a, hi_a) = (p.a.min(p.b), p.a.max(p.b));
371 let (lo_b, hi_b) = (q.a.min(q.b), q.a.max(q.b));
372 for _ in 0..60 {
373 let (x, y) = (region.eval(p.kind, sa), region.eval(q.kind, sb));
374 let r = [x[0] - y[0], x[1] - y[1]];
375 if r[0].hypot(r[1]) <= 1e-14 * size {
376 return (sa >= lo_a && sa <= hi_a && sb >= lo_b && sb <= hi_b).then_some((sa, sb));
377 }
378 let (ha, hb) = (1e-7 * (hi_a - lo_a), 1e-7 * (hi_b - lo_b));
379 let (xa, yb) = (region.eval(p.kind, sa + ha), region.eval(q.kind, sb + hb));
380 let j = [[(xa[0] - x[0]) / ha, -(yb[0] - y[0]) / hb], [(xa[1] - x[1]) / ha, -(yb[1] - y[1]) / hb]];
381 let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
382 if !(det.is_finite() && det != 0.0) {
383 return None;
384 }
385 sa -= (j[1][1] * r[0] - j[0][1] * r[1]) / det;
386 sb -= (-j[1][0] * r[0] + j[0][0] * r[1]) / det;
387 if !(sa.is_finite() && sb.is_finite()) {
388 return None;
389 }
390 }
391 None
392}
393
394pub fn sweep_pyramid_within(tool: &Pyramid, motion: &SolidMotion, within: [f64; 2]) -> Result<crate::BrepSolid, KernelRefusal> {
403 let axis = tool.axis.normalized().map_err(|e| input("apex_axis", e))?;
404 let x = tool.x_axis.sub(axis.scale(tool.x_axis.dot(axis))).normalized().map_err(|e| input("apex_x_axis", e))?;
405 let y = axis.cross(x);
406 let n = tool.section.len();
407 if n < 3 || !(tool.at > 0.0 && tool.from > 0.0 && tool.to > tool.from) {
408 return Err(input("apex_tool", "a section of three or more corners, at a positive distance, between positive end distances".into()));
409 }
410 let turn = |k: usize| {
412 let (a, b, c) = (tool.section[k], tool.section[(k + 1) % n], tool.section[(k + 2) % n]);
413 (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
414 };
415 let sense = turn(0).signum();
416 if sense == 0.0 || (0..n).any(|k| turn(k).signum() != sense) {
417 return Err(input("apex_convex", "the section must be convex".into()));
418 }
419 let point = |q: P2, at: f64| axis.scale(at).add(x.scale(q[0] * at / tool.at)).add(y.scale(q[1] * at / tool.at));
420 let corners: Vec<Vec3> = tool.section.iter().map(|&q| { let p = point(q, tool.at); p.scale(1.0 / p.length()) }).collect();
421 let normals: Vec<Vec3> = (0..n)
423 .map(|k| {
424 let c = corners[k].cross(corners[(k + 1) % n]);
425 let c = c.scale(1.0 / c.length());
426 if c.dot(corners[(k + 2) % n]) > 0.0 { c.scale(-1.0) } else { c }
427 })
428 .collect();
429 let inner = tool.section.iter().map(|&q| point(q, tool.from).length()).fold(0.0f64, f64::max);
431 let outer = {
432 let inside = (0..n).all(|k| { let (a, b) = (tool.section[k], tool.section[(k + 1) % n]); ((b[0] - a[0]) * (0.0 - a[1]) - (b[1] - a[1]) * (0.0 - a[0])).signum() == sense });
434 if inside {
435 tool.to
436 } else {
437 (0..n).map(|k| {
438 let (a, b) = (point(tool.section[k], tool.to), point(tool.section[(k + 1) % n], tool.to));
439 let e = b.sub(a);
440 let s = (-a.dot(e) / e.dot(e)).clamp(0.0, 1.0);
441 a.add(e.scale(s)).length()
442 }).fold(f64::INFINITY, f64::min)
443 }
444 };
445 let [r0, r1] = within;
446 if !(r0.is_finite() && r1.is_finite() && r1 > r0) {
447 return Err(input("apex_within", "the distances must be finite, the first below the second".into()));
448 }
449 if !(r0 >= inner && r1 <= outer) {
450 return Err(refuse("apex_within", format!("the sweep is the cone only between {inner} and {outer} from the apex, not across [{r0}, {r1}]")));
451 }
452 let mut axes = Vec::with_capacity(motion.steps.len());
454 for step in &motion.steps {
455 let a = step.axis_direction.normalized().map_err(|e| input("apex_step", e))?;
456 let off = step.axis_origin.sub(tool.apex);
457 let miss = off.sub(a.scale(off.dot(a))).length();
458 if step.advance != 0.0 || miss > 1e-12 * tool.to {
461 return Err(refuse("apex_motion", "every step must be a turn about an axis through the apex".into()));
462 }
463 axes.push((a, step.turn));
464 }
465 if !(motion.to > motion.from) || axes.iter().all(|(_, w)| *w == 0.0) {
466 return Err(input("apex_motion", "the motion must turn over a positive range".into()));
467 }
468 let turns = Turns { axes, t0: motion.from, t1: motion.to };
469 let m = turns.apply(0.5 * (turns.t0 + turns.t1), axis);
471 let e1 = m.perpendicular().map_err(|e| input("apex_chart", e))?;
472 let e2 = m.cross(e1);
473 for i in 0..=64 {
475 let t = turns.t0 + (turns.t1 - turns.t0) * i as f64 / 64.0;
476 if corners.iter().any(|c| turns.apply(t, *c).dot(m) < 0.17) {
477 return Err(refuse("apex_spread", "the tool turns more than 80° from its middle direction".into()));
478 }
479 }
480 let region = Region { turns, corners, normals, m, e1, e2 };
481 let pieces = boundary(®ion)?;
482 let mut widest = 1.0f64;
486 let mut samples: Vec<Vec<(f64, P2)>> = Vec::with_capacity(pieces.len());
487 for piece in &pieces {
488 let points: Vec<(f64, P2)> = (0..=96).map(|i| { let s = piece.a + (piece.b - piece.a) * i as f64 / 96.0; (s, region.eval(piece.kind, s)) }).collect();
489 for (_, q) in &points {
490 widest = widest.max((1.0 + q[0] * q[0] + q[1] * q[1]).sqrt());
491 }
492 samples.push(points);
493 }
494 let (near, far) = (r0 / widest * (1.0 - 1e-9), r1);
498 let lift = |q: P2, h: f64| tool.apex.add(region.m.scale(h)).add(region.e1.scale(q[0] * h)).add(region.e2.scale(q[1] * h));
499 let section = |h: f64| -> Result<Vec<NurbsCurve>, KernelRefusal> {
500 samples
501 .iter()
502 .map(|points| {
503 let xs: Vec<Vec3> = points.iter().map(|(_, q)| lift(*q, h)).collect();
504 let mut s = vec![0.0];
505 for w in xs.windows(2) {
506 s.push(s.last().unwrap() + w[1].sub(w[0]).length());
507 }
508 let total = *s.last().unwrap();
509 let parameters: Vec<f64> = s.iter().map(|v| v / total).collect();
510 crate::interpolate_curve(&xs, 3, ¶meters).map_err(|e| refuse("apex_fit", e))
511 })
512 .collect()
513 };
514 let (inner_section, outer_section) = (section(near)?, section(far)?);
515 loft_profile_brep(&[inner_section, outer_section])
516}
517