diff --git a/crates/kernel/src/prism_curve.rs b/crates/kernel/src/prism_curve.rs index 8aa74ae44..62c5c5821 100644 --- a/crates/kernel/src/prism_curve.rs +++ b/crates/kernel/src/prism_curve.rs @@ -608,8 +608,8 @@ mod tests { let ends = [at(c, interval[0]), at(c, interval[1])]; Run { curve: c, interval, forward, ends: if forward { ends } else { [ends[1], ends[0]] } } } - /// The quarter circle of radius 10 about the origin from +x to +y, as truck's circle arcs - /// were: a rational quadratic spline. + /// The quarter circle of radius 10 about the origin from +x to +y, as a rational quadratic + /// spline. fn quarter() -> Curve { let w = std::f64::consts::FRAC_1_SQRT_2; Curve::RationalSpline { knots: bezier_knots(2), homogeneous: vec![[10., 0., 0., 1.], [10. * w, 10. * w, 0., w], [0., 10., 0., 1.]] } diff --git a/crates/kernel/src/prism_measure.rs b/crates/kernel/src/prism_measure.rs index f0cf64f58..eee0405a2 100644 --- a/crates/kernel/src/prism_measure.rs +++ b/crates/kernel/src/prism_measure.rs @@ -1,8 +1,13 @@ -//! Independent current-geometry intervals for uniform prisms. -//! These are not mesh measurements or certificates of construction history. -use crate::body::from_p3; +//! Independent current-geometry intervals for uniform prisms, read off the body's schema 4 +//! record. These are not mesh measurements or certificates of construction history. +use crate::prism_curve::{Run, segment}; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::brep::{Brep, Curve, Loop, Shell, Surface}; use solidcraft_geom::{Plane, Ring, Seg2, Vec2, Vec3}; -use truck_modeling as mt; + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} #[derive(Clone, Copy, Debug)] struct Interval { @@ -52,11 +57,8 @@ struct CapLoop { /// Cross-product cancellation belongs to the surface representation, not /// just the later incidence dot product. Reject ill-conditioned plane bases. -fn plane_normal(p: &mt::Plane) -> Option<(Vec3, Vec3)> { - let u = p.u_axis(); - let v = p.v_axis(); - let u = Vec3::new(u.x, u.y, u.z); - let v = Vec3::new(v.x, v.y, v.z); +/// The natural normal of the plane spanned by `u` and `v`, and a bound on its rounding error. +fn plane_normal(u: Vec3, v: Vec3) -> Option<(Vec3, Vec3)> { let cross = u.cross(v); let length = cross.len(); if !length.is_finite() || length <= 1e-6 * u.len() * v.len() { @@ -69,52 +71,77 @@ fn plane_normal(p: &mt::Plane) -> Option<(Vec3, Vec3)> { (ne.x.is_finite() && ne.y.is_finite() && ne.z.is_finite()).then_some((n, ne)) } +/// A planar surface's origin and spanning vectors (as its record holds them). +fn plane_of(s: &Surface) -> Option<(Vec3, Vec3, Vec3)> { + match s { + Surface::Plane { origin, u_axis, v_axis } => Some((v3(*origin), v3(*u_axis), v3(*v_axis))), + Surface::PlaneThrough { origin, u_point, v_point } => { + let o = v3(*origin); + Some((o, v3(*u_point) - o, v3(*v_point) - o)) + } + _ => None, + } +} + +/// `v` (a point when `w` is 1, a direction when 0) mapped by the column-major affine `m`; `None` +/// where the map is not affine there. +fn placed(m: &[[f64; 4]; 4], v: Vec3, w: f64) -> Option { + let c = |k: usize| m[0][k] * v.x + m[1][k] * v.y + m[2][k] * v.z + m[3][k] * w; + (c(3) == w).then(|| Vec3::new(c(0), c(1), c(2))) +} + +/// A revolution of a line: the line's ends, the axis origin and unit axis, the placement. +type Revolved<'a> = (Vec3, Vec3, Vec3, Vec3, &'a [[f64; 4]; 4]); + +fn revolved_line(s: &Surface) -> Option> { + let Surface::PlacedRevolution { profile, origin, axis, matrix, .. } = s else { return None }; + let Curve::Line { start, end } = &**profile else { return None }; + Some((v3(*start), v3(*end), v3(*origin), v3(*axis).normalized()?, matrix)) +} + +/// A spline surface's control net, `(point, weight)` with `[i][j]` i along u, and its knots. +type Net<'a> = (Vec>, &'a [f64], &'a [f64]); + +fn net_of(s: &Surface) -> Option> { + match s { + Surface::Spline { u_knots, v_knots, points } => { + Some((points.iter().map(|r| r.iter().map(|p| (v3(*p), 1.)).collect()).collect(), u_knots, v_knots)) + } + Surface::RationalSpline { u_knots, v_knots, homogeneous } => Some(( + homogeneous.iter().map(|r| r.iter().map(|p| (Vec3::new(p[0] / p[3], p[1] / p[3], p[2] / p[3]), p[3])).collect()).collect(), + u_knots, + v_knots, + )), + _ => None, + } +} + /// A whole positive control-net bound for the wall's projected variation. /// A sampled normal or a vertex-only test is deliberately insufficient. -fn wall_error(surface: &mt::Surface, d: Vec3, height: f64, work: &mut usize) -> Option { - if let mt::Surface::Plane(p) = surface { - let (n, ne) = plane_normal(p)?; +fn wall_error(surface: &Surface, d: Vec3, height: f64, work: &mut usize) -> Option { + if let Some((_, u, v)) = plane_of(surface) { + let (n, ne) = plane_normal(u, v)?; let terms = (n.x * d.x).abs() + (n.y * d.y).abs() + (n.z * d.z).abs(); let error = ne.x * d.x.abs() + ne.y * d.y.abs() + ne.z * d.z.abs() + 1024. * f64::EPSILON * terms; return Some((n.dot(d).abs() + error) * height * 2.); } - if let mt::Surface::RevolutedCurve(p) = surface { - let r = p.entity(); - let mt::Curve::Line(line) = r.entity_curve() else { return None }; - let axis = r.axis(); - let meridian = line.1 - line.0; - let a = Vec3::new(axis.x, axis.y, axis.z).normalized()?; - let m = Vec3::new(meridian.x, meridian.y, meridian.z).normalized()?; - let placed = *p.transform() * mt::Vector4::new(axis.x, axis.y, axis.z, 0.); - if placed.w != 0. { - return None; - } - let pa = Vec3::new(placed.x, placed.y, placed.z).normalized()?; + if let Surface::Cylinder { frame, .. } = surface { + let a = v3(frame.x_axis).cross(v3(frame.y_axis)).normalized()?; + return Some(a.cross(d).len() * height * 4.); + } + if let Some((start, end, _, a, matrix)) = revolved_line(surface) { + let m = (end - start).normalized()?; + let pa = placed(matrix, a, 0.)?.normalized()?; return Some((a.cross(m).len() + pa.cross(d).len()) * height * 4.); } - let (rows, cols) = match surface { - mt::Surface::BSplineSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - mt::Surface::NurbsSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - _ => return None, - }; + let (points, _, _) = net_of(surface)?; + let (rows, cols) = (points.len(), points.first()?.len()); let count = rows.checked_mul(cols)?; - let rectangular = match surface { - mt::Surface::BSplineSurface(s) => s.control_points().iter().all(|r| r.len() == cols), - mt::Surface::NurbsSurface(s) => s.control_points().iter().all(|r| r.len() == cols), - _ => false, - }; - if rows < 2 || cols < 2 || count > 16_384 || !rectangular { + if rows < 2 || cols < 2 || count > 16_384 || !points.iter().all(|r| r.len() == cols) { return None; } *work = work.checked_sub(count.checked_mul(4)?)?; - let points: Vec> = match surface { - mt::Surface::BSplineSurface(s) => s.control_points().iter().map(|r| r.iter().map(|p| (from_p3(*p), 1.)).collect()).collect(), - mt::Surface::NurbsSurface(s) => { - s.control_points().iter().map(|r| r.iter().map(|p| (Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w), p.w)).collect()).collect() - } - _ => return None, - }; - if points.iter().any(|r| r.len() != cols) || points.iter().flatten().any(|(p, w)| !p.is_finite() || !w.is_finite() || *w <= 0.) { + if points.iter().flatten().any(|(p, w)| !p.is_finite() || !w.is_finite() || *w <= 0.) { return None; } let max_w = points.iter().flatten().map(|p| p.1).fold(0., f64::max); @@ -181,16 +208,24 @@ fn segment_same(a: &Seg2, b: &Seg2, tolerance: f64) -> bool { } } -fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, levels: (f64, f64), tol: f64, work: &mut usize) -> Option { - use mt::{BoundedCurve, ParametricCurve}; - let cap = crate::prism_curve::segment(edge, plane, tol, work)?; - if let mt::Surface::Plane(p) = surface { - let (n, ne) = plane_normal(p)?; - let origin = from_p3(p.origin()); +/// Does the wall (`surface` over the face's `domain`) carry the cap boundary `cap` (an edge of a +/// cap at level `level`, read in `plane`) between the cap levels `levels`? +fn wall_supports_cap( + surface: &Surface, + domain: &[[f64; 2]; 2], + cap: &[Seg2], + level: f64, + plane: &Plane, + levels: (f64, f64), + tol: f64, + work: &mut usize, +) -> Option { + if let Some((origin, u, v)) = plane_of(surface) { + let (n, ne) = plane_normal(u, v)?; for s in cap { - let Seg2::Line { a, b } = s else { return Some(false) }; + let Seg2::Line { a, b } = *s else { return Some(false) }; for q in [a, b] { - let point = plane.to_world(q) + plane.normal() * plane.height(from_p3(edge.front().point())); + let point = plane.to_world(q) + plane.normal() * level; let delta = point - origin; let error = 1024. * f64::EPSILON * (1. + point.len() + origin.len()) + delta.x.abs() * ne.x + delta.y.abs() * ne.y + delta.z.abs() * ne.z; @@ -201,28 +236,33 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve } return Some(true); } - if let mt::Surface::RevolutedCurve(processor) = surface { - let r = processor.entity(); - let mt::Curve::Line(line) = r.entity_curve() else { return None }; - let o = from_p3(r.origin()); - let axis = r.axis(); - let axis = Vec3::new(axis.x, axis.y, axis.z).normalized()?; - let delta = from_p3(line.0) - o; + let on_circle = |center: Vec2, radius: f64| { + cap.iter().all(|s| matches!(*s, Seg2::Arc { center: c, radius: r, .. } if c.dist(center) + (r - radius).abs() <= tol * 8.)) + }; + let spans = |ha: f64, hb: f64| !(ha.min(hb) > levels.0 + tol * 8. || ha.max(hb) < levels.1 - tol * 8.); + if let Surface::Cylinder { frame, radius } = surface { + let (o, x, y) = (v3(frame.origin), v3(frame.x_axis), v3(frame.y_axis)); + let z = x.cross(y); + // The face's heights along the axis: the rest of the cylinder carries no cap. + let [v0, v1] = domain[1]; + if !spans(plane.height(o + z * v0), plane.height(o + z * v1)) { + return Some(false); + } + if x.dot(plane.normal()).abs() * radius > tol || y.dot(plane.normal()).abs() * radius > tol { + return None; + } + return Some(on_circle(plane.to_local(o), *radius)); + } + if let Some((start, end, o, axis, matrix)) = revolved_line(surface) { + let delta = start - o; let radial = (delta - axis * delta.dot(axis)).len(); let u = axis.any_perp(); let v = axis.cross(u); - let matrix = *processor.transform(); - let place = |p: Vec3, w: f64| { - let q = matrix * mt::Vector4::new(p.x, p.y, p.z, w); - (q.w == w).then_some(Vec3::new(q.x, q.y, q.z)) - }; - let center = plane.to_local(place(o, 1.)?); - let ha = plane.height(place(from_p3(line.0), 1.)?); - let hb = plane.height(place(from_p3(line.1), 1.)?); - if ha.min(hb) > levels.0 + tol * 8. || ha.max(hb) < levels.1 - tol * 8. { + let center = plane.to_local(placed(matrix, o, 1.)?); + if !spans(plane.height(placed(matrix, start, 1.)?), plane.height(placed(matrix, end, 1.)?)) { return Some(false); } - let (pu, pv) = (place(u, 0.)?, place(v, 0.)?); + let (pu, pv) = (placed(matrix, u, 0.)?, placed(matrix, v, 0.)?); let radius = pu.len() * radial; if (pu.len() - pv.len()).abs() * radial > tol || pu.dot(pv).abs() * radial > tol @@ -231,21 +271,12 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve { return None; } - return Some(cap.iter().all(|s| matches!(*s,Seg2::Arc {center:c,radius:r,..} if c.dist(center)+(r-radius).abs()<=tol*8.))); + return Some(on_circle(center, radius)); } - let (rows, cols) = match surface { - mt::Surface::BSplineSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - mt::Surface::NurbsSurface(s) => (s.control_points().len(), s.control_points().first()?.len()), - _ => return None, - }; + let (points, u_knots, v_knots) = net_of(surface)?; + let (rows, cols) = (points.len(), points.first()?.len()); *work = work.checked_sub(rows.checked_mul(cols)?.checked_mul(4)?)?; - let at = |i: usize, j: usize| -> Option<(Vec3, f64)> { - match surface { - mt::Surface::BSplineSurface(s) => s.control_points().get(i)?.get(j).map(|p| (from_p3(*p), 1.)), - mt::Surface::NurbsSurface(s) => s.control_points().get(i)?.get(j).map(|p| (Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w), p.w)), - _ => None, - } - }; + let at = |i: usize, j: usize| -> Option<(Vec3, f64)> { points.get(i)?.get(j).copied() }; for transpose in [false, true] { let point = |i, j| if transpose { at(j, i) } else { at(i, j) }; let (groups, length) = if transpose { (cols, rows) } else { (rows, cols) }; @@ -255,23 +286,7 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve if !(2..=4096).contains(&groups) || length != 2 { continue; } - let axial_knots = match surface { - mt::Surface::BSplineSurface(s) => { - if transpose { - s.uknot_vec() - } else { - s.vknot_vec() - } - } - mt::Surface::NurbsSurface(s) => { - if transpose { - s.uknot_vec() - } else { - s.vknot_vec() - } - } - _ => return None, - }; + let axial_knots = if transpose { u_knots } else { v_knots }; if axial_knots.len() != 4 || axial_knots.first() != axial_knots.get(1) || axial_knots.get(2) != axial_knots.last() @@ -286,7 +301,7 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve let (base, w) = point(i, 0)?; let h0 = plane.height(base); let h1 = plane.height(point(i, 1)?.0); - if h0.min(h1) > levels.0 + tol * 8. || h0.max(h1) < levels.1 - tol * 8. || increasing.is_some_and(|s| s != (h1 > h0)) { + if !spans(h0, h1) || increasing.is_some_and(|s| s != (h1 > h0)) { valid = false; break; } @@ -299,46 +314,35 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve } } let q = plane.to_world(p); - projected.push(mt::Vector4::new(q.x * w, q.y * w, q.z * w, w)); + projected.push([q.x * w, q.y * w, q.z * w, w]); } if !valid { continue; } - let knots = match surface { - mt::Surface::BSplineSurface(s) => { - if transpose { - s.vknot_vec() - } else { - s.uknot_vec() - } - } - mt::Surface::NurbsSurface(s) => { - if transpose { - s.vknot_vec() - } else { - s.uknot_vec() - } - } - _ => return None, - }; + let knots = if transpose { v_knots } else { u_knots }; if knots.len() > 8192 { return None; } *work = work.checked_sub(knots.len())?; - let c = mt::Curve::NurbsCurve(mt::NurbsCurve::new(mt::BSplineCurve::try_new(knots.clone(), projected).ok()?)); - let (a, b) = c.range_tuple(); - let support = mt::Edge::new(&mt::Vertex::new(c.subs(a)), &mt::Vertex::new(c.subs(b)), c); - let Some(fit) = crate::prism_curve::segment(&support, plane, tol, work) else { + let degree = knots.len().checked_sub(projected.len() + 1)?; + let interval = [*knots.get(degree)?, *knots.get(projected.len())?]; + if !(interval[0] < interval[1]) { + continue; + } + let support = Curve::RationalSpline { knots: knots.to_vec(), homogeneous: projected }; + let eval = CurveEval::new(&support).ok()?; + let ends = [eval.point(interval[0])?, eval.point(interval[1])?]; + let Some(fit) = segment(&Run { curve: &support, interval, forward: true, ends }, plane, tol, work) else { continue; }; let fit_loop = CapLoop { segments: Ring::from(fit.clone()), area: Interval::enclosing(0., 0.)? }; if let Some((center, radius)) = circle(&fit_loop, tol * 8.) - && cap.iter().all(|s| matches!(*s,Seg2::Arc {center:c,radius:r,..} if c.dist(center)+(r-radius).abs()<=tol*8.)) + && on_circle(center, radius) { return Some(true); } let same = loops_same( - &CapLoop { segments: Ring::from(cap.clone()), area: Interval::enclosing(0., 0.)? }, + &CapLoop { segments: Ring::from(cap.to_vec()), area: Interval::enclosing(0., 0.)? }, &CapLoop { segments: Ring::from(fit), area: Interval::enclosing(0., 0.)? }, tol * 8., work, @@ -399,23 +403,322 @@ struct Certificate { hi: f64, } -fn preflight_body(body: &crate::Body) -> Option<()> { - if body.solid.boundaries().len() != 1 || body.mesh.is_some() { +/// One closed face shell within the budgets: each face's outward side (whether it is its +/// surface's natural normal). +fn preflight(record: &Brep) -> Option> { + let [Shell::Faces { faces, .. }] = record.shells.as_slice() else { return None }; + if record.faces.len() > 16_384 || faces.len() != record.faces.len() { return None; } - let mut faces = 16_384usize; let mut edges = 65_536usize; - for face in body.solid.face_iter() { - faces = faces.checked_sub(1)?; - // Borrow absolute wires: the oriented iterator would clone a hostile - // oversized wire before its edge count has been checked. - for wire in face.absolute_boundaries() { - for _ in wire.edge_iter() { - edges = edges.checked_sub(1)?; + for face in &record.faces { + for lp in &face.loops { + if let Loop::Edges { edges: uses } = lp { + edges = edges.checked_sub(uses.len())?; } } } - Some(()) + let mut outward = vec![None; record.faces.len()]; + for f in faces { + let slot = outward.get_mut(f.face as usize)?; + if slot.is_some() { + return None; + } + *slot = Some(f.forward); + } + outward.into_iter().collect() +} + +/// Face `face`'s edges, each once per use. +fn face_edges(record: &Brep, face: usize) -> impl Iterator + '_ { + record + .faces + .get(face) + .into_iter() + .flat_map(|f| &f.loops) + .flat_map(|lp| match lp { + Loop::Edges { edges } => edges.as_slice(), + Loop::Vertex { .. } => &[], + }) + .map(|e| e.edge as usize) +} + +/// The points of face `face`'s vertices (once per edge use). +fn face_points(record: &Brep, face: usize) -> impl Iterator + '_ { + face_edges(record, face) + .filter_map(|e| record.edges.get(e)) + .flat_map(|e| e.vertices) + .filter_map(|v| record.vertices.get(v as usize)) + .map(|v| v3(v.point)) +} + +/// Loop `l` of face `face` as it runs about the face's outward normal (`outward`: the natural +/// one), each edge with its number. +fn loop_runs(record: &Brep, face: usize, l: usize, outward: bool) -> Option)>> { + let Loop::Edges { edges } = record.faces.get(face)?.loops.get(l)? else { return None }; + let mut runs = + edges.iter().map(|e| Some((e.edge as usize, Run::of(record, e.edge as usize, e.forward == outward)?))).collect::>>()?; + if !outward { + runs.reverse(); + } + Some(runs) +} + +fn certificate(record: &Brep, body_size: f64, plane: &Plane, tol: f64) -> Option { + let outward = preflight(record)?; + let d = plane.normal(); + let mut caps = Vec::new(); + let mut walls = Vec::new(); + let mut edge_uses = 65_536usize; + for (fi, face) in record.faces.iter().enumerate() { + for _ in face_edges(record, fi) { + edge_uses = edge_uses.checked_sub(1)?; + } + let out = *outward.get(fi)?; + if let Some((_, u, v)) = plane_of(&face.surface) { + let n = u.cross(v).normalized()? * if out { 1. } else { -1. }; + if n.dot(d).abs() > 1. - 1e-12 { + if n.cross(d).len() * body_size > tol { + return None; + } + // A planar support's parameter origin may be arbitrarily far + // from its trimmed face. Use actual boundary geometry only. + let level = plane.height(face_points(record, fi).next()?); + caps.push((fi, level, n.dot(d) > 0.)); + if caps.len() > 2 { + return None; + } + continue; + } + } + walls.push(fi); + } + if caps.len() != 2 { + return None; + } + let top = *caps.iter().find(|c| c.2)?; + let bottom = *caps.iter().find(|c| !c.2)?; + let height = top.1 - bottom.1; + if height <= tol || !height.is_finite() { + return None; + } + for cap in [top, bottom] { + let (origin, u, v) = plane_of(&record.faces.get(cap.0)?.surface)?; + let (n, ne) = plane_normal(u, v)?; + for point in face_points(record, cap.0) { + let delta = point - origin; + let terms = (delta.x * n.x).abs() + (delta.y * n.y).abs() + (delta.z * n.z).abs(); + let error = 1024. * f64::EPSILON * terms + delta.x.abs() * ne.x + delta.y.abs() * ne.y + delta.z.abs() * ne.z; + if delta.dot(n).abs() + error > tol * 2. || (plane.height(point) - cap.1).abs() > tol * 2. { + return None; + } + } + } + let mut work = 2_000_000; + let cap_loops = |cap: usize, work: &mut usize| -> Option> { + let out = *outward.get(cap)?; + (0..record.faces.get(cap)?.loops.len()).map(|l| cap_loop(&loop_runs(record, cap, l, out)?, plane, tol, work)).collect() + }; + let loops = cap_loops(top.0, &mut work)?; + let lower = cap_loops(bottom.0, &mut work)?; + if loops.len() != lower.len() || loops.is_empty() || loops.len() > 8192 { + return None; + } + let mut pair_work = 16_000_000; + for a in &loops { + // Bottom cap has the opposite material orientation. + let reverse = CapLoop { segments: a.segments.clone(), area: Interval { lo: -a.area.hi, hi: -a.area.lo } }; + let mut matches = 0usize; + for b in &lower { + if loops_same(&reverse, b, tol * 8., &mut pair_work)? { + matches += 1; + } + } + if matches != 1 { + return None; + } + } + let mut controls = 262_144; + // Include cap fitting, support fitting and the <=8tol support-to-cap + // comparison, not just the control-net's projected ruling variation. + let mut corridor = tol * 16.; + let top_edges: std::collections::BTreeSet = face_edges(record, top.0).collect(); + let bottom_edges: std::collections::BTreeSet = face_edges(record, bottom.0).collect(); + let cap_edges = face_edges(record, top.0).count().checked_add(face_edges(record, bottom.0).count())?; + pair_work = pair_work.checked_sub((65_536 - edge_uses).checked_mul(cap_edges)?)?; + for &wall in &walls { + let face = record.faces.get(wall)?; + let variation = wall_error(&face.surface, d, height, &mut controls)?; + if variation > tol * 8. { + return None; + } + corridor = corridor.max(tol * 16. + variation); + if corridor > tol * 24. { + return None; + } + // Every wall must end on these actual cap wires. This is topology + // correspondence, not nearest geometry or stale face provenance. + let mut upper = 0usize; + let mut lower = 0usize; + for edge in face_edges(record, wall) { + let run = Run::of(record, edge, true)?; + let (on_top, on_bottom) = (top_edges.contains(&edge), bottom_edges.contains(&edge)); + if on_top || on_bottom { + let cap = segment(&run, plane, tol, &mut work)?; + if !wall_supports_cap(&face.surface, &face.domain, &cap, plane.height(run.ends[0]), plane, (bottom.1, top.1), tol, &mut work)? { + return None; + } + if on_top { + upper += 1; + } else { + lower += 1; + } + continue; + } + if !matches!(run.curve, Curve::Line { .. }) { + return None; + } + let eval = CurveEval::new(run.curve).ok()?; + let (p, q) = (eval.point(run.interval[0])?, eval.point(run.interval[1])?); + if p.dist(run.ends[0]) > tol || q.dist(run.ends[1]) > tol { + return None; + } + let delta = q - p; + if delta.cross(d).len() > corridor || delta.dot(d).abs() < height - tol * 8. { + return None; + } + } + if upper == 0 || upper != lower { + return None; + } + } + let mut area = Interval::enclosing(0., 0.)?; + let mut length = 0.; + let mut count = 0usize; + for lp in &loops { + area = area.add(lp.area)?; + for edge in &lp.segments { + length += edge.length(); + count = count.checked_add(1)?; + } + } + if count > 8192 || area.lo <= 0. { + return None; + } + separated_material(&loops, corridor * 16., &mut pair_work)?; + // Each boundary's monotone radial/linear corridor contributes at most a + // two-sided strip plus four endpoint disks. Unknown intersecting or + // touching corridors will be refused by the separation check below. + let strip = 2. * length * corridor + 4. * std::f64::consts::PI * count as f64 * corridor * corridor; + // Each cap's vertices are within 2tol and its whole rational edge + // control heights within another tol; include both cap corridors. + let h_error = tol * 8.; + if area.lo <= strip || height <= h_error { + return None; + } + let lo = (area.lo - strip) * (height - h_error); + let hi = (area.hi + strip) * (height + h_error); + let volume = Interval::enclosing((lo + hi) * 0.5, (hi - lo) * 0.5)?; + if volume.lo <= 0. || volume.hi - volume.lo > 0.001 { + return None; + } + Some(Certificate { loops, volume, lo: bottom.1, hi: top.1 }) +} + +/// Independently prove equality of the supported current uniform prisms. +/// `None` means unproved, including budget exhaustion; it never grants a copy. +pub fn certified_prism_equivalent(a: &crate::Body, b: &crate::Body) -> crate::Result> { + crate::guard("certified prism comparison", || { + if a.is_mesh() || b.is_mesh() || !a.size().is_finite() || !b.size().is_finite() { + return Ok(None); + } + let (ra, rb) = (crate::native::brep_record(a)?, crate::native::brep_record(b)?); + Ok(equivalent(&ra, a.size(), &rb, b.size())) + }) +} + +/// [`certified_prism_equivalent`] of the records `a` and `b` of bodies of sizes `size_a` and +/// `size_b`. +fn equivalent(a: &Brep, size_a: f64, b: &Brep, size_b: f64) -> Option { + let outward = preflight(a)?; + preflight(b)?; + let size = size_a.max(size_b).max(1.); + let tol = size * 1e-10; + let identity_tol = size * 1e-7; + let origin = v3(a.vertices.first()?.point); + let mut candidates = Vec::new(); + for (face, out) in a.faces.iter().zip(&outward) { + if let Some((_, u, v)) = plane_of(&face.surface) { + let n = u.cross(v).normalized()? * if *out { 1. } else { -1. }; + if !candidates.iter().any(|d: &Vec3| d.dot(n).abs() > 1. - 1e-12) { + candidates.push(n); + if candidates.len() == 8 { + break; + } + } + } + } + for d in candidates { + let plane = Plane::from_normal(origin, d)?; + let Some(ca) = certificate(a, size_a, &plane, tol) else { continue }; + let Some(cb) = certificate(b, size_b, &plane, tol) else { continue }; + if (ca.lo - cb.lo).abs() > identity_tol || (ca.hi - cb.hi).abs() > identity_tol || ca.loops.len() != cb.loops.len() { + return Some(false); + } + let mut work = 16_000_000; + let mut used = vec![false; cb.loops.len()]; + for lp in &ca.loops { + let mut matched = None; + for (i, other) in cb.loops.iter().enumerate() { + if !used.get(i).copied()? && loops_same(lp, other, identity_tol, &mut work)? { + if matched.is_some() { + return None; + } + matched = Some(i); + } + } + let Some(i) = matched else { return Some(false) }; + *used.get_mut(i)? = true; + } + let delta = (ca.volume.hi - cb.volume.lo).abs().max((cb.volume.hi - ca.volume.lo).abs()); + return Some(delta <= 1e-5 * (1. + ca.volume.lo.abs())); + } + None +} + +/// A cap's loop from its edges in order (each with its edge number), certified segment by +/// segment, with the interval of its signed area. +fn cap_loop(runs: &[(usize, Run)], plane: &Plane, tolerance: f64, work: &mut usize) -> Option { + let mut segments = Vec::new(); + let mut area = Interval::enclosing(0., 0.)?; + let mut ids = std::collections::HashSet::new(); + for (id, run) in runs { + if !ids.insert(*id) { + return None; + } + let certified = segment(run, plane, tolerance, work)?; + if segments.len().checked_add(certified.len())? > 8192 { + return None; + } + for segment in &certified { + area = area.add(green_interval(segment, tolerance)?)?; + } + segments.extend(certified); + } + // The edges run end to end round the loop. + let closed = runs.iter().zip(runs.iter().cycle().skip(1)).all(|((_, a), (_, b))| a.ends[1].dist(b.ends[0]) <= 2. * tolerance); + if segments.is_empty() || !closed { + return None; + } + // Curve endpoints already agree with actual shared vertices in the + // whole-span proof. Check the fitted representation's continuity too. + let segments = Ring::new(segments); + for (a, b) in segments.edges() { + if a.end().dist(b.start()) > 2. * tolerance { + return None; + } + } + Some(CapLoop { segments, area }) } /// Initial material scope: a convex straight outer or a circle, with separated @@ -493,261 +796,10 @@ fn separated_material(loops: &[CapLoop], clearance: f64, work: &mut usize) -> Op Some(()) } -fn certificate(body: &crate::Body, plane: &Plane, tol: f64) -> Option { - preflight_body(body)?; - let d = plane.normal(); - let body_size = body.size(); - let mut remaining = 16_384usize; - let mut caps = Vec::new(); - let mut walls = Vec::new(); - let mut edge_uses = 65_536usize; - for face in body.solid.face_iter() { - remaining = remaining.checked_sub(1)?; - for _ in face.edge_iter() { - edge_uses = edge_uses.checked_sub(1)?; - } - let surface = face.oriented_surface(); - if let mt::Surface::Plane(p) = &surface { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - if n.dot(d).abs() > 1. - 1e-12 { - if n.cross(d).len() * body_size > tol { - return None; - } - // A planar support's parameter origin may be arbitrarily far - // from its trimmed face. Use actual boundary geometry only. - let level = plane.height(from_p3(face.vertex_iter().next()?.point())); - caps.push((face, level, n.dot(d) > 0.)); - if caps.len() > 2 { - return None; - } - continue; - } - } - walls.push((face, surface)); - } - if caps.len() != 2 { - return None; - } - let top = caps.iter().find(|c| c.2)?; - let bottom = caps.iter().find(|c| !c.2)?; - let height = top.1 - bottom.1; - if height <= tol || !height.is_finite() { - return None; - } - for cap in [top, bottom] { - let mt::Surface::Plane(support) = cap.0.oriented_surface() else { - return None; - }; - let origin = from_p3(support.origin()); - let (n, ne) = plane_normal(&support)?; - for vertex in cap.0.vertex_iter() { - let point = from_p3(vertex.point()); - let delta = point - origin; - let terms = (delta.x * n.x).abs() + (delta.y * n.y).abs() + (delta.z * n.z).abs(); - let error = 1024. * f64::EPSILON * terms + delta.x.abs() * ne.x + delta.y.abs() * ne.y + delta.z.abs() * ne.z; - if delta.dot(n).abs() + error > tol * 2. || (plane.height(point) - cap.1).abs() > tol * 2. { - return None; - } - } - } - let mut work = 2_000_000; - let loops = top.0.boundaries().iter().map(|w| cap_loop(w, plane, tol, &mut work)).collect::>>()?; - let lower = bottom.0.boundaries().iter().map(|w| cap_loop(w, plane, tol, &mut work)).collect::>>()?; - if loops.len() != lower.len() || loops.is_empty() || loops.len() > 8192 { - return None; - } - let mut pair_work = 16_000_000; - for a in &loops { - // Bottom cap has the opposite material orientation. - let reverse = CapLoop { segments: a.segments.clone(), area: Interval { lo: -a.area.hi, hi: -a.area.lo } }; - let mut matches = 0usize; - for b in &lower { - if loops_same(&reverse, b, tol * 8., &mut pair_work)? { - matches += 1; - } - } - if matches != 1 { - return None; - } - } - let mut controls = 262_144; - // Include cap fitting, support fitting and the <=8tol support-to-cap - // comparison, not just the control-net's projected ruling variation. - let mut corridor = tol * 16.; - let cap_edges = top.0.edge_iter().count().checked_add(bottom.0.edge_iter().count())?; - pair_work = pair_work.checked_sub((65_536 - edge_uses).checked_mul(cap_edges)?)?; - for (face, surface) in &walls { - let variation = wall_error(surface, d, height, &mut controls)?; - if variation > tol * 8. { - return None; - } - corridor = corridor.max(tol * 16. + variation); - if corridor > tol * 24. { - return None; - } - // Every wall must end on these actual cap wires. This is topology - // correspondence, not nearest geometry or stale face provenance. - let mut upper = 0usize; - let mut lower = 0usize; - for edge in face.edge_iter() { - if top.0.edge_iter().any(|e| e.id() == edge.id()) { - if !wall_supports_cap(surface, &edge, plane, (bottom.1, top.1), tol, &mut work)? { - return None; - } - upper += 1; - continue; - } - if bottom.0.edge_iter().any(|e| e.id() == edge.id()) { - if !wall_supports_cap(surface, &edge, plane, (bottom.1, top.1), tol, &mut work)? { - return None; - } - lower += 1; - continue; - } - let mt::Curve::Line(line) = edge.curve() else { return None }; - if from_p3(line.0).dist(from_p3(edge.absolute_front().point())) > tol || from_p3(line.1).dist(from_p3(edge.absolute_back().point())) > tol - { - return None; - } - let delta = from_p3(line.1) - from_p3(line.0); - if delta.cross(d).len() > corridor || delta.dot(d).abs() < height - tol * 8. { - return None; - } - } - if upper == 0 || upper != lower { - return None; - } - } - let mut area = Interval::enclosing(0., 0.)?; - let mut length = 0.; - let mut count = 0usize; - for lp in &loops { - area = area.add(lp.area)?; - for edge in &lp.segments { - length += edge.length(); - count = count.checked_add(1)?; - } - } - if count > 8192 || area.lo <= 0. { - return None; - } - separated_material(&loops, corridor * 16., &mut pair_work)?; - // Each boundary's monotone radial/linear corridor contributes at most a - // two-sided strip plus four endpoint disks. Unknown intersecting or - // touching corridors will be refused by the separation check below. - let strip = 2. * length * corridor + 4. * std::f64::consts::PI * count as f64 * corridor * corridor; - // Each cap's vertices are within 2tol and its whole rational edge - // control heights within another tol; include both cap corridors. - let h_error = tol * 8.; - if area.lo <= strip || height <= h_error { - return None; - } - let lo = (area.lo - strip) * (height - h_error); - let hi = (area.hi + strip) * (height + h_error); - let volume = Interval::enclosing((lo + hi) * 0.5, (hi - lo) * 0.5)?; - if volume.lo <= 0. || volume.hi - volume.lo > 0.001 { - return None; - } - Some(Certificate { loops, volume, lo: bottom.1, hi: top.1 }) -} - -/// Independently prove equality of the supported current uniform prisms. -/// `None` means unproved, including budget exhaustion; it never grants a copy. -pub fn certified_prism_equivalent(a: &crate::Body, b: &crate::Body) -> crate::Result> { - crate::guard("certified prism comparison", || { - let result = (|| { - preflight_body(a)?; - preflight_body(b)?; - if !a.size().is_finite() || !b.size().is_finite() { - return None; - } - let size = a.size().max(b.size()).max(1.); - let tol = size * 1e-10; - let identity_tol = size * 1e-7; - let origin = a.solid.vertex_iter().next().map(|v| from_p3(v.point()))?; - let mut candidates = Vec::new(); - let mut remaining = 16_384usize; - for f in a.solid.face_iter() { - remaining = remaining.checked_sub(1)?; - if let mt::Surface::Plane(p) = f.oriented_surface() { - let n = p.normal(); - let n = Vec3::new(n.x, n.y, n.z).normalized()?; - if !candidates.iter().any(|d: &Vec3| d.dot(n).abs() > 1. - 1e-12) { - candidates.push(n); - if candidates.len() == 8 { - break; - } - } - } - } - for d in candidates { - let plane = Plane::from_normal(origin, d)?; - let Some(ca) = certificate(a, &plane, tol) else { continue }; - let Some(cb) = certificate(b, &plane, tol) else { continue }; - if (ca.lo - cb.lo).abs() > identity_tol || (ca.hi - cb.hi).abs() > identity_tol || ca.loops.len() != cb.loops.len() { - return Some(false); - } - let mut work = 16_000_000; - let mut used = vec![false; cb.loops.len()]; - for lp in &ca.loops { - let mut matched = None; - for (i, other) in cb.loops.iter().enumerate() { - if !used.get(i).copied()? && loops_same(lp, other, identity_tol, &mut work)? { - if matched.is_some() { - return None; - } - matched = Some(i); - } - } - let Some(i) = matched else { return Some(false) }; - *used.get_mut(i)? = true; - } - let delta = (ca.volume.hi - cb.volume.lo).abs().max((cb.volume.hi - ca.volume.lo).abs()); - return Some(delta <= 1e-5 * (1. + ca.volume.lo.abs())); - } - None - })(); - Ok(result) - }) -} - -fn cap_loop(wire: &mt::Wire, plane: &Plane, tolerance: f64, work: &mut usize) -> Option { - let mut segments = Vec::new(); - let mut area = Interval::enclosing(0., 0.)?; - let mut ids = std::collections::HashSet::new(); - for edge in wire.edge_iter() { - if !ids.insert(edge.id()) { - return None; - } - let certified = crate::prism_curve::segment(edge, plane, tolerance, work)?; - if segments.len().checked_add(certified.len())? > 8192 { - return None; - } - for segment in &certified { - area = area.add(green_interval(segment, tolerance)?)?; - } - segments.extend(certified); - } - if segments.is_empty() || !wire.is_closed() { - return None; - } - // Curve endpoints already agree with actual shared vertices in the - // whole-span proof. Check the fitted representation's continuity too. - let segments = Ring::new(segments); - for (a, b) in segments.edges() { - if a.end().dist(b.start()) > 2. * tolerance { - return None; - } - } - Some(CapLoop { segments, area }) -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { use super::*; - use mt::builder; fn drilled(radius: f64, shift: f64) -> crate::Body { use solidcraft_geom::{Loop2, Region2}; @@ -758,6 +810,19 @@ mod tests { crate::extrude(&Plane::XY, &[region], 0., 10.).unwrap().remove(0) } + fn record(b: &crate::Body) -> Brep { + crate::native::brep_record(b).unwrap() + } + + fn cert(b: &crate::Body, tol: f64) -> Option { + certificate(&record(b), b.size(), &Plane::XY, tol) + } + + /// The first face of `r` not on a plane. + fn curved(r: &Brep) -> usize { + r.faces.iter().position(|f| plane_of(&f.surface).is_none()).unwrap() + } + #[test] fn actual_drilled_prism_and_step_reopen_are_certified_without_history() { let source = drilled(6., 0.); @@ -766,18 +831,18 @@ mod tests { let copy = &imported.bodies[0].body; let exact = 4000. - 360. * std::f64::consts::PI; for body in [&source, copy] { - let cap = certificate(body, &Plane::XY, 3e-9).expect("actual complete current cap and walls"); + let cap = cert(body, 3e-9).expect("actual complete current cap and walls"); assert!(cap.volume.lo <= exact && cap.volume.hi >= exact, "{:?}, expected {exact}", cap.volume); assert!(cap.volume.hi - cap.volume.lo <= 0.001); } assert_eq!(certified_prism_equivalent(&source, copy).unwrap(), Some(true)); let wider = drilled(6.0001, 0.); - let a = certificate(&source, &Plane::XY, 3e-9).unwrap(); - let b = certificate(&wider, &Plane::XY, 3e-9).unwrap(); + let a = cert(&source, 3e-9).unwrap(); + let b = cert(&wider, 3e-9).unwrap(); assert!(a.volume.lo - b.volume.hi > 1e-5 * (1. + a.volume.hi)); assert_eq!(certified_prism_equivalent(&source, &wider).unwrap(), Some(false)); let shifted = drilled(6., 0.0001); - let same_volume = certificate(&shifted, &Plane::XY, 3e-9).unwrap(); + let same_volume = cert(&shifted, 3e-9).unwrap(); assert!(same_volume.volume.lo <= exact && same_volume.volume.hi >= exact); assert_eq!(certified_prism_equivalent(&source, &shifted).unwrap(), Some(false)); assert_eq!(crate::step_export(&[&source], "source").unwrap(), before); @@ -785,15 +850,14 @@ mod tests { #[test] fn poorly_conditioned_plane_walls_do_not_get_certificates() { - let origin = mt::Point3::new(0., 0., 0.); - let u = mt::Point3::new(1., 0., 0.); - let v = mt::Point3::new(1., 0., 1e-9); - let surface = mt::Surface::Plane(mt::Plane::new(origin, u, v)); - let edge = builder::line(&mt::Vertex::new(origin), &mt::Vertex::new(u)); + let surface = Surface::Plane { origin: [0., 0., 0.], u_axis: [1., 0., 0.], v_axis: [1., 0., 1e-9] }; + let line = Curve::Line { start: [0., 0., 0.], end: [1., 0., 0.] }; let mut work = 2_000_000; + let cap = + segment(&Run { curve: &line, interval: [0., 1.], forward: true, ends: [Vec3::ZERO, Vec3::X] }, &Plane::XY, 1e-9, &mut work).unwrap(); assert!(wall_error(&surface, Vec3::Z, 10., &mut work).is_none()); - assert!(wall_supports_cap(&surface, &edge, &Plane::XY, (0., 10.), 1e-9, &mut work).is_none()); - let normal = plane_normal(&mt::Plane::new(origin, u, mt::Point3::new(0., 0., 1.))).unwrap(); + assert!(wall_supports_cap(&surface, &[[0., 1.], [0., 1.]], &cap, 0., &Plane::XY, (0., 10.), 1e-9, &mut work).is_none()); + let normal = plane_normal(Vec3::X, Vec3::Z).unwrap(); assert!(normal.0.dist(-Vec3::Y) < 1e-12); assert!(normal.1.len() > 0.); } @@ -807,61 +871,69 @@ mod tests { let saved = crate::step_export(&[&moved], "actual boolean").unwrap(); let imported = crate::step_import(&saved).unwrap(); assert_eq!(certified_prism_equivalent(&moved, &imported.bodies[0].body).unwrap(), Some(true)); - // Preserve every current cap/edge ID while replacing only the curved + // Preserve every current cap/edge while replacing only the curved // wall support with radius five. Topology incidence alone must fail. - let wrong = drilled(5., 0.); - let wrong_surface = wrong.solid.face_iter().find(|f| !matches!(f.surface(), mt::Surface::Plane(_))).unwrap().surface(); - let faces = source - .solid - .face_iter() - .map(|f| { - if matches!(f.surface(), mt::Surface::Plane(_)) { - return f.clone(); - } - let mut face = mt::Face::new(f.absolute_boundaries().clone(), wrong_surface.clone()); - if !f.orientation() { - face.invert(); - } - face + let wrong = record(&drilled(5., 0.)); + let mut invalid = record(&source); + let wall = curved(&invalid); + invalid.faces[wall].surface = wrong.faces[curved(&wrong)].surface.clone(); + assert!(certificate(&invalid, source.size(), &Plane::XY, 3e-9).is_none()); + // The actual wall moved 1000 up: it carries no cap edge at the part's levels. + let actual = record(&source); + let wall = curved(&actual); + let mut shifted = actual.faces[wall].surface.clone(); + match &mut shifted { + Surface::Cylinder { frame, .. } => frame.origin[2] += 1000., + Surface::PlacedRevolution { matrix, .. } => matrix[3][2] += 1000., + Surface::Spline { points, .. } => points.iter_mut().flatten().for_each(|p| p[2] += 1000.), + Surface::RationalSpline { homogeneous, .. } => homogeneous.iter_mut().flatten().for_each(|p| p[2] += 1000. * p[3]), + other => panic!("unexpected wall {other:?}"), + } + let outward = preflight(&actual).unwrap(); + let top = (0..actual.faces.len()) + .find(|&f| { + plane_of(&actual.faces[f].surface) + .is_some_and(|(_, u, v)| u.cross(v).normalized().unwrap().z * if outward[f] { 1. } else { -1. } > 0.9) }) - .collect::>(); - let invalid = crate::Body::new(crate::body::Solid::try_new(vec![faces.into()]).unwrap()).unwrap(); - assert!(certificate(&invalid, &Plane::XY, 3e-9).is_none()); - let actual = source.solid.face_iter().find(|f| !matches!(f.surface(), mt::Surface::Plane(_))).unwrap().surface(); - let shifted = mt::Transformed::transformed(&actual, mt::Matrix4::from_translation(mt::Vector3::new(0., 0., 1000.))); - let top = source.solid.face_iter().find(|f| matches!(f.oriented_surface(),mt::Surface::Plane(p) if p.normal().z>0.9)).unwrap(); - let arc = top.edge_iter().find(|e| !matches!(e.curve(), mt::Curve::Line(_))).unwrap(); - assert_ne!(wall_supports_cap(&shifted, &arc, &Plane::XY, (0., 10.), 3e-9, &mut 2_000_000), Some(true)); + .unwrap(); + let arc = face_edges(&actual, top).find(|e| !matches!(actual.edges[*e].curve, Curve::Line { .. })).unwrap(); + let run = Run::of(&actual, arc, true).unwrap(); + let cap = segment(&run, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); + let domain = actual.faces[wall].domain; + assert_ne!( + wall_supports_cap(&shifted, &domain, &cap, Plane::XY.height(run.ends[0]), &Plane::XY, (0., 10.), 3e-9, &mut 2_000_000), + Some(true) + ); } #[test] fn cap_support_origin_is_not_a_trimmed_face_height() { let source = drilled(6., 0.); - let faces = source - .solid - .face_iter() - .map(|f| { - let mt::Surface::Plane(p) = f.surface() else { - return f.clone(); - }; - if p.normal().z.abs() < 0.9 { - return f.clone(); + let original = record(&source); + let mut same = original.clone(); + for face in &mut same.faces { + match &mut face.surface { + Surface::Plane { origin, u_axis, v_axis } if v3(*u_axis).cross(v3(*v_axis)).normalized().unwrap().z.abs() > 0.9 => { + *origin = (v3(*origin) + v3(*u_axis) * 1e8).into(); } - let origin = p.origin() + p.u_axis() * 1e8; - let plane = mt::Surface::Plane(mt::Plane::new(origin, origin + p.u_axis(), origin + p.v_axis())); - let mut face = mt::Face::new(f.absolute_boundaries().clone(), plane); - if !f.orientation() { - face.invert(); + Surface::PlaneThrough { origin, u_point, v_point } => { + let (o, u, v) = (v3(*origin), v3(*u_point), v3(*v_point)); + if (u - o).cross(v - o).normalized().unwrap().z.abs() > 0.9 { + let shift = (u - o) * 1e8; + (*origin, *u_point, *v_point) = ((o + shift).into(), (u + shift).into(), (v + shift).into()); + } } - face - }) - .collect::>(); - let same = crate::Body::new(crate::body::Solid::try_new(vec![faces.into()]).unwrap()).unwrap(); - assert_eq!(certified_prism_equivalent(&source, &same).unwrap(), Some(true)); + _ => {} + } + } + assert_eq!(equivalent(&original, source.size(), &same, source.size()), Some(true)); + let last = original.faces.len() - 1; + let outward = preflight(&original).unwrap()[last]; + let runs = loop_runs(&original, last, 0, outward).unwrap(); assert!( loops_same( - &cap_loop(&source.solid.face_iter().last().unwrap().boundaries()[0], &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), - &cap_loop(&source.solid.face_iter().last().unwrap().boundaries()[0], &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), + &cap_loop(&runs, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), + &cap_loop(&runs, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), 1e-6, &mut 0 ) @@ -879,26 +951,41 @@ mod tests { let doubled = CapLoop { segments: region.segs.iter().chain(®ion.segs).copied().collect(), area: Interval::enclosing(800., 1e-8).unwrap() }; assert!(separated_material(&[doubled], 1e-6, &mut 16_000_000).is_none()); let thin = crate::box_solid(Vec3::ZERO, Vec3::new(20., 20., 1e-5)).unwrap(); - assert!(certificate(&thin, &Plane::XY, 3e-6).is_none()); + assert!(cert(&thin, 3e-6).is_none()); } #[test] fn current_rational_circle_green_interval_encloses_independent_area() { let r = 6.; - let vertices = - [mt::Point3::new(r, 0., 0.), mt::Point3::new(0., r, 0.), mt::Point3::new(-r, 0., 0.), mt::Point3::new(0., -r, 0.)].map(builder::vertex); - let mut edges = Vec::new(); - for i in 0..4 { - let angle = (i as f64 + 0.5) * std::f64::consts::FRAC_PI_2; - edges.push(builder::circle_arc(&vertices[i], &vertices[(i + 1) % 4], mt::Point3::new(r * angle.cos(), r * angle.sin(), 0.))); - } - let wire: mt::Wire = edges.into(); - let cap = cap_loop(&wire, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); + let w = std::f64::consts::FRAC_1_SQRT_2; + let corner = |i: usize| { + let a = i as f64 * std::f64::consts::FRAC_PI_2; + Vec3::new(r * a.cos(), r * a.sin(), 0.) + }; + // Four quarter circles as rational quadratic splines. + let curves: Vec = (0..4) + .map(|i| { + let (a, b) = (corner(i), corner(i + 1)); + let apex = a + b; + Curve::RationalSpline { + knots: vec![0., 0., 0., 1., 1., 1.], + homogeneous: vec![[a.x, a.y, 0., 1.], [apex.x * w, apex.y * w, 0., w], [b.x, b.y, 0., 1.]], + } + }) + .collect(); + let runs: Vec<(usize, Run)> = curves + .iter() + .enumerate() + .map(|(i, c)| (i, Run { curve: c, interval: [0., 1.], forward: true, ends: [corner(i), corner(i + 1)] })) + .collect(); + let cap = cap_loop(&runs, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); let exact = std::f64::consts::PI * r * r; assert!(cap.area.lo <= exact && cap.area.hi >= exact, "{:?}", cap.area); assert!((cap.area.hi - cap.area.lo) * 10. < 0.001); assert_eq!(cap.segments.len(), 4); - let reversed = cap_loop(&wire.inverse(), &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); + let back: Vec<(usize, Run)> = + runs.iter().rev().map(|(i, run)| (*i, Run { forward: false, ends: [run.ends[1], run.ends[0]], ..*run })).collect(); + let reversed = cap_loop(&back, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(); assert!(reversed.area.lo <= -exact && reversed.area.hi >= -exact); } }