1use super::*;
2use crate::{KernelRefusal, KernelStage, OrRefuse};
3use crate::offset_retrim::{rebuild_loop_pcurves, retrim_planar_face};
4use crate::{RevolutionFrame, Vec4};
5use super::face_move::{carrier_ruled, retrim_ruled_face};
6use super::face_rotate::rotation_about;
7
8const OP: &str = "draft_faces";
52
53const CONSUMES_FACE: &str = "draft_consumes_face";
57
58#[derive(Clone)]
60enum Carrier {
61 Plane { origin: Vec3, normal: Vec3 },
63 Ruled { frame: RevolutionFrame, rho0: f64, rho1: f64, height: f64 },
67}
68
69impl Carrier {
70 fn residual(&self, point: Vec3) -> f64 {
71 match self {
72 Carrier::Plane { origin, normal } => point.sub(*origin).dot(*normal),
73 Carrier::Ruled { frame, rho0, rho1, height } => {
74 let w = point.sub(frame.origin);
75 let h = w.dot(frame.axis);
76 let radial = w.sub(frame.axis.scale(h)).length();
77 radial - (rho0 + (rho1 - rho0) * h / height)
78 }
79 }
80 }
81}
82
83#[derive(Clone)]
85enum Draft {
86 Plane { old: Plane, outward: Vec3, rotation: AffineTransform },
89 Cylinder { axis_point: Vec3, radius: f64, sign: f64 },
92}
93
94fn outward_sign(face: &FaceRecord) -> f64 {
96 if face.same_sense {
97 1.0
98 } else {
99 -1.0
100 }
101}
102
103fn frame_about(origin: Vec3, axis: Vec3) -> Result<RevolutionFrame, KernelRefusal> {
105 let x_axis = axis.perpendicular().or_refuse(KernelStage::Classify, "perpendicular")?;
106 let y_axis = axis.cross(x_axis).normalized().or_refuse(KernelStage::Classify, "normalized")?;
107 Ok(RevolutionFrame { origin, axis, x_axis, y_axis })
108}
109
110fn vertical_cylinder(surface: &NurbsSurface, pull: Vec3, tolerance: f64) -> Option<(Vec3, f64)> {
116 let [u0, u1] = surface.domain_u().ok()?;
117 let [v0, v1] = surface.domain_v().ok()?;
118 let ex = pull.perpendicular().ok()?;
119 let ey = pull.cross(ex).normalized().ok()?;
120 let mut samples: Vec<[f64; 2]> = Vec::with_capacity(25);
121 for i in 0..5 {
122 for j in 0..5 {
123 let u = u0 + (u1 - u0) * (0.05 + 0.9 * i as f64 / 4.0);
124 let v = v0 + (v1 - v0) * (0.05 + 0.9 * j as f64 / 4.0);
125 let normal = surface.normal(u, v).ok()?;
126 if normal.dot(pull).abs() > 1e-7 {
127 return None;
128 }
129 let point = surface.evaluate(u, v).ok()?;
130 samples.push([point.dot(ex), point.dot(ey)]);
131 }
132 }
133 let distance = |a: [f64; 2], b: [f64; 2]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt();
134 let a = samples[0];
135 let b = *samples.iter().max_by(|p, q| distance(a, **p).total_cmp(&distance(a, **q)))?;
136 let area = |p: [f64; 2]| ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])).abs();
137 let c = *samples.iter().max_by(|p, q| area(**p).total_cmp(&area(**q)))?;
138 if area(c) <= 1e-9 * distance(a, b).powi(2).max(1e-30) {
139 return None; }
141 let (bx, by) = (b[0] - a[0], b[1] - a[1]);
142 let (cx, cy) = (c[0] - a[0], c[1] - a[1]);
143 let det = 2.0 * (bx * cy - by * cx);
144 let ux = (cy * (bx * bx + by * by) - by * (cx * cx + cy * cy)) / det;
145 let uy = (bx * (cx * cx + cy * cy) - cx * (bx * bx + by * by)) / det;
146 let center = [a[0] + ux, a[1] + uy];
147 let radius = (ux * ux + uy * uy).sqrt();
148 if samples.iter().any(|p| (distance(*p, center) - radius).abs() > tolerance) {
149 return None;
150 }
151 Some((ex.scale(center[0]).add(ey.scale(center[1])), radius))
152}
153
154fn carrier_of(
157 solid: &BrepSolid,
158 face_lookup: &HashMap<u64, (usize, usize)>,
159 face_id: u64,
160 pull: Vec3,
161 plane_tolerance: f64,
162) -> Option<Carrier> {
163 let &(shell, index) = face_lookup.get(&face_id)?;
164 let surface = &solid.shells[shell].faces[index].surface;
165 if let Ok(plane) = plane_of_surface(surface, plane_tolerance, OP) {
166 return Some(Carrier::Plane { origin: plane.origin, normal: plane.normal });
167 }
168 if let Some((frame, rho0, rho1, height)) = carrier_ruled(solid, face_lookup, face_id) {
169 return Some(Carrier::Ruled { frame, rho0, rho1, height });
170 }
171 let (axis_point, radius) = vertical_cylinder(surface, pull, plane_tolerance)?;
172 let frame = frame_about(axis_point, pull).ok()?;
173 Some(Carrier::Ruled { frame, rho0: radius, rho1: radius, height: 1.0 })
174}
175
176fn swept_azimuth(frame: &RevolutionFrame, curve: &NurbsCurve, t0: f64, t1: f64) -> Result<f64, KernelRefusal> {
178 let azimuth = |point: Vec3| {
179 let w = point.sub(frame.origin);
180 w.dot(frame.y_axis).atan2(w.dot(frame.x_axis))
181 };
182 let steps = 64;
183 let mut previous = azimuth(curve.evaluate(t0).or_refuse(KernelStage::Refine, "evaluate")?);
184 let mut total = 0.0;
185 for step in 1..=steps {
186 let t = t0 + (t1 - t0) * step as f64 / steps as f64;
187 let next = azimuth(curve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?);
188 let mut delta = next - previous;
189 while delta > std::f64::consts::PI {
190 delta -= std::f64::consts::TAU;
191 }
192 while delta < -std::f64::consts::PI {
193 delta += std::f64::consts::TAU;
194 }
195 total += delta;
196 previous = next;
197 }
198 Ok(total)
199}
200
201fn line_meets(carrier: &Carrier, point: Vec3, direction: Vec3, near: Vec3) -> Option<Vec3> {
203 match carrier {
204 Carrier::Plane { origin, normal } => {
205 let denominator = normal.dot(direction);
206 if denominator.abs() <= 1e-12 {
207 return None;
208 }
209 let t = normal.dot(origin.sub(point)) / denominator;
210 Some(point.add(direction.scale(t)))
211 }
212 Carrier::Ruled { frame, rho0, rho1, height } => {
213 let k = (rho1 - rho0) / height;
214 let w0 = point.sub(frame.origin);
215 let h0 = w0.dot(frame.axis);
216 let q0 = w0.sub(frame.axis.scale(h0));
217 let h1 = direction.dot(frame.axis);
218 let q1 = direction.sub(frame.axis.scale(h1));
219 let r0 = rho0 + k * h0;
220 let a = q1.dot(q1) - k * k * h1 * h1;
221 let b = 2.0 * (q0.dot(q1) - r0 * k * h1);
222 let c = q0.dot(q0) - r0 * r0;
223 let mut roots = Vec::new();
224 if a.abs() <= 1e-14 * (b.abs() + c.abs()).max(1e-300) {
225 if b.abs() > 0.0 {
226 roots.push(-c / b);
227 }
228 } else {
229 let disc = b * b - 4.0 * a * c;
230 if disc < 0.0 {
231 return None;
232 }
233 let root = disc.sqrt();
234 roots.push((-b + root) / (2.0 * a));
235 roots.push((-b - root) / (2.0 * a));
236 }
237 roots
238 .into_iter()
239 .filter(|t| r0 + k * h1 * t >= 0.0)
240 .map(|t| point.add(direction.scale(t)))
241 .min_by(|p, q| p.sub(near).length().total_cmp(&q.sub(near).length()))
242 }
243 }
244}
245
246fn planes_meet(planes: &[(Vec3, Vec3)]) -> Option<Vec3> {
248 let mut m = [[0.0f64; 3]; 3];
249 let mut rhs = [0.0f64; 3];
250 for (origin, normal) in planes {
251 let n = [normal.x, normal.y, normal.z];
252 let b = normal.dot(*origin);
253 for r in 0..3 {
254 for c in 0..3 {
255 m[r][c] += n[r] * n[c];
256 }
257 rhs[r] += n[r] * b;
258 }
259 }
260 let det = |m: &[[f64; 3]; 3]| {
261 m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
262 - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
263 + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
264 };
265 let d = det(&m);
266 let trace = m[0][0] + m[1][1] + m[2][2];
267 if d.abs() <= 1e-10 * trace.powi(3) {
268 return None;
269 }
270 let mut solution = [0.0f64; 3];
271 for column in 0..3 {
272 let mut replaced = m;
273 for row in 0..3 {
274 replaced[row][column] = rhs[row];
275 }
276 solution[column] = det(&replaced) / d;
277 }
278 Some(Vec3::new(solution[0], solution[1], solution[2]))
279}
280
281pub fn draft_faces(
301 solid: &BrepSolid,
302 face_ids: &[u64],
303 pull_direction: Vec3,
304 neutral_point: Vec3,
305 angle_radians: f64,
306) -> Result<BrepSolid, KernelRefusal> {
307 crate::accept_sound(draft_faces_unchecked(solid, face_ids, pull_direction, neutral_point, angle_radians)?, "draftFaces")
308}
309
310pub fn draft_faces_unchecked(
314 solid: &BrepSolid,
315 face_ids: &[u64],
316 pull_direction: Vec3,
317 neutral_point: Vec3,
318 angle_radians: f64,
319) -> Result<BrepSolid, KernelRefusal> {
320 match draft_faces_in_place(solid, face_ids, pull_direction, neutral_point, angle_radians) {
321 Err(refusal)
322 if matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == CONSUMES_FACE) =>
323 {
324 draft_convex_polyhedron(solid, face_ids, pull_direction, neutral_point, angle_radians)
325 .map_err(|convex| {
326 KernelRefusal::unsupported(KernelStage::Classify, CONSUMES_FACE, format!(
327 "{OP}: the draft changes the body's topology ({refusal}), and the convex \
328 route that builds such a draft cannot take this body ({convex}) — refusing"
329 ))
330 })
331 }
332 other => other,
333 }
334}
335
336fn check_inputs(
337 face_ids: &[u64],
338 pull_direction: Vec3,
339 neutral_point: Vec3,
340 angle_radians: f64,
341) -> Result<Vec3, KernelRefusal> {
342 let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
343 if !finite(pull_direction) {
344 return Err(KernelRefusal::input(KernelStage::Collect, "pull_direction", format!("{OP}: the pull direction must be finite")));
345 }
346 if !finite(neutral_point) {
347 return Err(KernelRefusal::input(KernelStage::Collect, "neutral_point", format!("{OP}: the neutral point must be finite")));
348 }
349 if !angle_radians.is_finite() || angle_radians.abs() >= 89.0f64.to_radians() {
350 return Err(KernelRefusal::input(KernelStage::Collect, "angle", format!(
351 "{OP}: the draft angle must be finite and less than 89° either way (got {angle_radians})"
352 )));
353 }
354 if face_ids.is_empty() {
355 return Err(KernelRefusal::input(KernelStage::Collect, "selection", format!("{OP}: no faces selected")));
356 }
357 pull_direction.normalized().map_err(|_| {
358 KernelRefusal::input(KernelStage::Collect, "pull_direction", format!("{OP}: the pull direction has zero length"))
359 })
360}
361
362fn draft_faces_in_place(
363 solid: &BrepSolid,
364 face_ids: &[u64],
365 pull_direction: Vec3,
366 neutral_point: Vec3,
367 angle_radians: f64,
368) -> Result<BrepSolid, KernelRefusal> {
369 let pull = check_inputs(face_ids, pull_direction, neutral_point, angle_radians)?;
370 let scale = solid_model_scale(solid);
371 let tolerance = (scale * 1e-7).max(1e-9);
372 let plane_tolerance = (scale * 1e-6).max(1e-7);
373 let accept = 10.0 * plane_tolerance;
374 let (sin, cos) = angle_radians.sin_cos();
375 let tan = angle_radians.tan();
376 let height_of = |point: Vec3| point.sub(neutral_point).dot(pull);
377
378 let mut face_lookup: HashMap<u64, (usize, usize)> = HashMap::default();
379 for (shell_index, shell) in solid.shells.iter().enumerate() {
380 for (face_index, face) in shell.faces.iter().enumerate() {
381 face_lookup.entry(face.id).or_insert((shell_index, face_index));
382 }
383 }
384 let selected: HashSet<u64> = face_ids.iter().copied().collect();
385 for &face_id in &selected {
386 if !face_lookup.contains_key(&face_id) {
387 return Err(KernelRefusal::input(KernelStage::Collect, "face_id", format!("{OP}: no face with id {face_id}")));
388 }
389 }
390 if angle_radians == 0.0 {
391 return Ok(solid.clone());
392 }
393
394 let mut drafts: HashMap<u64, Draft> = HashMap::default();
396 let mut carriers: HashMap<u64, Carrier> = HashMap::default();
397 for &face_id in &selected {
398 let (shell, index) = face_lookup[&face_id];
399 let face = &solid.shells[shell].faces[index];
400 let sign = outward_sign(face);
401 if let Ok(old) = plane_of_surface(&face.surface, plane_tolerance, OP) {
402 let outward = old.normal.scale(sign);
403 if outward.dot(pull).abs() > 1e-9 {
404 return Err(KernelRefusal::unsupported(KernelStage::Classify, "draft_plane_not_parallel", format!(
405 "{OP}: face {face_id} is a plane that is not parallel to the pull direction \
406 (its normal makes {:.6}° with the pull); a draft turns a face that runs along \
407 the pull — refusing",
408 outward.dot(pull).clamp(-1.0, 1.0).acos().to_degrees()
409 )));
410 }
411 let hinge = outward.cross(pull).normalized().or_refuse(KernelStage::Classify, "hinge")?;
413 let on_hinge = old.origin.add(pull.scale(-height_of(old.origin)));
414 let rotation = rotation_about(on_hinge, hinge, angle_radians).or_refuse(KernelStage::Classify, "rotation")?;
415 let turned = super::face_rotate::rotate_direction(&rotation, old.normal);
416 carriers.insert(face_id, Carrier::Plane { origin: on_hinge, normal: turned });
417 drafts.insert(face_id, Draft::Plane { old, outward, rotation });
418 continue;
419 }
420 let Some((axis_point, radius)) = vertical_cylinder(&face.surface, pull, plane_tolerance) else {
421 return Err(KernelRefusal::unsupported(KernelStage::Classify, "draft_carrier_kind", format!(
422 "{OP}: face {face_id} is neither a plane parallel to the pull direction nor a \
423 cylinder whose axis is the pull direction; a draft turns those into a tilted plane \
424 and a cone, and has no drafted carrier for this one — refusing"
425 )));
426 };
427 let axis_point = axis_point.add(pull.scale(height_of(axis_point) * -1.0));
428 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Classify, "domain_u")?;
430 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Classify, "domain_v")?;
431 let (um, vm) = ((u0 + u1) * 0.5, (v0 + v1) * 0.5);
432 let at = face.surface.evaluate(um, vm).or_refuse(KernelStage::Classify, "evaluate")?;
433 let normal = face.surface.normal(um, vm).or_refuse(KernelStage::Classify, "normal")?.scale(sign);
434 let radial = at.sub(axis_point);
435 let radial = radial.sub(pull.scale(radial.dot(pull)));
436 let draft_sign = if normal.dot(radial) > 0.0 { 1.0 } else { -1.0 };
437 let frame = frame_about(axis_point, pull)?;
438 let height = 0.5 * radius / tan.abs();
440 carriers.insert(face_id, Carrier::Ruled {
441 frame,
442 rho0: radius,
443 rho1: radius - draft_sign * tan * height,
444 height,
445 });
446 drafts.insert(face_id, Draft::Cylinder { axis_point, radius, sign: draft_sign });
447 }
448 let generator = |face_id: u64, point: Vec3| -> Option<Vec3> {
451 let outward = match drafts.get(&face_id)? {
452 Draft::Plane { outward, .. } => *outward,
453 Draft::Cylinder { axis_point, sign, .. } => {
454 let radial = point.sub(*axis_point);
455 radial.sub(pull.scale(radial.dot(pull))).normalized().ok()?.scale(*sign)
456 }
457 };
458 pull.scale(cos).sub(outward.scale(sin)).normalized().ok()
459 };
460
461 let mut faces_of_edge: HashMap<u64, Vec<u64>> = HashMap::default();
463 for shell in &solid.shells {
464 for face in &shell.faces {
465 for loop_record in &face.loops {
466 for coedge in &loop_record.coedges {
467 faces_of_edge.entry(coedge.edge_id).or_default().push(face.id);
468 }
469 }
470 }
471 }
472 let mut edges_at: HashMap<u64, Vec<usize>> = HashMap::default();
473 for (index, edge) in solid.edges.iter().enumerate() {
474 let uses = faces_of_edge.get(&edge.id).map(Vec::len).unwrap_or(0);
475 let expected = if edge.degenerate { 1 } else { 2 };
476 if uses != expected {
477 return Err(KernelRefusal::input(KernelStage::Collect, "non_manifold", format!(
478 "{OP}: edge {} is used {uses} times (non-manifold input)", edge.id
479 )));
480 }
481 edges_at.entry(edge.start_vertex_id).or_default().push(index);
482 if edge.end_vertex_id != edge.start_vertex_id {
483 edges_at.entry(edge.end_vertex_id).or_default().push(index);
484 }
485 }
486 let touches_draft = |edge: &EdgeRecord| faces_of_edge[&edge.id].iter().any(|f| selected.contains(f));
487
488 let mut neighbours: HashSet<u64> = HashSet::default();
491 for edge in &solid.edges {
492 if touches_draft(edge) {
493 neighbours.extend(faces_of_edge[&edge.id].iter().copied());
494 }
495 }
496 for vertex_edges in edges_at.values() {
497 if vertex_edges.iter().any(|&e| touches_draft(&solid.edges[e])) {
498 for &e in vertex_edges {
499 neighbours.extend(faces_of_edge[&solid.edges[e].id].iter().copied());
500 }
501 }
502 }
503 let mut sorted_neighbours: Vec<u64> = neighbours.iter().copied().collect();
504 sorted_neighbours.sort_unstable();
505 for face_id in sorted_neighbours {
506 if carriers.contains_key(&face_id) {
507 continue;
508 }
509 let Some(carrier) = carrier_of(solid, &face_lookup, face_id, pull, plane_tolerance) else {
510 return Err(KernelRefusal::unsupported(KernelStage::Classify, "draft_neighbour_kind", format!(
511 "{OP}: face {face_id}, which meets a drafted face, is not a plane, a cylinder or \
512 a cone; the draft re-trims its neighbours by closed-form sections only — refusing"
513 )));
514 };
515 carriers.insert(face_id, carrier);
516 }
517
518 let mut new_vertex: HashMap<u64, Vec3> = HashMap::default();
520 for vertex in &solid.vertices {
521 let Some(vertex_edges) = edges_at.get(&vertex.id) else { continue };
522 let mut at: Vec<u64> = vertex_edges
523 .iter()
524 .flat_map(|&e| faces_of_edge[&solid.edges[e].id].iter().copied())
525 .collect();
526 at.sort_unstable();
527 at.dedup();
528 if !at.iter().any(|f| selected.contains(f)) {
529 continue;
530 }
531 let worst = |point: Vec3| at.iter().map(|f| carriers[f].residual(point).abs()).fold(0.0, f64::max);
532 if worst(vertex.point) <= tolerance {
533 new_vertex.insert(vertex.id, vertex.point); continue;
535 }
536 let mut lines: Vec<(Vec3, Vec3)> = Vec::new();
540 for &e in vertex_edges {
541 let edge = &solid.edges[e];
542 if edge.degenerate {
543 continue;
544 }
545 let Some((a, b)) = edge.curve.straight_segment(tolerance) else { continue };
546 let uses = &faces_of_edge[&edge.id];
547 let drafted = uses.iter().filter(|f| selected.contains(*f)).count();
548 let direction = b.sub(a);
549 if drafted == 0 {
550 lines.push((a, direction));
551 } else if drafted == uses.len() {
552 let along = direction.dot(pull);
553 if along.abs() <= 1e-9 * direction.length() {
554 continue; }
556 let crossing = a.add(direction.scale(-height_of(a) / along));
557 let mut line_direction = None;
558 if let (Some(Carrier::Plane { normal: na, .. }), Some(Carrier::Plane { normal: nb, .. })) =
559 (carriers.get(&uses[0]), carriers.get(&uses[1]))
560 {
561 let cross = na.cross(*nb);
562 if cross.length() > 1e-9 {
563 line_direction = cross.normalized().ok();
564 }
565 }
566 let line_direction = match line_direction.or_else(|| generator(uses[0], crossing)) {
567 Some(direction) => direction,
568 None => continue,
569 };
570 let probe = crossing.add(line_direction.scale(scale));
571 if uses.iter().all(|f| {
572 carriers[f].residual(crossing).abs() <= accept && carriers[f].residual(probe).abs() <= accept
573 }) {
574 lines.push((crossing, line_direction));
575 }
576 }
577 }
578 let mut best: Option<(f64, Vec3)> = None;
579 for &(point, direction) in &lines {
580 for face_id in &at {
581 let carrier = &carriers[face_id];
582 let probe = point.add(direction.scale(scale));
583 if carrier.residual(point).abs() <= tolerance && carrier.residual(probe).abs() <= tolerance {
584 continue; }
586 if let Some(candidate) = line_meets(carrier, point, direction, vertex.point) {
587 let error = worst(candidate);
588 if best.map_or(true, |(e, _)| error < e) {
589 best = Some((error, candidate));
590 }
591 }
592 }
593 }
594 if best.map_or(true, |(e, _)| e > accept) {
595 let planes: Option<Vec<(Vec3, Vec3)>> = at
596 .iter()
597 .map(|f| match &carriers[f] {
598 Carrier::Plane { origin, normal } => Some((*origin, *normal)),
599 _ => None,
600 })
601 .collect();
602 if let Some(candidate) = planes.as_deref().filter(|p| p.len() >= 3).and_then(planes_meet) {
603 let error = worst(candidate);
604 if best.map_or(true, |(e, _)| error < e) {
605 best = Some((error, candidate));
606 }
607 }
608 }
609 match best {
610 Some((error, point)) if error <= accept => {
611 new_vertex.insert(vertex.id, point);
612 }
613 _ => {
614 return Err(KernelRefusal::unsupported(KernelStage::Refine, "draft_corner", format!(
615 "{OP}: the corner at vertex {} where faces {at:?} meet has no closed-form \
616 solve on the drafted carriers (a corner must lie on an edge line both of \
617 whose faces are drafted or both fixed, or on three planes) — refusing",
618 vertex.id
619 )));
620 }
621 }
622 }
623
624 let point_of = |id: u64| -> Vec3 {
626 new_vertex
627 .get(&id)
628 .copied()
629 .unwrap_or_else(|| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point).unwrap_or_default())
630 };
631 let old_point = |id: u64| -> Vec3 { solid.vertices.iter().find(|v| v.id == id).map(|v| v.point).unwrap_or_default() };
632 let mut result = solid.clone();
633 let mut changed_edges: HashSet<u64> = HashSet::default();
634 for edge in &mut result.edges {
635 if edge.degenerate {
636 continue;
637 }
638 let uses = faces_of_edge[&edge.id].clone();
639 let moved_ends = [edge.start_vertex_id, edge.end_vertex_id]
640 .iter()
641 .any(|id| point_of(*id).sub(old_point(*id)).length() > tolerance);
642 let drafted_here = uses.iter().any(|f| selected.contains(f));
643 if !drafted_here && !moved_ends {
644 continue;
645 }
646 let (start, end) = (point_of(edge.start_vertex_id), point_of(edge.end_vertex_id));
647 let mid_t = (edge.t0 + edge.t1) * 0.5;
648 let old_mid = edge.curve.evaluate(mid_t).or_refuse(KernelStage::Refine, "evaluate")?;
649 let on_new = |point: Vec3| uses.iter().all(|f| carriers.get(f).map_or(false, |c| c.residual(point).abs() <= accept));
650 if !moved_ends && on_new(old_mid) {
651 let quarter = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * 0.25).or_refuse(KernelStage::Refine, "evaluate")?;
654 if on_new(quarter) {
655 continue;
656 }
657 }
658 changed_edges.insert(edge.id);
659 if let Some((a, b)) = edge.curve.straight_segment(tolerance) {
660 let old_direction = b.sub(a);
661 let new_direction = end.sub(start);
662 if new_direction.length() <= tolerance || new_direction.dot(old_direction) <= 0.0 {
663 return Err(KernelRefusal::unsupported(KernelStage::Refine, CONSUMES_FACE, format!(
664 "{OP}: the draft turns edge {} end over end (or collapses it) between faces \
665 {uses:?}: it consumes a face, a change of topology the in-place draft does \
666 not make — refusing",
667 edge.id
668 )));
669 }
670 let curve = make_line(start, end).or_refuse(KernelStage::Sew, "make_line")?;
671 let mid = curve.evaluate(0.5).or_refuse(KernelStage::Sew, "evaluate")?;
672 if !on_new(mid) {
673 return Err(KernelRefusal::internal(KernelStage::Validate, "draft_edge_off_carrier", format!(
674 "{OP}: the rebuilt straight edge {} leaves the carriers of faces {uses:?} — refusing",
675 edge.id
676 )));
677 }
678 edge.curve = curve;
679 edge.t0 = 0.0;
680 edge.t1 = 1.0;
681 continue;
682 }
683 let pair = match (carriers.get(&uses[0]), carriers.get(&uses[1])) {
685 (Some(Carrier::Plane { origin, normal }), Some(Carrier::Ruled { frame, rho0, rho1, height }))
686 | (Some(Carrier::Ruled { frame, rho0, rho1, height }), Some(Carrier::Plane { origin, normal })) => {
687 Some((*origin, *normal, frame.clone(), *rho0, *rho1, *height))
688 }
689 _ => None,
690 };
691 let Some((origin, normal, frame, rho0, rho1, height)) = pair else {
692 return Err(KernelRefusal::unsupported(KernelStage::Refine, "draft_curved_edge", format!(
693 "{OP}: curved edge {} between faces {uses:?} is not the section of a cylinder or \
694 cone by a plane, the only curved edge the draft re-intersects — refusing",
695 edge.id
696 )));
697 };
698 let sweep = swept_azimuth(&frame, &edge.curve, edge.t0, edge.t1)?;
699 let azimuth = |point: Vec3| {
700 let w = point.sub(frame.origin);
701 let a = w.dot(frame.y_axis).atan2(w.dot(frame.x_axis));
702 if a < 0.0 { a + std::f64::consts::TAU } else { a }
703 };
704 let closed = edge.start_vertex_id == edge.end_vertex_id;
705 let sweep = if closed { std::f64::consts::TAU.copysign(sweep) } else { sweep };
706 let (from, magnitude) = if sweep > 0.0 { (azimuth(start), sweep) } else { (azimuth(end), -sweep) };
707 let magnitude = if closed {
711 magnitude
712 } else {
713 let (a0, a1) = if sweep > 0.0 { (azimuth(start), azimuth(end)) } else { (azimuth(end), azimuth(start)) };
714 let mut span = a1 - a0;
715 while span <= 0.0 {
716 span += std::f64::consts::TAU;
717 }
718 if (span - magnitude).abs() > std::f64::consts::PI {
719 magnitude
720 } else {
721 span
722 }
723 };
724 let mut curve = plane_ruled_section_arc(origin, normal, &frame, rho0, rho1, height, from, magnitude, tolerance)
725 .map_err(|error| {
726 KernelRefusal::unsupported(KernelStage::Refine, "draft_section", format!(
727 "{OP}: edge {} between faces {uses:?}: {error}", edge.id
728 ))
729 })?;
730 if sweep < 0.0 {
731 curve = curve.reversed().or_refuse(KernelStage::Sew, "reversed")?;
732 }
733 let [d0, d1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
734 let (c0, c1) = (
735 curve.evaluate(d0).or_refuse(KernelStage::Sew, "evaluate")?,
736 curve.evaluate(d1).or_refuse(KernelStage::Sew, "evaluate")?,
737 );
738 if c0.sub(start).length() > accept || c1.sub(end).length() > accept {
739 return Err(KernelRefusal::internal(KernelStage::Validate, "draft_section_ends", format!(
740 "{OP}: the re-intersected section of edge {} misses its corners by {:.3e} and \
741 {:.3e} — refusing",
742 edge.id,
743 c0.sub(start).length(),
744 c1.sub(end).length()
745 )));
746 }
747 edge.curve = curve;
748 edge.t0 = d0;
749 edge.t1 = d1;
750 }
751 for vertex in &mut result.vertices {
752 if let Some(point) = new_vertex.get(&vertex.id) {
753 vertex.point = *point;
754 }
755 }
756 let final_edges: HashMap<u64, EdgeRecord> = result.edges.iter().map(|edge| (edge.id, edge.clone())).collect();
757
758 let mut ruled_retrims = Vec::new();
760 for shell in &mut result.shells {
761 for face in &mut shell.faces {
762 let touched = face
763 .loops
764 .iter()
765 .flat_map(|l| l.coedges.iter())
766 .any(|c| changed_edges.contains(&c.edge_id));
767 match drafts.get(&face.id) {
768 Some(Draft::Plane { old, rotation, .. }) => {
769 let turned = Plane {
770 origin: rotation.point(old.origin),
771 u_dir: super::face_rotate::rotate_direction(rotation, old.u_dir),
772 v_dir: super::face_rotate::rotate_direction(rotation, old.v_dir),
773 normal: super::face_rotate::rotate_direction(rotation, old.normal),
774 };
775 retrim_planar_face(face, &turned, &final_edges, scale, OP)?;
776 }
777 Some(Draft::Cylinder { axis_point, radius, sign }) => {
778 let surface = drafted_cylinder(&face.surface, pull, *axis_point, *radius, *sign, tan, face.id)?;
779 let carrier = &carriers[&face.id];
780 let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
781 let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
782 for i in 0..=4 {
783 for j in 0..=4 {
784 let p = surface
785 .evaluate(u0 + (u1 - u0) * i as f64 / 4.0, v0 + (v1 - v0) * j as f64 / 4.0)
786 .or_refuse(KernelStage::Refine, "evaluate")?;
787 if carrier.residual(p).abs() > accept {
788 return Err(KernelRefusal::internal(KernelStage::Validate, "draft_cone_net", format!(
789 "{OP}: the drafted net of face {} leaves its cone by {:.3e} — refusing",
790 face.id,
791 carrier.residual(p).abs()
792 )));
793 }
794 }
795 }
796 rebuild_loop_pcurves(face, &final_edges, &surface, tolerance, OP)?;
797 face.surface = surface;
798 }
799 None if touched => match &carriers.get(&face.id) {
800 Some(Carrier::Plane { .. }) => {
801 let plane = plane_of_surface(&face.surface, plane_tolerance, OP)?;
802 retrim_planar_face(face, &plane, &final_edges, scale, OP)?;
803 }
804 Some(Carrier::Ruled { .. }) => ruled_retrims.push(face.id),
805 None => {
806 return Err(KernelRefusal::internal(KernelStage::Sew, "draft_unclassified", format!(
807 "{OP}: face {} lost an edge to the draft but has no carrier — refusing",
808 face.id
809 )));
810 }
811 },
812 None => {}
813 }
814 }
815 }
816 for face_id in ruled_retrims {
817 retrim_ruled_face(&mut result, face_id, &final_edges, tolerance, OP)?;
818 }
819 result.mass_properties_cache = Default::default();
820 accept_result(solid, &result)?;
821 Ok(result)
822}
823
824fn drafted_cylinder(
831 surface: &NurbsSurface,
832 pull: Vec3,
833 axis_point: Vec3,
834 radius: f64,
835 sign: f64,
836 tan: f64,
837 face_id: u64,
838) -> Result<NurbsSurface, KernelRefusal> {
839 let mut rows = surface.control_points.clone();
840 for row in &mut rows {
841 for control in row.iter_mut() {
842 let point = control.point().or_refuse(KernelStage::Refine, "point")?;
843 let w = point.sub(axis_point);
844 let h = w.dot(pull);
845 let q = w.sub(pull.scale(h));
846 let r = radius - sign * h * tan;
847 if r <= 0.0 {
848 return Err(KernelRefusal::unsupported(KernelStage::Refine, "draft_cone_apex", format!(
849 "{OP}: the cone drafted from face {face_id} reaches its apex within the face's \
850 carrier (radius {r:.6e} at height {h:.6e}) — refusing"
851 )));
852 }
853 let moved = axis_point.add(pull.scale(h)).add(q.scale(r / radius));
854 *control = Vec4::from_point(moved, control.w);
855 }
856 }
857 NurbsSurface::new(
858 surface.degree_u,
859 surface.degree_v,
860 surface.knots_u.clone(),
861 surface.knots_v.clone(),
862 rows,
863 )
864 .or_refuse(KernelStage::Refine, "drafted_cone")
865}
866
867fn accept_result(input: &BrepSolid, result: &BrepSolid) -> Result<(), KernelRefusal> {
869 let report = result.validate_detailed(&crate::KernelTolerances::for_solid(result, 1e-7));
870 if !report.issues.is_empty() {
871 return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!(
872 "{OP}: the drafted solid failed validation: {:?}", report.issues
873 )));
874 }
875 let crossings = crate::loop_self_crossings(result);
876 if !crossings.unreadable.is_empty() || crossings.loops == 0 {
877 return Err(KernelRefusal::internal(KernelStage::Validate, "crossing_scan_unreadable", format!(
878 "{OP}: the loop self-crossing scan could not read the drafted body ({:?}) — refusing",
879 crossings.unreadable
880 )));
881 }
882 if crossings.is_flagged() {
883 return Err(KernelRefusal::unsupported(KernelStage::Validate, CONSUMES_FACE, format!(
884 "{OP}: the draft makes a face's own loop cross itself ({}) — refusing",
885 crossings.summary().unwrap_or_default()
886 )));
887 }
888 if let (Ok(before), Ok(after)) =
889 (crate::signed_volume_against(input, 0.0), crate::signed_volume_against(result, 0.0))
890 {
891 if before * after <= 0.0 {
892 return Err(KernelRefusal::unsupported(KernelStage::Validate, CONSUMES_FACE, format!(
893 "{OP}: the draft inverts the solid (signed volume changed sign) — refusing"
894 )));
895 }
896 }
897 if !report.wire_warnings.is_empty() {
898 let inherited = input.validate_detailed(&crate::KernelTolerances::for_solid(input, 1e-7)).wire_warnings;
899 if report.wire_warnings.len() > inherited.len() {
900 return Err(KernelRefusal::internal(KernelStage::Validate, "chart_winding", format!(
901 "{OP}: the draft leaves a face whose (u,v) chart is left-handed against its own \
902 normal ({}) — refusing",
903 report.wire_warnings.iter().map(|w| w.message.as_str()).collect::<Vec<_>>().join("; ")
904 )));
905 }
906 }
907 Ok(())
908}
909
910fn draft_convex_polyhedron(
918 solid: &BrepSolid,
919 face_ids: &[u64],
920 pull_direction: Vec3,
921 neutral_point: Vec3,
922 angle_radians: f64,
923) -> Result<BrepSolid, String> {
924 let pull = pull_direction.normalized()?;
925 let scale = solid_model_scale(solid);
926 let plane_tolerance = (scale * 1e-6).max(1e-7);
927 let selected: HashSet<u64> = face_ids.iter().copied().collect();
928 let (sin, cos) = angle_radians.sin_cos();
929 let mut half_spaces: Vec<(Vec3, Vec3)> = Vec::new();
930 for shell in &solid.shells {
931 for face in &shell.faces {
932 let plane = plane_of_surface(&face.surface, plane_tolerance, OP)
933 .map_err(|_| format!("face {} is not planar", face.id))?;
934 let outward = plane.normal.scale(outward_sign(face));
935 if selected.contains(&face.id) {
936 let height = plane.origin.sub(neutral_point).dot(pull);
937 let on_hinge = plane.origin.sub(pull.scale(height));
938 half_spaces.push((on_hinge, outward.scale(cos).add(pull.scale(sin)).normalized()?));
939 } else {
940 half_spaces.push((plane.origin, outward));
941 }
942 }
943 }
944 if solid.shells.len() != 1 {
945 return Err("the body has more than one shell".into());
946 }
947 for shell in &solid.shells {
948 for face in &shell.faces {
949 let plane = plane_of_surface(&face.surface, plane_tolerance, OP).map_err(|e| e.to_string())?;
950 let outward = plane.normal.scale(outward_sign(face));
951 if solid.vertices.iter().any(|v| v.point.sub(plane.origin).dot(outward) > plane_tolerance * 10.0) {
952 return Err(format!("the body is not convex (a vertex lies outside face {})", face.id));
953 }
954 }
955 }
956 let centre = solid.vertices.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, v| s.add(v.point)).scale(1.0 / solid.vertices.len().max(1) as f64);
964 let mut planes: Vec<(Vec3, f64)> = Vec::new();
965 for (origin, normal) in &half_spaces {
966 let offset = normal.dot(origin.sub(centre));
967 if !planes.iter().any(|(n, d)| n.dot(*normal) > 1.0 - 1e-12 && (d - offset).abs() <= plane_tolerance) {
968 planes.push((*normal, offset));
969 }
970 }
971 let (corners, loops) = brep_construction::solid_sweep_caps::polyhedron_of_planes(&planes).map_err(|e| e.to_string())?;
972 if corners.len() < 4 || loops.len() < 4 {
973 return Err("the drafted half-spaces leave nothing".into());
974 }
975 let corners: Vec<Vec3> = corners.iter().map(|p| p.add(centre)).collect();
976 let body = brep_construction::make_polyhedron_brep(&corners, &loops).map_err(|e| format!("the drafted half-spaces do not bound a solid ({e})"))?;
977 accept_result(solid, &body).map_err(|e| e.to_string())?;
978 Ok(body)
979}
980
981pub fn draft_faces_parted(
989 solid: &BrepSolid,
990 face_ids: &[u64],
991 pull_direction: Vec3,
992 parting_point: Vec3,
993 angle_radians: f64,
994) -> Result<BrepSolid, KernelRefusal> {
995 let pull = check_inputs(face_ids, pull_direction, parting_point, angle_radians)?;
996 let scale = solid_model_scale(solid);
997 let plane_tolerance = (scale * 1e-6).max(1e-7);
998 let mut face_lookup: HashMap<u64, (usize, usize)> = HashMap::default();
999 for (shell_index, shell) in solid.shells.iter().enumerate() {
1000 for (face_index, face) in shell.faces.iter().enumerate() {
1001 face_lookup.entry(face.id).or_insert((shell_index, face_index));
1002 }
1003 }
1004 let mut wanted = Vec::new();
1005 for &face_id in face_ids {
1006 if !face_lookup.contains_key(&face_id) {
1007 return Err(KernelRefusal::input(KernelStage::Collect, "face_id", format!("{OP}: no face with id {face_id}")));
1008 }
1009 let carrier = carrier_of(solid, &face_lookup, face_id, pull, plane_tolerance).ok_or_else(|| {
1010 KernelRefusal::unsupported(KernelStage::Classify, "draft_carrier_kind", format!(
1011 "{OP}: face {face_id} is neither a plane parallel to the pull direction nor a \
1012 cylinder whose axis is the pull direction — refusing"
1013 ))
1014 })?;
1015 wanted.push(carrier);
1016 }
1017 let (below, above) = crate::split_solid_by_plane(solid, parting_point, pull).map_err(|error| {
1018 KernelRefusal::unsupported(KernelStage::Classify, "draft_parting_plane", format!(
1019 "{OP}: the parting plane does not divide the body ({error}) — refusing"
1020 ))
1021 })?;
1022 let same = |a: &Carrier, b: &Carrier| -> bool {
1023 match (a, b) {
1024 (Carrier::Plane { origin: oa, normal: na }, Carrier::Plane { origin: ob, normal: nb }) => {
1025 na.cross(*nb).length() <= 1e-9 && ob.sub(*oa).dot(*na).abs() <= plane_tolerance
1026 }
1027 (
1028 Carrier::Ruled { frame: fa, rho0: ra0, rho1: ra1, height: ha },
1029 Carrier::Ruled { frame: fb, rho0: rb0, rho1: rb1, height: hb },
1030 ) => {
1031 let offset = fb.origin.sub(fa.origin);
1032 fa.axis.cross(fb.axis).length() <= 1e-9
1033 && offset.sub(fa.axis.scale(offset.dot(fa.axis))).length() <= plane_tolerance
1034 && ((ra1 - ra0) / ha).abs() <= 1e-9
1035 && ((rb1 - rb0) / hb).abs() <= 1e-9
1036 && (ra0 - rb0).abs() <= plane_tolerance
1037 }
1038 _ => false,
1039 }
1040 };
1041 let mut halves = Vec::new();
1042 for (piece, side_pull) in [(above, pull), (below, pull.scale(-1.0))] {
1043 let mut lookup: HashMap<u64, (usize, usize)> = HashMap::default();
1044 for (shell_index, shell) in piece.shells.iter().enumerate() {
1045 for (face_index, face) in shell.faces.iter().enumerate() {
1046 lookup.entry(face.id).or_insert((shell_index, face_index));
1047 }
1048 }
1049 let mut ids: Vec<u64> = lookup
1050 .keys()
1051 .copied()
1052 .filter(|&id| {
1053 carrier_of(&piece, &lookup, id, pull, plane_tolerance)
1054 .map_or(false, |c| wanted.iter().any(|w| same(w, &c)))
1055 })
1056 .collect();
1057 ids.sort_unstable();
1058 if ids.is_empty() {
1059 return Err(KernelRefusal::unsupported(KernelStage::Classify, "draft_parting_side", format!(
1060 "{OP}: no selected face reaches one side of the parting plane — refusing"
1061 )));
1062 }
1063 halves.push(draft_faces_unchecked(&piece, &ids, side_pull, parting_point, angle_radians)?);
1064 }
1065 crate::boolean_operation(
1066 &halves[0],
1067 &halves[1],
1068 crate::BooleanOperation::Union,
1069 &crate::BooleanOptions::default(),
1070 )
1071}