diff --git a/crates/kernel/src/boolean_backend.rs b/crates/kernel/src/boolean_backend.rs new file mode 100644 index 000000000..9372e968e --- /dev/null +++ b/crates/kernel/src/boolean_backend.rs @@ -0,0 +1,110 @@ +//! Which kernel runs [`crate::boolean`]: truck (the default) or SMLib. +//! +//! The setting is the environment variable `SOLIDCRAFT_BOOLEANS`, read once per process: +//! `truck` (or unset) or `smlib`. SMLib needs a build with the kernel's `smlib` feature; set +//! without it, or set to anything else, every boolean fails with an error that says so rather +//! than quietly running truck, so a comparison run can never compare truck with itself. +//! +//! Through SMLib a boolean is: each operand's schema 4 record built in SMLib and tagged as +//! operand 0 or 1, `SmBrep` boolean, the result exported to schema 4 and decoded as a kernel +//! body. The result's history is SMLib's own (its tags carried through the operation), +//! renumbered from SMLib's face and edge order into the operands' and the result's ([`History`]'s +//! contract). A result SMLib's own check or the record's geometry check refuses is an error, +//! never a body. + +use crate::{KernelError, Result}; + +/// The environment variable that picks the boolean kernel. +pub const BOOLEANS_ENV: &str = "SOLIDCRAFT_BOOLEANS"; + +/// A kernel that runs booleans. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BooleanBackend { + Truck, + Smlib, +} + +impl BooleanBackend { + /// The backend a setting names; `None` (unset) is truck. + pub fn parse(setting: Option<&str>) -> std::result::Result { + match setting.map(str::trim) { + None | Some("") | Some("truck") => Ok(BooleanBackend::Truck), + Some("smlib") if cfg!(feature = "smlib") => Ok(BooleanBackend::Smlib), + Some("smlib") => Err(format!("{BOOLEANS_ENV}=smlib: not supported yet: this build has no SMLib (feature `smlib`)")), + Some(other) => Err(format!("{BOOLEANS_ENV}={other}: expected `truck` or `smlib`")), + } + } +} + +/// The boolean kernel this process uses ([`BOOLEANS_ENV`], read on first use). +pub fn boolean_backend() -> Result { + static SETTING: std::sync::OnceLock> = std::sync::OnceLock::new(); + SETTING.get_or_init(|| BooleanBackend::parse(std::env::var(BOOLEANS_ENV).ok().as_deref())).clone().map_err(KernelError::Invalid) +} + +#[cfg(feature = "smlib")] +pub(crate) use smlib::boolean as smlib_boolean; + +#[cfg(feature = "smlib")] +mod smlib { + use solidcraft_smlib::{BooleanOp, CheckLevel}; + + use crate::body::Body; + use crate::history::History; + use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; + use crate::ops::BoolOp; + use crate::{KernelError, Result, record}; + + fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { + KernelError::Failed(format!("SMLib boolean: {what}: {e}")) + } + + /// `a` and `b` combined by `op` in SMLib, with the history SMLib's tags give (none where a + /// body's face and edge order cannot be matched to SMLib's). `None`: the result is empty. + pub(crate) fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { + a.require_brep("a boolean")?; + b.require_brep("a boolean")?; + let (sa, oa) = smlib_body_ordered(a)?; + let (sb, ob) = smlib_body_ordered(b)?; + let ta = sa.tagged(0).map_err(|e| failed("tag", e))?; + let tb = sb.tagged(1).map_err(|e| failed("tag", e))?; + let kind = match op { + BoolOp::Union => BooleanOp::Union, + BoolOp::Cut => BooleanOp::Subtract, + BoolOp::Intersect => BooleanOp::Intersect, + }; + let Some(r) = ta.boolean(&tb, kind).map_err(|e| failed("operation", e))? else { return Ok(None) }; + let check = r.check(CheckLevel::All).map_err(|e| failed("check", e))?; + if !check.is_valid() { + return Err(failed("SMLib's check refuses the result", check)); + } + let (body, or) = body_from_smlib_ordered(&r)?; + let history = match (oa, ob, or) { + (Some(oa), Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[oa, ob], &or).map(Some).unwrap_or_else(|e| { + log::debug!(target: "smlib", "boolean history: {e}"); + None + }), + _ => None, + }; + Ok(Some(with_history(body, history, a, b))) + } + + /// `body` with `history` where it describes `body` made from `a` and `b`. + fn with_history(body: Body, history: Option, a: &Body, b: &Body) -> Body { + body.with_checked_history(history, &record::counts(&[a, b])) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_setting_names_a_backend_or_is_refused() { + assert_eq!(BooleanBackend::parse(None), Ok(BooleanBackend::Truck)); + assert_eq!(BooleanBackend::parse(Some("truck")), Ok(BooleanBackend::Truck)); + assert_eq!(BooleanBackend::parse(Some(" ")), Ok(BooleanBackend::Truck)); + assert_eq!(BooleanBackend::parse(Some("smlib")).is_ok(), cfg!(feature = "smlib")); + assert!(BooleanBackend::parse(Some("occt")).is_err()); + } +} diff --git a/crates/kernel/src/boolean_history_tests.rs b/crates/kernel/src/boolean_history_tests.rs index 33022a018..7635f2b42 100644 --- a/crates/kernel/src/boolean_history_tests.rs +++ b/crates/kernel/src/boolean_history_tests.rs @@ -525,3 +525,70 @@ fn stacked_pieces_of_one_cylinder_keep_their_walls() { } } } + +/// The same booleans through SMLib: its tags, renumbered into the operands' and the result's +/// face and edge order, give a history that holds against the geometry. +#[cfg(feature = "smlib")] +mod smlib { + use super::*; + use crate::boolean_backend::smlib_boolean; + + fn through_smlib(a: &Body, b: &Body, op: BoolOp) -> Body { + smlib_boolean(a, b, op).unwrap().expect("a result") + } + + #[test] + fn operands_number_as_their_records() { + let bodies = [ + boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0), + crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 12.0).unwrap(), + crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap(), + crate::torus(Vec3::new(0.0, 0.0, 0.0), 10.0, 2.0).unwrap(), + ]; + for (i, b) in bodies.iter().enumerate() { + let (_, order) = crate::native::smlib_body_ordered(b).unwrap(); + assert!(order.is_some(), "body {i}"); + } + } + + #[test] + fn box_minus_sphere() { + let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); + let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap(); + let r = through_smlib(&a, &b, BoolOp::Cut); + let h = verified(&r, &[&a, &b], 0.02); + // The three notched box faces, the three untouched, and the sphere's patches inside. + assert_eq!(changes(h)[..2].iter().sum::() + changes(h)[2], h.faces.len(), "{}", show(h)); + assert!( + meets(h).iter().all(|(x, y)| matches!((x, y), (FaceOrigin::Face { operand: 0, .. }, FaceOrigin::Face { operand: 1, .. }))), + "{}", + show(h) + ); + } + + #[test] + fn box_minus_cylinder() { + let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); + let b = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 12.0).unwrap(); + let r = through_smlib(&a, &b, BoolOp::Cut); + let h = verified(&r, &[&a, &b], 0.01); + assert!(from(h, face(0, 0)).len() + from(h, face(0, 1)).len() >= 1, "{}", show(h)); + } + + #[test] + fn box_union_box() { + let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); + let b = boxed(5.0, 2.0, 2.0, 15.0, 8.0, 8.0); + let r = through_smlib(&a, &b, BoolOp::Union); + let h = verified(&r, &[&a, &b], 0.02); + assert_eq!(h.faces.len(), 11, "{}", show(h)); + assert_eq!(meets(h).len(), 4, "{}", show(h)); + } + + #[test] + fn disjoint_intersection_is_empty() { + let a = boxed(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + let b = boxed(5.0, 5.0, 5.0, 6.0, 6.0, 6.0); + assert!(smlib_boolean(&a, &b, BoolOp::Intersect).unwrap().is_none()); + } +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index d044900b1..8e0921db7 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -20,6 +20,7 @@ mod blend_vertex; #[cfg(test)] mod blend_wrong_way_tests; mod body; +mod boolean_backend; mod boolean_diagnostics; mod boolean_guard; mod boolean_record; @@ -160,6 +161,7 @@ pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet pub use blend_corner::fillet_radii; pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper}; pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, Paint}; +pub use boolean_backend::{BOOLEANS_ENV, BooleanBackend, boolean_backend}; pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics}; pub use boundary::{Boundary, boundary_patch}; pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDGE_PICKS, boundary_join, boundary_surface}; diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index ac6da1ecc..239b58be9 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -157,8 +157,64 @@ pub fn decode_native_body(bytes: &[u8]) -> Result { /// says (`Body::oriented`), never by meshing it. #[cfg(feature = "smlib")] pub fn body_from_smlib(brep: &solidcraft_smlib::Brep) -> Result { - let record = brep.to_native().map_err(|e| KernelError::Failed(e.to_string()))?; - guard("decode SMLib B-rep", || Body::oriented(adapter::decode_from(record, adapter::Producer::Foreign)?)) + body_from_smlib_ordered(brep).map(|(body, _)| body) +} + +/// [`body_from_smlib`], with where each of SMLib's faces and edges is in the body's face and +/// edge order ([`crate::history`]): `None` where the body did not keep the record's order (a +/// rebuild that walked a face's edges the other way). +#[cfg(feature = "smlib")] +pub(crate) fn body_from_smlib_ordered(brep: &solidcraft_smlib::Brep) -> Result<(Body, Option)> { + let (record, order) = brep.to_native_ordered().map_err(|e| KernelError::Failed(e.to_string()))?; + guard("decode SMLib B-rep", || { + let (solid, numbering) = adapter::decode_numbered(record, adapter::Producer::Foreign)?; + let body = Body::oriented(solid)?; + let kept = numbering.kept_by(&body.solid); + Ok((body, kept.then_some(order))) + }) +} + +/// `body` in SMLib ([`smlib_body`]), with where each of SMLib's faces and edges is in the body's +/// face and edge order: SMLib's export of the imported body, checked to number every face, +/// edge and vertex as the body's record does. `None` where it does not. +#[cfg(feature = "smlib")] +pub(crate) fn smlib_body_ordered(body: &Body) -> Result<(solidcraft_smlib::Brep, Option)> { + let record = brep_record(body)?; + let brep = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| KernelError::Failed(format!("SMLib: {e}")))?; + let order = match brep.to_native_ordered() { + Ok((back, order)) => same_numbering(&record, &back).then_some(order), + Err(e) => { + log::debug!(target: "smlib", "no order for an operand: {e}"); + None + } + }; + Ok((brep, order)) +} + +/// Whether two records of one body number its faces, edges and vertices alike: the same loops of +/// the same edges, the same edge ends, and each vertex where the other's is. +#[cfg(feature = "smlib")] +fn same_numbering(a: &solidcraft_geom::brep::Brep, b: &solidcraft_geom::brep::Brep) -> bool { + use solidcraft_geom::brep::Loop; + if a.faces.len() != b.faces.len() || a.edges.len() != b.edges.len() || a.vertices.len() != b.vertices.len() { + return false; + } + let loops_alike = a.faces.iter().zip(&b.faces).all(|(fa, fb)| { + fa.loops.len() == fb.loops.len() + && fa.loops.iter().zip(&fb.loops).all(|pair| match pair { + (Loop::Edges { edges: x }, Loop::Edges { edges: y }) => { + x.len() == y.len() && x.iter().zip(y).all(|(u, w)| u.edge == w.edge && u.forward == w.forward) + } + (Loop::Vertex { vertex: x }, Loop::Vertex { vertex: y }) => x == y, + _ => false, + }) + }); + let ends_alike = a.edges.iter().zip(&b.edges).all(|(x, y)| x.vertices == y.vertices); + let at_same_place = a.vertices.iter().zip(&b.vertices).all(|(x, y)| { + let d = (0..3).map(|k| (x.point[k] - y.point[k]).powi(2)).sum::().sqrt(); + d <= x.tolerance + y.tolerance + a.tolerance + b.tolerance + }); + loops_alike && ends_alike && at_same_place } fn validate_topology(saved: &SavedBody) -> Result<()> { diff --git a/crates/kernel/src/native/adapter.rs b/crates/kernel/src/native/adapter.rs index 3caadce78..55971cd1e 100644 --- a/crates/kernel/src/native/adapter.rs +++ b/crates/kernel/src/native/adapter.rs @@ -330,6 +330,35 @@ pub(super) fn decode(body: b::Brep) -> Result { } pub(super) fn decode_from(body: b::Brep, producer: Producer) -> Result { + decode_numbered(body, producer).map(|(solid, _)| solid) +} + +/// The identities of a decoded record's faces and edges, by record index: each face's +/// identity and those of the edges bounding it (a face rebuilt on the same boundary, as +/// `Body::oriented` rephases a revolution, keeps those). +#[cfg_attr(not(feature = "smlib"), allow(dead_code))] +pub(super) struct Numbering { + pub faces: Vec<(mt::FaceID, std::collections::HashSet)>, + pub edges: Vec, +} + +#[cfg_attr(not(feature = "smlib"), allow(dead_code))] +impl Numbering { + /// Whether `solid` lists its faces and edges in the record's order. + pub fn kept_by(&self, solid: &mt::Solid) -> bool { + let faces_kept = solid.face_iter().count() == self.faces.len() + && solid + .face_iter() + .zip(&self.faces) + .all(|(f, (id, edges))| f.id() == *id || f.edge_iter().map(|e| e.id()).collect::>() == *edges); + faces_kept && crate::body::edge_order(solid.face_iter()).0.iter().map(|e| e.id()).eq(self.edges.iter().copied()) + } +} + +/// [`decode_from`], with each record face's and edge's identity in the solid: a caller holding +/// indices into the record (an SMLib history) checks with them that the solid's face and edge +/// order is the record's. +pub(super) fn decode_numbered(body: b::Brep, producer: Producer) -> Result<(mt::Solid, Numbering)> { body.validate().map_err(invalid)?; body.check_geometry().map_err(invalid)?; compatible(&body, producer)?; @@ -340,6 +369,7 @@ pub(super) fn decode_from(body: b::Brep, producer: Producer) -> Result>>()?; + let mut face_ids: Vec)>> = vec![None; faces.len()]; let mut faces: Vec> = faces.into_iter().map(Some).collect(); let shells = shells .into_iter() @@ -349,7 +379,11 @@ pub(super) fn decode_from(body: b::Brep, producer: Producer) -> Result>(), b::Shell::Faces { .. } => Err(unsupported("wire edges embedded in a shell")), @@ -359,7 +393,9 @@ pub(super) fn decode_from(body: b::Brep, producer: Producer) -> Result>>().ok_or_else(|| invalid("a face no shell uses"))?; + let numbering = Numbering { faces, edges: edges.iter().map(mt::Edge::id).collect() }; + Ok((mt::Solid::new_unchecked(shells), numbering)) } /// A face's topology as recorded, references already checked: built as the kernel built it, /// without truck's checks for wires that touch themselves (a seam edge used twice, a closed edge diff --git a/crates/kernel/src/native/smlib_import_tests.rs b/crates/kernel/src/native/smlib_import_tests.rs index 0443c3531..d34f3acaf 100644 --- a/crates/kernel/src/native/smlib_import_tests.rs +++ b/crates/kernel/src/native/smlib_import_tests.rs @@ -27,14 +27,37 @@ fn primitives_keep_their_analytic_volume() { assert!(solid && (got - 28.0 * PI).abs() <= 1e-6 * 28.0 * PI, "tilted cylinder: SMLib volume {got}, manifold {solid}"); } -/// Truck holds spheres and tori as revolutions (`PlacedRevolution`); they go to SMLib as their -/// exact rational B-spline surfaces. +/// Truck holds spheres and tori as revolutions (`PlacedRevolution`): SMLib gets them as its +/// analytic sphere and torus, faces turned over where the revolution's normal points inward. #[test] fn revolutions_keep_their_analytic_volume() { - let (got, solid) = in_smlib(&sphere(v(1., 2., 3.), 5.0).unwrap()).unwrap(); - let ball = 4.0 / 3.0 * PI * 125.0; - assert!(solid && (got - ball).abs() <= 1e-6 * ball, "sphere: SMLib volume {got}, manifold {solid}"); - let (got, solid) = in_smlib(&torus(v(0., 0., 0.), 10.0, 2.0).unwrap()).unwrap(); - let ring = 2.0 * PI * PI * 10.0 * 4.0; - assert!(solid && (got - ring).abs() <= 1e-6 * ring, "torus: SMLib volume {got}, manifold {solid}"); + let cases = [ + ("sphere", sphere(v(1., 2., 3.), 5.0).unwrap(), 4.0 / 3.0 * PI * 125.0), + ("torus", torus(v(0., 0., 0.), 10.0, 2.0).unwrap(), 2.0 * PI * PI * 10.0 * 4.0), + ]; + for (name, body, exact) in cases { + let s = super::smlib_body(&body).unwrap_or_else(|e| panic!("{name}: {e}")); + let check = s.check(solidcraft_smlib::CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{name}: {check}"); + let got = s.volume(1e-7).unwrap(); + assert!(s.is_manifold_solid().unwrap_or(false) && (got - exact).abs() <= 1e-6 * exact, "{name}: SMLib volume {got}, exact {exact}"); + } +} + +/// A body SMLib made (analytic faces) comes back from truck as revolutions, and goes into SMLib +/// again as the same analytic faces: a second boolean on a first one's result. +#[test] +fn smlib_results_go_back_into_smlib() { + for (name, body, exact) in [ + ("cylinder", cylinder(v(1., 2., 3.), v(0., 0., 1.), 5.0, 10.0).unwrap(), 250.0 * PI), + ("sphere", sphere(v(0., 0., 0.), 3.0).unwrap(), 36.0 * PI), + ] { + let first = super::smlib_body(&body).unwrap(); + let back = super::body_from_smlib(&first).unwrap_or_else(|e| panic!("{name}: {e}")); + let again = super::smlib_body(&back).unwrap_or_else(|e| panic!("{name}: {e}")); + let check = again.check(solidcraft_smlib::CheckLevel::All).unwrap(); + assert!(check.is_valid(), "{name}: {check}"); + let got = again.volume(1e-7).unwrap(); + assert!((got - exact).abs() <= 1e-6 * exact, "{name}: SMLib volume {got}, exact {exact}"); + } } diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index ba88d5fce..0df1d9503 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -917,8 +917,38 @@ fn take_attempt() -> bool { /// /// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`, /// whichever way it was made, or none where a step it took does not report one. +/// +/// Truck runs it unless [`crate::BOOLEANS_ENV`] picks SMLib ([`crate::boolean_backend`]). pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { - crate::profile::timed(crate::profile::Kind::Boolean, || boolean_untimed(a, b, op)) + crate::profile::timed(crate::profile::Kind::Boolean, || match crate::boolean_backend()? { + crate::BooleanBackend::Truck => boolean_untimed(a, b, op), + crate::BooleanBackend::Smlib => smlib_boolean(a, b, op), + }) +} + +/// [`boolean`] through SMLib, its result given the operands' roles as truck's is. +#[cfg(feature = "smlib")] +fn smlib_boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { + let r = guard("SMLib boolean", || crate::boolean_backend::smlib_boolean(a, b, op)); + with_operand_roles(a, b, op, r) +} + +#[cfg(not(feature = "smlib"))] +fn smlib_boolean(_: &Body, _: &Body, _: BoolOp) -> Result> { + Err(KernelError::Invalid("not supported yet: this build has no SMLib".into())) +} + +/// A boolean's result with what its operands' faces stood for carried over: regularization +/// protection and the planar construction and shell roles on supports it kept. +fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result>) -> Result> { + let r = r.map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b))); + match op { + BoolOp::Cut => r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()), + BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), + // Every face of an intersection lies on one operand's face, as a union's does: the same + // roles carry over (#565). + BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), + } } fn boolean_untimed(a: &Body, b: &Body, op: BoolOp) -> Result> { @@ -1012,7 +1042,7 @@ fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, Bool )), }; } - r = finished(a, b, op, r); + r = with_operand_roles(a, b, op, r); // A retry's result is held to what the operation can do at all; one that fails is refused // rather than returned wrong (issue #616). if (!diagnostics.events.is_empty() || diagnostics.truncated) diff --git a/crates/smlib/src/export.rs b/crates/smlib/src/export.rs index 38e3700da..e542dec2c 100644 --- a/crates/smlib/src/export.rs +++ b/crates/smlib/src/export.rs @@ -34,6 +34,7 @@ use solidcraft_geom::Vec3; use solidcraft_geom::brep as b; use crate::flat::{self, *}; +use crate::history::Order; use crate::import::Arrays; use crate::{Brep, Result, error, ffi, init}; @@ -86,6 +87,15 @@ impl Brep { let arrays = self.arrays().map_err(ExportError::Smlib)?; native(&arrays) } + + /// [`Brep::to_native`], with where each of SMLib's faces and edges went in the record's + /// canonical order: what [`crate::history::Raw::history`] renumbers this body's history with. + /// SMLib's export lists faces and edges in the body's own order (`SmBrep::GetFaces`, + /// `GetEdges`), the order its history uses. + pub fn to_native_ordered(&self) -> std::result::Result<(b::Brep, Order), ExportError> { + let arrays = self.arrays().map_err(ExportError::Smlib)?; + native_ordered(&arrays).map(|(brep, _, order)| (brep, order)) + } } /// What the mapping could not put in its own kind, or turned. @@ -576,6 +586,11 @@ struct Edge { /// The schema 4 B-rep of SMLib's flat arrays: mapped, renumbered canonically and validated. pub fn native(arrays: &Arrays) -> Res<(b::Brep, Report)> { + native_ordered(arrays).map(|(brep, report, _)| (brep, report)) +} + +/// [`native`], with the canonical place of each array face and edge. +fn native_ordered(arrays: &Arrays) -> Res<(b::Brep, Report, Order)> { let flat = View(arrays); let mut report = Report::default(); if arrays.ints.values().map(Vec::len).chain(arrays.reals.values().map(Vec::len)).any(|n| n > flat::MAX_LEN) { @@ -787,7 +802,7 @@ pub fn native(arrays: &Arrays) -> Res<(b::Brep, Report)> { } let shells: Vec> = order.iter().filter_map(|s| shells.get(*s as usize).cloned()).collect(); - canonical(Parts { faces, edges, shells, regions }, n_vertices, flat, tolerance).map(|brep| (brep, report)) + canonical(Parts { faces, edges, shells, regions }, n_vertices, flat, tolerance).map(|(brep, order)| (brep, report, order)) } /// The mapped records before renumbering. @@ -800,8 +815,9 @@ struct Parts { /// The record in canonical order: faces in first appearance through the shells, edges through /// the faces (a face whose first oriented face is reversed walked backwards), vertices through -/// the edges and then the vertex loops, with each face's pcurves; validated. -fn canonical(parts: Parts, n_vertices: usize, flat: View, tolerance: f64) -> Res { +/// the edges and then the vertex loops, with each face's pcurves; validated. With it, the +/// canonical index of each array face and edge. +fn canonical(parts: Parts, n_vertices: usize, flat: View, tolerance: f64) -> Res<(b::Brep, Order)> { let Parts { faces, edges, shells, regions } = parts; let mut face_new: Vec> = vec![None; faces.len()]; let (mut face_order, mut direction) = (Vec::new(), Vec::new()); @@ -933,7 +949,11 @@ fn canonical(parts: Parts, n_vertices: usize, flat: View, tolerance: f64) -> Res .collect::>>()?; let brep = b::Brep { version: b::VERSION, tolerance, regions, shells, faces: face_records, edges: edge_records, vertices }; brep.validate().map_err(|e| invalid(format!("the mapped B-rep does not validate: {e}")))?; - Ok(brep) + let placed = |new: &[Option]| { + new.iter().map(|i| i.map(|i| i as usize).ok_or_else(|| invalid("an entity outside the canonical walk"))).collect::>>() + }; + let order = Order { faces: placed(&face_new)?, edges: placed(&edge_new)? }; + Ok((brep, order)) } /// A face's pcurves, edge loop by edge loop, from the plain-record routine on the face's diff --git a/crates/smlib/src/export/tests.rs b/crates/smlib/src/export/tests.rs index bc3114535..e48c29c32 100644 --- a/crates/smlib/src/export/tests.rs +++ b/crates/smlib/src/export/tests.rs @@ -58,6 +58,29 @@ mod native_tests { } } + /// A tagged body's own history, renumbered with its export's order on both sides, is the + /// identity in canonical order: the order says where each SMLib face and edge went. + #[test] + fn the_export_order_renumbers_a_history_into_the_record() { + for (name, s, _) in primitives() { + let t = s.tagged(0).unwrap(); + let (record, order) = t.to_native_ordered().unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!((order.faces.len(), order.edges.len()), (record.faces.len(), record.edges.len()), "{name}"); + let h = t.history().unwrap().history(std::slice::from_ref(&order), &order).unwrap(); + for (i, f) in h.faces.iter().enumerate() { + assert_eq!(f.origins, vec![solidcraft_geom::brep::history::FaceOrigin::Face { operand: 0, face: i }], "{name}: face {i}"); + } + for (i, e) in h.edges.iter().enumerate() { + assert_eq!(e.origins, vec![solidcraft_geom::brep::history::EdgeOrigin::Edge { operand: 0, edge: i }], "{name}: edge {i}"); + // The faces it bounds, as the record's uses say. + let mut faces: Vec = record.edges[i].uses.iter().map(|u| u.face as usize).collect(); + faces.sort(); + faces.dedup(); + assert_eq!(e.faces, faces, "{name}: edge {i}"); + } + } + } + #[test] fn recognised_edges_are_on_smlibs_curves() { let cyl = Brep::make_cylinder([0.0; 3], 5.0, 10.0).unwrap().to_native().unwrap(); diff --git a/crates/smlib/src/import.rs b/crates/smlib/src/import.rs index c8e103949..1a2a97425 100644 --- a/crates/smlib/src/import.rs +++ b/crates/smlib/src/import.rs @@ -84,6 +84,8 @@ fn z_axis(f: &b::Frame) -> [f64; 3] { /// rules (SMLib then skips its healer); otherwise SMLib heals it on import. pub fn arrays(brep: &b::Brep, trusted: bool) -> R { brep.validate().map_err(|e| Unsupported::Invalid(e.0))?; + let brep = revolved::analytic(brep)?; + let brep = brep.as_ref(); let mut a = Arrays::default(); // Regions and shells. Each region gets its own copy of each shell it lists. @@ -481,6 +483,8 @@ fn curve(a: &mut Arrays, c: &b::Curve) -> R<()> { Ok(()) } +mod revolved; + #[cfg(test)] mod tests; diff --git a/crates/smlib/src/import/revolved.rs b/crates/smlib/src/import/revolved.rs new file mode 100644 index 000000000..917a00cf7 --- /dev/null +++ b/crates/smlib/src/import/revolved.rs @@ -0,0 +1,368 @@ +//! Revolutions as SMLib's analytic surfaces. A `placed_revolution` record holds a surface the +//! way truck does (a profile turned about an axis, then placed); SMLib has no such surface, but +//! every one truck makes for a cylinder, cone, sphere or torus is one of those exactly: a line +//! along the axis, a line in a plane through it, a circle centred on it, a circle in a plane +//! through it. Each such face becomes that analytic surface, its range mapped from the +//! revolution's parameters, and checked point by point over the face's range; where the +//! analytic surface's natural normal is the other way round, the face is turned over (its loops +//! reversed, its uses in the shells flipped), which leaves the solid as it was. +//! +//! A revolution of any other profile, or one placed by a matrix that is not a rigid motion, is +//! refused. + +use std::borrow::Cow; +use std::f64::consts::{FRAC_PI_2, TAU}; + +use solidcraft_geom::Vec3; +use solidcraft_geom::brep as b; +use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; + +use super::{R, Unsupported}; + +const NOT_ANALYTIC: Unsupported = Unsupported::NotYet("revolved surfaces other than cylinders, cones, spheres and tori"); + +/// `brep` with every revolution replaced by its analytic surface (borrowed when it has none). +pub(super) fn analytic(brep: &b::Brep) -> R> { + if !brep.faces.iter().any(|f| matches!(f.surface, b::Surface::PlacedRevolution { .. })) { + return Ok(Cow::Borrowed(brep)); + } + let mut out = brep.clone(); + let size = extent(brep); + let mut turned = Vec::new(); + for (i, f) in out.faces.iter_mut().enumerate() { + let b::Surface::PlacedRevolution { profile, origin, axis, matrix, forward } = &f.surface else { continue }; + let rev = Revolution::new(profile, *origin, *axis, matrix, *forward)?; + let (surface, mut domain, v) = rev.analytic(f.domain)?; + // Angles start within the first turn, where SMLib's degree domains are at home. + domain[0] = first_turn(domain[0]); + if matches!(surface, b::Surface::Torus { .. }) { + domain[1] = first_turn(domain[1]); + } + let flip = agree(&f.surface, f.domain, &surface, domain, &rev, &v, brep.tolerance.max(1e-9 * size))?; + f.surface = surface; + f.domain = domain; + if flip { + turned.push(i); + } + } + for i in turned { + turn_over(&mut out, i)?; + } + Ok(Cow::Owned(out)) +} + +/// An angle range moved by whole turns to start in [0, 2π). +fn first_turn([a, z]: [f64; 2]) -> [f64; 2] { + let shift = (a / TAU).floor() * TAU; + [a - shift, z - shift] +} + +/// The body's size from its vertices (1 where it has none). +fn extent(brep: &b::Brep) -> f64 { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for v in &brep.vertices { + for k in 0..3 { + lo[k] = lo[k].min(v.point[k]); + hi[k] = hi[k].max(v.point[k]); + } + } + let d = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::().sqrt(); + if d.is_finite() && d > 0.0 { d } else { 1.0 } +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} +fn arr(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +/// A revolution in world space: its profile placed, its axis placed, the turning sense. +struct Revolution { + profile: CurveEval, + line: Option<[Vec3; 2]>, + /// A point on the axis and the axis, oriented so that the revolution's angle turns about it + /// by the right-hand rule. + o: Vec3, + z: Vec3, + /// The record's (u, v) is (profile, angle). + forward: bool, +} + +impl Revolution { + fn new(profile: &b::Curve, origin: [f64; 3], axis: [f64; 3], m: &[[f64; 4]; 4], forward: bool) -> R { + // Column-major: m[column][row]. A rigid motion only (a mirror reverses the turning). + let col = |c: usize| Vec3::new(m[c][0], m[c][1], m[c][2]); + let (c0, c1, c2, t) = (col(0), col(1), col(2), col(3)); + let unit = |v: Vec3| (v.len() - 1.0).abs() <= 1e-9; + if !(m[0][3] == 0.0 && m[1][3] == 0.0 && m[2][3] == 0.0 && m[3][3] == 1.0) + || !(unit(c0) && unit(c1) && unit(c2)) + || c0.dot(c1).abs() > 1e-9 + || c0.dot(c2).abs() > 1e-9 + || c1.dot(c2).abs() > 1e-9 + { + return Err(Unsupported::NotYet("revolved surfaces placed by a matrix that is no rigid motion")); + } + let det = c0.dot(c1.cross(c2)); + let place = |p: Vec3| c0 * p.x + c1 * p.y + c2 * p.z + t; + let turn = |d: Vec3| c0 * d.x + c1 * d.y + c2 * d.z; + let z = turn(v3(axis)).normalized().ok_or(Unsupported::Invalid("revolution axis"))? * det.signum(); + let placed_curve = |c: &b::Curve| -> R { + let p = |q: [f64; 3]| arr(place(v3(q))); + Ok(match c { + b::Curve::Line { start, end } => b::Curve::Line { start: p(*start), end: p(*end) }, + b::Curve::Circle { frame, radius } => b::Curve::Circle { + frame: b::Frame { origin: p(frame.origin), x_axis: arr(turn(v3(frame.x_axis))), y_axis: arr(turn(v3(frame.y_axis))) }, + radius: *radius, + }, + b::Curve::Spline { knots, points } => b::Curve::Spline { knots: knots.clone(), points: points.iter().map(|q| p(*q)).collect() }, + b::Curve::RationalSpline { knots, homogeneous } => b::Curve::RationalSpline { + knots: knots.clone(), + homogeneous: homogeneous + .iter() + .map(|h| { + let w = h[3]; + let q = place(Vec3::new(h[0], h[1], h[2]) * (1.0 / w)); + [q.x * w, q.y * w, q.z * w, w] + }) + .collect(), + }, + _ => return Err(NOT_ANALYTIC), + }) + }; + let world = placed_curve(profile)?; + let line = match &world { + b::Curve::Line { start, end } => Some([v3(*start), v3(*end)]), + _ => None, + }; + let profile = CurveEval::new(&world).map_err(|_| Unsupported::Invalid("revolution profile"))?; + Ok(Revolution { profile, line, o: place(v3(origin)), z, forward }) + } + + /// The profile's parameter range and the angle range of a face's domain. + fn ranges(&self, domain: [[f64; 2]; 2]) -> ([f64; 2], [f64; 2]) { + if self.forward { (domain[0], domain[1]) } else { (domain[1], domain[0]) } + } + + /// `p` relative to the axis: its foot on the axis, its height along z and its radial part. + fn split(&self, p: Vec3) -> (Vec3, f64, Vec3) { + let h = (p - self.o).dot(self.z); + let foot = self.o + self.z * h; + (foot, h, p - foot) + } + + /// The analytic surface and the face's range on it: u the angle about z from the profile's + /// half-plane, v as the surface's kind has it. + fn analytic(&self, domain: [[f64; 2]; 2]) -> R<(b::Surface, [[f64; 2]; 2], V)> { + let (t, angle) = self.ranges(domain); + let at = |s: f64| self.profile.point(s).ok_or(Unsupported::Invalid("revolution profile")); + let samples: Vec = (0..=16).map(|i| at(t[0] + (t[1] - t[0]) * f64::from(i) / 16.0)).collect::>()?; + // The profile's half-plane: the radial direction of its point farthest from the axis. + let far = samples.iter().map(|p| self.split(*p).2).fold(Vec3::ZERO, |best, r| if r.len() > best.len() { r } else { best }); + let x = far.normalized().ok_or(NOT_ANALYTIC)?; + let y = self.z.cross(x); + let frame = |o: Vec3| b::Frame { origin: arr(o), x_axis: arr(x), y_axis: arr(y) }; + let sorted = |a: f64, b: f64| if a <= b { [a, b] } else { [b, a] }; + if let Some([s, e]) = self.line { + let d = e - s; + let len = d.len(); + if !(len > 0.0) { + return Err(NOT_ANALYTIC); + } + // In a plane through the axis: no component out of the (z, x) plane. + if (s - self.o).dot(y).abs() > 1e-9 * len.max(1.0) || d.dot(y).abs() > 1e-9 * len { + return Err(NOT_ANALYTIC); + } + let (foot, _, _) = self.split(s); + let height = |p: Vec3| (p - foot).dot(self.z); + let radial = |p: Vec3| (p - foot).dot(x); + let (h0, h1) = (height(at(t[0])?), height(at(t[1])?)); + let (dh, dr) = (d.dot(self.z), d.dot(x)); + if dh.abs() <= 1e-12 * len { + return Err(NOT_ANALYTIC); // a disc: a plane, which a revolution face never is in the kernel + } + let r0 = radial(s) - dr / dh * height(s); + let v = sorted(h0, h1); + if dr.abs() <= 1e-12 * len { + if !(r0 > 0.0) { + return Err(NOT_ANALYTIC); + } + return Ok((b::Surface::Cylinder { frame: frame(foot), radius: r0 }, [angle, v], V::Height { foot, z: self.z })); + } + // A cone on one side of its apex only. + let r = |h: f64| r0 + h * dr / dh; + if r(v[0]) < 0.0 || r(v[1]) < 0.0 { + return Err(NOT_ANALYTIC); + } + let cone = b::Surface::Cone { frame: frame(foot), radius_at_origin: r0, half_angle: (dr / dh).atan() }; + return Ok((cone, [angle, v], V::Height { foot, z: self.z })); + } + // A circular profile. + let (center, radius, normal) = circle(&self.profile, t).ok_or(NOT_ANALYTIC)?; + let slack = 1e-9 * radius.max(1.0); + if normal.dot(self.z).abs() > 1e-9 || normal.dot(x).abs() > 1e-9 || (center - self.o).dot(y).abs() > slack { + return Err(NOT_ANALYTIC); + } + let (foot, _, off) = self.split(center); + // The meridian angle of each sample about the circle's centre in the (x, z) plane, unwrapped. + let meridian = |p: Vec3| { + let q = p - center; + q.dot(self.z).atan2(q.dot(x)) + }; + let mut angles = Vec::with_capacity(samples.len()); + for p in &samples { + let mut a = meridian(*p); + if let Some(prev) = angles.last().copied() { + while a - prev > std::f64::consts::PI { + a -= TAU; + } + while a - prev < -std::f64::consts::PI { + a += TAU; + } + } + angles.push(a); + } + let (first, last) = (angles.first().copied().ok_or(NOT_ANALYTIC)?, angles.last().copied().ok_or(NOT_ANALYTIC)?); + if off.len() <= slack { + // A sphere: the latitude is the meridian angle, within the half-plane's [-π/2, π/2]. + let v = sorted(first, last); + if v[0] < -FRAC_PI_2 - 1e-9 || v[1] > FRAC_PI_2 + 1e-9 { + return Err(NOT_ANALYTIC); + } + let v = [v[0].max(-FRAC_PI_2), v[1].min(FRAC_PI_2)]; + return Ok((b::Surface::Sphere { frame: frame(foot), radius }, [angle, v], V::Angle { center, x, z: self.z })); + } + let major = off.dot(x); + if !(major > radius) { + return Err(NOT_ANALYTIC); + } + let torus = b::Surface::Torus { frame: frame(foot), major_radius: major, minor_radius: radius }; + Ok((torus, [angle, sorted(first, last)], V::Angle { center, x, z: self.z })) + } + + /// The analytic (u, v) of the record's (u, v): the angle is the revolution's own, v that of + /// the profile's point (at angle 0), unwrapped to within half a turn of `near`. + fn map(&self, v: &V, uv: [f64; 2], near: f64) -> Option<[f64; 2]> { + let (t, angle) = if self.forward { (uv[0], uv[1]) } else { (uv[1], uv[0]) }; + let p = self.profile.point(t)?; + Some([angle, v.of(p, near)]) + } +} + +/// How the analytic v of a profile point is found. +enum V { + /// Height along `z` above `foot` (cylinder, cone). + Height { foot: Vec3, z: Vec3 }, + /// The angle about `center` from `x` towards `z` (sphere latitude, torus meridian). + Angle { center: Vec3, x: Vec3, z: Vec3 }, +} + +impl V { + fn of(&self, p: Vec3, near: f64) -> f64 { + match self { + V::Height { foot, z } => (p - *foot).dot(*z), + V::Angle { center, x, z } => { + let q = p - *center; + let mut a = q.dot(*z).atan2(q.dot(*x)); + while a - near > std::f64::consts::PI { + a -= TAU; + } + while a - near < -std::f64::consts::PI { + a += TAU; + } + a + } + } + } +} + +/// Checks the analytic surface against the revolution over the face's range, 5 × 5 points +/// within `tol`, and says whether their natural normals are opposite (the face must be turned +/// over), read at the range's middle. +fn agree(record: &b::Surface, domain: [[f64; 2]; 2], analytic: &b::Surface, range: [[f64; 2]; 2], rev: &Revolution, v: &V, tol: f64) -> R { + let bad = Unsupported::Invalid("a revolution its analytic surface does not match"); + let s = SurfaceEval::new(record).map_err(|_| bad.clone())?; + let a = SurfaceEval::new(analytic).map_err(|_| bad.clone())?; + let [[u0, u1], [v0, v1]] = domain; + let near = 0.5 * (range[1][0] + range[1][1]); + let normals = |u: f64, w: f64| -> R { + let (p, du, dv) = s.derivs(u, w).ok_or(bad.clone())?; + let uv = rev.map(v, [u, w], near).ok_or(bad.clone())?; + let (q, au, av) = a.derivs(uv[0], uv[1]).ok_or(bad.clone())?; + if !((p - q).len() <= tol) { + return Err(bad.clone()); + } + Ok(du.cross(dv).dot(au.cross(av))) + }; + for i in 0..=4 { + for j in 0..=4 { + normals(u0 + (u1 - u0) * f64::from(i) / 4.0, v0 + (v1 - v0) * f64::from(j) / 4.0)?; + } + } + let d = normals(0.5 * (u0 + u1), 0.5 * (v0 + v1))?; + if !(d.abs() > 0.0) { + return Err(bad); + } + Ok(d < 0.0) +} + +/// The circle a curve runs along over `t`: centre, radius and unit normal (its turning sense), +/// checked at 65 points within 10⁻⁹ of the radius (at least 1 mm). +fn circle(c: &CurveEval, t: [f64; 2]) -> Option<(Vec3, f64, Vec3)> { + let at = |s: f64| c.point(t[0] + (t[1] - t[0]) * s); + let (p, q, r) = (at(0.0)?, at(1.0 / 3.0)?, at(2.0 / 3.0)?); + let (u, w) = (q - p, r - p); + let normal = u.cross(w); + let nn = normal.dot(normal); + if !(nn > 0.0) { + return None; + } + let center = p + (normal.cross(u) * w.dot(w) + w.cross(normal) * u.dot(u)) * (0.5 / nn); + let radius = (p - center).len(); + let k = normal.normalized()?; + let slack = 1e-9 * radius.max(1.0); + for i in 0..=64 { + let s = at(f64::from(i) / 64.0)?; + if ((s - center).len() - radius).abs() > slack || (s - center).dot(k).abs() > slack { + return None; + } + } + Some((center, radius, k)) +} + +/// Face `face` turned over: its loops run the other way, each use of it in a shell flips, and +/// each of its edges' uses names its new place. The solid is unchanged. +fn turn_over(brep: &mut b::Brep, face: usize) -> R<()> { + use std::collections::HashMap; + let index = |x: usize| u32::try_from(x).map_err(|_| Unsupported::Invalid("index")); + let fi = index(face)?; + let f = brep.faces.get_mut(face).ok_or(Unsupported::Invalid("face"))?; + // (loop, old position) -> (new position, the use's new direction). + let mut moved: HashMap<(u32, u32), (u32, bool)> = HashMap::new(); + for (li, l) in f.loops.iter_mut().enumerate() { + if let b::Loop::Edges { edges } = l { + let n = edges.len(); + edges.reverse(); + for (p, e) in edges.iter_mut().enumerate() { + e.forward = !e.forward; + moved.insert((index(li)?, index(n - 1 - p)?), (index(p)?, e.forward)); + } + } + } + for e in &mut brep.edges { + for u in e.uses.iter_mut().filter(|u| u.face == fi) { + let &(position, forward) = moved.get(&(u.r#loop, u.position)).ok_or(Unsupported::Invalid("edge use"))?; + u.position = position; + u.upper = !forward; + } + } + for s in &mut brep.shells { + if let b::Shell::Faces { faces, .. } = s { + for o in faces.iter_mut().filter(|o| o.face == fi) { + o.forward = !o.forward; + } + } + } + Ok(()) +}