diff --git a/apps/solidcraft-cli/src/kernel_cases.rs b/apps/solidcraft-cli/src/kernel_cases.rs index 4cf618080..01bac57bd 100644 --- a/apps/solidcraft-cli/src/kernel_cases.rs +++ b/apps/solidcraft-cli/src/kernel_cases.rs @@ -668,7 +668,9 @@ fn check_case(dir: &str, dumps: Option<&std::path::Path>, validation: solidcraft return out; } }; - if !solidcraft_engine::kernel::smlib_built() { + // The C++ kernel is needed only if a family is routed to it. + let route = solidcraft_engine::kernel::kernel_route::Op::ALL; + if !solidcraft_engine::kernel::smlib_built() && route.iter().any(|op| op.backend() == solidcraft_engine::kernel::kernel_route::Backend::Smlib) { out["status"] = json!("unsupported"); out["error"] = json!("this build has no SMLib: build solidcraft-cli with --features smlib"); return out; diff --git a/crates/engine/src/schema/diagnostics_tests.rs b/crates/engine/src/schema/diagnostics_tests.rs index f568cc59a..ce00eee48 100644 --- a/crates/engine/src/schema/diagnostics_tests.rs +++ b/crates/engine/src/schema/diagnostics_tests.rs @@ -108,10 +108,8 @@ fn diagnostics_kernel_reports_and_sets_the_choice() { assert_eq!(r["overrides"], serde_json::Value::Object(moved), "{r}"); for choice in ["solidcore", "smlib", "routed"] { let c = route::Choice::from_id(choice).unwrap(); - // `.smb` files stay on SMLib whatever is chosen. for op in route::Op::ALL { let want = match choice { - _ if op == route::Op::File => "smlib", "routed" => op.route().id(), other => other, }; diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rs index f71e3366b..ef94142e2 100644 --- a/crates/kernel/src/prism.rs +++ b/crates/kernel/src/prism.rs @@ -108,7 +108,6 @@ struct Regions { touching: bool, } -#[cfg(feature = "smlib")] mod sheets { use solidcraft_geom::Loop2; use solidcraft_geom::Vec3; @@ -289,30 +288,6 @@ mod sheets { } } -#[cfg(not(feature = "smlib"))] -mod sheets { - use super::*; - - fn refused() -> Result { - Err(KernelError::Failed("not supported yet: planar region booleans run on SMLib (build with the feature `smlib`)".into())) - } - - /// A sheet stands for nothing without SMLib. - pub(super) enum Sheet {} - - pub(super) fn sheet(_: &[Region2], _: f64) -> Result { - refused() - } - - pub(super) fn combine(a: &Sheet, _: &Sheet, _: BoolOp) -> Result> { - match *a {} - } - - pub(super) fn regions(sheet: &Sheet, _: f64) -> Result { - match *sheet {} - } -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::panic)] mod planar_tests { diff --git a/crates/smlib/src/check.rs b/crates/smlib/src/check.rs index fd714ee58..abe93842a 100644 --- a/crates/smlib/src/check.rs +++ b/crates/smlib/src/check.rs @@ -105,6 +105,7 @@ mod tests { #[test] fn a_copy_and_a_native_file_round_trip_stay_valid() { + let _cpp = crate::route::on_cpp(); let b = Brep::make_box([0.0; 3], [2.0, 3.0, 4.0]).unwrap(); assert!(b.try_clone().unwrap().check(CheckLevel::All).unwrap().is_valid()); let dir = std::env::temp_dir().join(format!("solidcraft-smlib-check-{}", std::process::id())); diff --git a/crates/smlib/src/core.rs b/crates/smlib/src/core.rs index 9fc714ee7..88d14820c 100644 --- a/crates/smlib/src/core.rs +++ b/crates/smlib/src/core.rs @@ -25,6 +25,7 @@ mod boolean_tests; mod convert; #[cfg(test)] mod convert_tests; +pub(crate) mod file; pub(crate) mod history; mod measure; #[cfg(test)] diff --git a/crates/smlib/src/core/blend_tests.rs b/crates/smlib/src/core/blend_tests.rs index 389f0a721..4ca486cf2 100644 --- a/crates/smlib/src/core/blend_tests.rs +++ b/crates/smlib/src/core/blend_tests.rs @@ -371,11 +371,13 @@ macro_rules! cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::cpp_case(stringify!($m)); } } @@ -768,12 +770,14 @@ mod history { /// new. #[test] fn tags_cross_a_fillet() { + let _cpp = crate::route::on_cpp(); check(Blend::Round, 2.0); } /// A 2 mm chamfer on the same edge: the same faces kept, trimmed and made as the round. #[test] fn tags_cross_a_chamfer() { + let _cpp = crate::route::on_cpp(); check(Blend::Chamfer, 2.0); } } diff --git a/crates/smlib/src/core/boolean_tests.rs b/crates/smlib/src/core/boolean_tests.rs index e016fc72b..c92971796 100644 --- a/crates/smlib/src/core/boolean_tests.rs +++ b/crates/smlib/src/core/boolean_tests.rs @@ -260,6 +260,7 @@ macro_rules! cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } } @@ -415,6 +416,7 @@ mod history { #[test] fn tags_cross_a_cpp_boolean() { + let _cpp = crate::route::on_cpp(); let (a, b) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([5.0; 3], [10.0; 3], 1)); let r = Brep::made(ffi::ops::boolean(a.cpp().unwrap(), b.cpp().unwrap(), ffi::ops::BOOLEAN_UNION).unwrap()); check(&r.history().unwrap()); @@ -422,6 +424,7 @@ mod history { #[test] fn tags_cross_a_solidcore_boolean() { + let _cpp = crate::route::on_cpp(); let (a, b) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([5.0; 3], [10.0; 3], 1)); let r = super::boolean(a.core().unwrap(), b.core().unwrap(), BooleanOp::Union).unwrap().unwrap(); check(&Brep::made_core(r).history().unwrap()); @@ -441,6 +444,7 @@ mod history { #[test] fn an_overlapping_union_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); parity(&tagged_box([0.0; 3], [10.0; 3], 0), &tagged_box([5.0; 3], [10.0; 3], 1), BooleanOp::Union); } @@ -448,6 +452,7 @@ mod history { /// come from the tool. #[test] fn a_slot_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); let (a, b) = (tagged_box([0.0; 3], [20.0; 3], 0), tagged_box([5.0, -1.0, 10.0], [10.0, 22.0, 15.0], 1)); parity(&a, &b, BooleanOp::Subtract); } @@ -456,6 +461,7 @@ mod history { /// found lying on each other's (SMLib's coincidences and merges) stand for both. #[test] fn boxes_side_by_side_have_the_cpp_history() { + let _cpp = crate::route::on_cpp(); let (a, b) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([10.0, 0.0, 0.0], [10.0; 3], 1)); parity(&a, &b, BooleanOp::Union); } @@ -463,6 +469,7 @@ mod history { /// A box sharing one corner region with another: the intersection keeps three faces of each. #[test] fn an_intersection_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); parity(&tagged_box([0.0; 3], [10.0; 3], 0), &tagged_box([5.0; 3], [10.0; 3], 1), BooleanOp::Intersect); } @@ -470,6 +477,7 @@ mod history { /// copy's history is the operand's own, every face Kept, as on C++. #[test] fn tags_cross_a_copy() { + let _cpp = crate::route::on_cpp(); let a = tagged_box([0.0; 3], [10.0, 20.0, 30.0], 0); // Converted (and tagged) before the kernel's lock is taken: the conversion takes it too. let body = a.core().unwrap(); @@ -488,6 +496,7 @@ mod history { /// post's foot, the other faces are as they were. #[test] fn an_imprint_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); let (a, b) = (tagged_box([0.0; 3], [20.0; 3], 0), tagged_box([5.0, 5.0, 10.0], [10.0, 10.0, 20.0], 1)); let cpp = Brep::made(ffi::ops::imprint(a.cpp().unwrap(), b.cpp().unwrap()).unwrap()).history().unwrap(); let core = Brep::made_core(super::imprint(a.core().unwrap(), b.core().unwrap()).unwrap().unwrap()).history().unwrap(); @@ -501,6 +510,7 @@ mod history { /// x = 0, x = 40 and the bottom (the fork's 1c7accd; before, y = 0 and y = 30 were Modified). #[test] fn a_face_whose_edge_is_only_cut_by_a_vertex_is_kept() { + let _cpp = crate::route::on_cpp(); use solidcraft_geom::brep::history::Change; let (a, b) = (tagged_box([0.0; 3], [40.0, 30.0, 20.0], 0), tagged_box([10.0, -5.0, 20.0], [10.0, 40.0, 10.0], 1)); let cpp = Brep::made(ffi::ops::imprint(a.cpp().unwrap(), b.cpp().unwrap()).unwrap()).history().unwrap(); @@ -519,6 +529,7 @@ mod history { /// child the split edge's `at`), so the side x = 0 is still all of itself and Kept. #[test] fn an_imprint_split_edge_lies_where_the_edge_lay() { + let _cpp = crate::route::on_cpp(); use solidcraft_geom::brep::history::Change; let (a, b) = (tagged_box([0.0; 3], [20.0; 3], 0), tagged_box([0.0, 5.0, 20.0], [10.0; 3], 1)); let cpp = Brep::made(ffi::ops::imprint(a.cpp().unwrap(), b.cpp().unwrap()).unwrap()).history().unwrap(); @@ -540,6 +551,7 @@ mod history { /// leaves a target that already has a tag alone, so the top stands for the cube's top only. #[test] fn a_copy_onto_a_tagged_face_keeps_its_own_tag() { + let _cpp = crate::route::on_cpp(); use solidcraft_geom::brep::history::Change; let (a, b) = (tagged_box([0.0; 3], [20.0; 3], 0), tagged_box([5.0, 5.0, 20.0], [10.0; 3], 1)); parity(&a, &b, BooleanOp::Subtract); @@ -553,6 +565,7 @@ mod history { /// own tag (SMLib's Copy), as on C++. #[test] fn a_copy_onto_a_tagged_edge_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); parity(&tagged_box([0.0; 3], [10.0; 3], 0), &tagged_box([10.0, 0.0, 0.0], [10.0; 3], 1), BooleanOp::Subtract); } @@ -578,6 +591,7 @@ mod history { /// A hole through a block: the tool's and the block's faces meet along whole circles. #[test] fn a_round_hole_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); parity(&tagged_box([0.0; 3], [40.0, 40.0, 10.0], 0), &tagged_cylinder([20.0, 20.0, -5.0], 5.0, 20.0, 1), BooleanOp::Subtract); } @@ -585,6 +599,7 @@ mod history { /// edge still where it lay (`moved`'s `open.is_empty()`), so it is Kept on both kernels. #[test] fn a_face_bounded_by_closed_edges_is_kept() { + let _cpp = crate::route::on_cpp(); use solidcraft_geom::brep::history::Change; let (a, b) = (holed_plate(0), tagged_box([35.0, 35.0, -5.0], [10.0, 10.0, 20.0], 1)); let cpp = Brep::made(ffi::ops::boolean(a.cpp().unwrap(), b.cpp().unwrap(), ffi::ops::BOOLEAN_SUBTRACT).unwrap()).history().unwrap(); @@ -598,6 +613,7 @@ mod history { /// and cut that closed edge by vertices; the top is split, the wall's rim stays where it lay. #[test] fn an_imprint_cutting_a_closed_edge_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); let (a, b) = (holed_plate(0), tagged_box([-5.0, 18.0, 10.0], [50.0, 4.0, 5.0], 1)); let cpp = Brep::made(ffi::ops::imprint(a.cpp().unwrap(), b.cpp().unwrap()).unwrap()).history().unwrap(); let core = Brep::made_core(super::imprint(a.core().unwrap(), b.core().unwrap()).unwrap().unwrap()).history().unwrap(); @@ -608,6 +624,7 @@ mod history { /// each curved face is split in two across its seam. #[test] fn a_curved_face_split_across_its_seam_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); use solidcraft_geom::brep::history::Change; let slab = || tagged_box([-20.0, -1.0, -20.0], [40.0, 2.0, 40.0], 1); let sphere = Brep::made(ffi::make_sphere(&[0.0, 0.0, 0.0], 7.0).unwrap()).tagged(0).unwrap(); @@ -621,6 +638,7 @@ mod history { /// A chain of three overlapping boxes in one `union_all`. #[test] fn a_union_of_three_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); let (a, b, c) = (tagged_box([0.0; 3], [10.0; 3], 0), tagged_box([5.0; 3], [10.0; 3], 1), tagged_box([10.0; 3], [10.0; 3], 2)); let cpp = Brep::made(ffi::ops::boolean_union_all(&[a.cpp().unwrap(), b.cpp().unwrap(), c.cpp().unwrap()]).unwrap()).history().unwrap(); let core = Brep::made_core(super::union_all(&[a.core().unwrap(), b.core().unwrap(), c.core().unwrap()]).unwrap()).history().unwrap(); @@ -633,6 +651,7 @@ mod history { /// stands for all four, both sources carrying several origins. #[test] fn a_merge_of_several_origins_on_each_side_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); let boxes: Vec = (0..4u32).map(|i| tagged_box([f64::from(i) * 10.0, 0.0, 0.0], [10.0; 3], i as usize)).collect(); let c = |x: usize, y: usize| ffi::ops::boolean(boxes[x].cpp().unwrap(), boxes[y].cpp().unwrap(), ffi::ops::BOOLEAN_UNION).unwrap(); let (ab, cd) = (c(0, 1), c(2, 3)); @@ -648,6 +667,7 @@ mod history { #[test] #[ignore = "solidcore's boolean_2d carries no attributes through its merge (#1462's scope; write-up review-1031/bugs/boolean2d-drops-history.md, not filed yet)"] fn a_boolean2d_has_the_cpp_history() { + let _cpp = crate::route::on_cpp(); use crate::sweeps::Curve; let square = |x: f64, y: f64, s: f64, operand: usize| { crate::init().unwrap(); diff --git a/crates/smlib/src/core/convert_tests.rs b/crates/smlib/src/core/convert_tests.rs index a24c96001..6a8133577 100644 --- a/crates/smlib/src/core/convert_tests.rs +++ b/crates/smlib/src/core/convert_tests.rs @@ -152,11 +152,13 @@ macro_rules! primitive { #[cfg(feature = "native")] #[test] fn its_record_measures_in_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::record_measures_in_cpp($name); } #[cfg(feature = "native")] #[test] fn arrays_match_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::matches_cpp($name); } } @@ -222,6 +224,7 @@ fn a_parabola_gives_its_nurb_or_says_it_cannot() { #[cfg(feature = "native")] #[test] fn validate_refuses_what_the_cpp_kernel_refuses() { + let _cpp = crate::route::on_cpp(); /// `SM_ERR_INVALID_INPUT`. const INVALID_INPUT: i32 = 1007; use crate::flat::Flat; @@ -291,6 +294,7 @@ fn validate_refuses_what_the_cpp_kernel_refuses() { #[cfg(feature = "native")] #[test] fn a_cpp_box_comes_into_solidcore() { + let _cpp = crate::route::on_cpp(); crate::init().unwrap(); let cpp = crate::ffi::make_box(&[1.0, -2.0, 3.0], &[10.0, 20.0, 30.0]).map(crate::Brep::made).unwrap(); let body = from_arrays(&cpp.cpp_arrays().unwrap()).unwrap(); @@ -431,6 +435,7 @@ fn shells_listed_inner_first_import_outer_first() { #[cfg(feature = "native")] #[test] fn a_sealed_void_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); use crate::{Brep, ffi}; crate::init().unwrap(); let make = |o: f64, s: f64| ffi::make_box(&[o; 3], &[s; 3]).map(Brep::made).unwrap(); @@ -597,6 +602,7 @@ mod cpp_round_trip { /// on an operation's tolerances. #[test] fn a_filleted_box() { + let _cpp = crate::route::on_cpp(); let a = cpp_box([0.0; 3], [20.0; 3]); let edges = [[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]; let f = Brep::made(ffi::ops::pick_op(ffi::ops::Pick::Fillet, a.cpp().unwrap(), &edges, PICK_TOL, 2.0).unwrap()); @@ -607,6 +613,7 @@ mod cpp_round_trip { /// A plate with a round hole: inner loops, and a cylinder face looking at its axis. #[test] fn a_holed_plate() { + let _cpp = crate::route::on_cpp(); let p = cut(&cpp_box([0.0; 3], [40.0, 30.0, 5.0]), &cpp_cylinder([20.0, 15.0, -1.0], 6.0, 7.0)); let rec = crosses_with_volume("holed plate", &p); assert!(has_face(&rec, |f| f.loops.len() > 1), "no inner loop"); @@ -615,6 +622,7 @@ mod cpp_round_trip { /// A square swept along a cubic B-spline path: B-spline walls that are nothing analytic. #[test] fn a_swept_nurbs_face() { + let _cpp = crate::route::on_cpp(); let c = [[-2.0, -2.0, 0.0], [2.0, -2.0, 0.0], [2.0, 2.0, 0.0], [-2.0, 2.0, 0.0]]; let square: Vec = (0..4).map(|i| Curve::Line { start: c[i], end: c[(i + 1) % 4] }).collect(); let points = [[0.0, 0.0, 0.0, 1.0], [0.0, 10.0, 20.0, 1.0], [10.0, -10.0, 40.0, 1.0], [10.0, 0.0, 60.0, 1.0]]; @@ -627,6 +635,7 @@ mod cpp_round_trip { /// A cylinder sliced by a plane leaning 45 degrees: the cut's edge an ellipse. #[test] fn an_ellipse_edge() { + let _cpp = crate::route::on_cpp(); let cyl = cpp_cylinder([0.0, 0.0, -30.0], 5.0, 60.0); let (s, c) = std::f64::consts::FRAC_PI_4.sin_cos(); // About y through the origin; the box's underside is the plane z = 0 turned. @@ -639,6 +648,7 @@ mod cpp_round_trip { /// A 20 mm box with a 10 mm void sealed inside: two shells in the solid's region. #[test] fn a_sealed_void() { + let _cpp = crate::route::on_cpp(); let v = cut(&cpp_box([-10.0; 3], [20.0; 3]), &cpp_box([-5.0; 3], [10.0; 3])); let rec = crosses_with_volume("sealed void", &v); assert!(rec.regions.iter().any(|r| r.shells.len() == 2), "{:?}", rec.regions); @@ -648,6 +658,7 @@ mod cpp_round_trip { /// One planar face, and an open extrusion: a sheet's shells, no solid. #[test] fn sheets() { + let _cpp = crate::route::on_cpp(); let c = [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 6.0, 0.0], [0.0, 6.0, 0.0]]; let rect: Vec = (0..4).map(|i| Curve::Line { start: c[i], end: c[(i + 1) % 4] }).collect(); let rec = crosses("planar sheet", &on_cpp(|| Brep::planar_faces(&rect))); @@ -709,6 +720,7 @@ mod cpp_round_trip { /// arrays only. #[test] fn wire_edges_and_a_point_shell() { + let _cpp = crate::route::on_cpp(); let theirs = Flat::from_arrays(&box_with_wires_and_a_point()).unwrap().import().unwrap().cpp_arrays().unwrap(); assert_eq!(theirs.ints[&flat::WIRE_EDGE_CURVE_TYPE].len(), 4); assert_eq!(theirs.reals[&flat::SHELL_POINT_POSITION], [1.0, 2.0, 3.0]); @@ -718,6 +730,7 @@ mod cpp_round_trip { /// Two boxes apart, united: two lumps. #[test] fn a_multi_lump_body() { + let _cpp = crate::route::on_cpp(); let (a, b) = (cpp_box([0.0; 3], [10.0; 3]), cpp_box([30.0, 0.0, 0.0], [5.0; 3])); let u = Brep::made(ffi::ops::boolean(a.cpp().unwrap(), b.cpp().unwrap(), ffi::ops::BOOLEAN_UNION).unwrap()); let rec = crosses_with_volume("two lumps", &u); @@ -728,6 +741,7 @@ mod cpp_round_trip { /// A rounded box shelled: faces on the offsets of its rounds, on the operation's tolerances. #[test] fn a_shelled_rounded_box() { + let _cpp = crate::route::on_cpp(); let a = cpp_box([0.0; 3], [20.0; 3]); let r = ffi::ops::pick_op(ffi::ops::Pick::Fillet, a.cpp().unwrap(), &[[10.0, 0.0, 0.0]], PICK_TOL, 2.0).unwrap(); let s = Brep::made(ffi::ops::pick_op(ffi::ops::Pick::Shell, &r, &[[10.0, 10.0, 20.0]], PICK_TOL, -1.0).unwrap()); diff --git a/crates/smlib/src/core/file.rs b/crates/smlib/src/core/file.rs new file mode 100644 index 000000000..03b8c937f --- /dev/null +++ b/crates/smlib/src/core/file.rs @@ -0,0 +1,56 @@ +//! `.smb` files on solidcore (`smlib_brep_read`, `smlib_brep_write`): the B-rep's contents through +//! `SmApiReadBrepFromFile` and `SmApiWriteBrepToFile`, the file itself read and written here (the +//! library touches no files, so that it builds for the browser). + +use std::path::Path; + +use solidcore::geom::attribute::{AttributeStore, ObjectKey}; +use solidcore::topology::api_files::{read_brep_from_file, write_brep_to_file}; +use solidcore::topology::brep::p10::TopologyEnv; +use solidcore::topology::brep_data_write::FromBrepEnv; +use solidcore::topology::topology::NotifyRecords; +use solidcore::topology::{EdgeId, EdgeuseId, FaceId}; + +use super::convert::key_of; +use super::{Body, run, with_body}; +use crate::{Error, Result}; + +/// Where the keys of a file's curves and surfaces start, clear of [`key_of`]'s entity keys. +const FILE_KEYS: u64 = 1 << 50; + +fn io(what: &str, path: &Path, e: &std::io::Error) -> Error { + Error::Solidcore(format!("{what} {}: {e}", path.display())) +} + +/// The body in the file at `path`, ASCII or binary. Its UV trims are checked, not rebuilt, as the +/// C API reads them. +pub(crate) fn read(path: &Path, ascii: bool) -> Result { + let data = std::fs::read(path).map_err(|e| io("reading", path, &e))?; + let b = run("smlib_brep_read", |k| { + let mut attributes = AttributeStore::default(); + let mut records = NotifyRecords::new(); + let mut env = TopologyEnv { all_attributes: &[], attributes: &mut attributes, key_of: &key_of, records: &mut records, next_key: FILE_KEYS }; + let mut b = read_brep_from_file(k, Some(data), ascii, false, &mut env)?; + b.refresh_cached_topology(); + Ok(b) + })?; + Ok(Body::new(b)) +} + +/// `body` written to the file at `path`, ASCII or binary. +pub(crate) fn write(body: &Body, path: &Path, ascii: bool) -> Result<()> { + let bytes = with_body("smlib_brep_write", body, |k, b| { + let store = AttributeStore::default(); + let records = NotifyRecords::new(); + let env = FromBrepEnv { + attributes: &store, + key_of: &key_of, + records: &records, + curve_key: &|_: EdgeId| ObjectKey(0), + uv_curve_key: &|_: EdgeuseId| ObjectKey(0), + surface_key: &|_: FaceId| ObjectKey(0), + }; + write_brep_to_file(k, Some(&*b), &env, ascii) + })?; + std::fs::write(path, bytes).map_err(|e| io("writing", path, &e)) +} diff --git a/crates/smlib/src/core/measure_tests.rs b/crates/smlib/src/core/measure_tests.rs index e70349e8c..dc80111ba 100644 --- a/crates/smlib/src/core/measure_tests.rs +++ b/crates/smlib/src/core/measure_tests.rs @@ -244,37 +244,44 @@ macro_rules! primitive { #[test] $(#[$mass])? fn mass_properties_match_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); mass_properties_parity($name); } #[cfg(feature = "native")] #[test] $(#[$area])? fn area_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); area_parity($name); } #[cfg(feature = "native")] #[test] fn bounds_match_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); bounds_parity($name); } #[cfg(feature = "native")] #[test] fn solid_count_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); solid_count_parity($name); } #[cfg(feature = "native")] #[test] fn manifold_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); manifold_parity($name); } #[cfg(feature = "native")] #[test] fn distances_match_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); distance_parity($name); } #[cfg(feature = "native")] #[test] fn check_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); check_parity($name); } } diff --git a/crates/smlib/src/core/merge_tests.rs b/crates/smlib/src/core/merge_tests.rs index c96d36af6..f89a15e4d 100644 --- a/crates/smlib/src/core/merge_tests.rs +++ b/crates/smlib/src/core/merge_tests.rs @@ -254,11 +254,13 @@ macro_rules! cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::cpp_case(stringify!($m)); } } @@ -403,6 +405,7 @@ fn a_flap_on_a_cube_edge_stays_beside_it() { #[cfg(feature = "native")] #[test] fn sheets_on_a_cube_stitch_the_same_on_cpp() { + let _cpp = crate::route::on_cpp(); use crate::{Brep, error, ffi}; crate::init().unwrap(); let sew = |b: Body| ffi::sheets::stitch(Brep::made_core(b).cpp().unwrap(), 1e-6).map_err(error); @@ -437,6 +440,7 @@ mod history { #[test] fn tags_cross_a_stitch() { + let _cpp = crate::route::on_cpp(); crate::init().unwrap(); let a = Brep::made_core(super::loose_faces(super::ALL, 0.0)).tagged(0).unwrap(); let cpp = Brep::made(ffi::sheets::stitch(a.cpp().unwrap(), super::TOL).unwrap().0).history().unwrap(); @@ -446,6 +450,7 @@ mod history { #[test] fn tags_cross_a_merge() { + let _cpp = crate::route::on_cpp(); crate::init().unwrap(); let a = Brep::made_core(super::split_cube()).tagged(0).unwrap(); let cpp = Brep::made(ffi::ops::merge_faces(a.cpp().unwrap(), &[], super::TOL).unwrap()).history().unwrap(); diff --git a/crates/smlib/src/core/offset_tests.rs b/crates/smlib/src/core/offset_tests.rs index ccb2360f1..2671b0fe3 100644 --- a/crates/smlib/src/core/offset_tests.rs +++ b/crates/smlib/src/core/offset_tests.rs @@ -422,11 +422,13 @@ macro_rules! cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::cpp_case(stringify!($m)); } } @@ -631,6 +633,7 @@ fn a_draft_leaves_no_mark() { #[cfg(feature = "native")] #[test] fn a_draft_moves_a_face_as_on_cpp() { + let _cpp = crate::route::on_cpp(); use crate::sweeps::{Curve, DraftCorner}; use crate::{Brep, ffi}; crate::init().unwrap(); @@ -674,6 +677,7 @@ fn a_draft_moves_a_face_as_on_cpp() { #[cfg(feature = "native")] #[test] fn a_draft_past_the_neighbours_meeting_is_unsupported_as_on_cpp() { + let _cpp = crate::route::on_cpp(); use crate::sweeps::{Curve, DraftCorner}; use crate::{Brep, ffi}; crate::init().unwrap(); @@ -693,6 +697,7 @@ fn a_draft_past_the_neighbours_meeting_is_unsupported_as_on_cpp() { #[cfg(feature = "native")] #[test] fn an_l_sheet_thickens_as_on_cpp() { + let _cpp = crate::route::on_cpp(); use crate::sweeps::{Curve, DraftCorner}; use crate::{Brep, ffi}; crate::init().unwrap(); @@ -722,6 +727,7 @@ mod history { /// faces they offset. #[test] fn tags_cross_a_shell() { + let _cpp = crate::route::on_cpp(); let a = tagged_box(); let top = [[10.0, 15.0, 10.0]]; let cpp = Brep::made(ffi::ops::pick_op(ffi::ops::Pick::Shell, a.cpp().unwrap(), &top, super::TOL, -2.0).unwrap()).history().unwrap(); @@ -732,6 +738,7 @@ mod history { /// The top moved down 2 mm: it stands for itself, its four neighbours are trimmed to meet it. #[test] fn tags_cross_a_face_offset() { + let _cpp = crate::route::on_cpp(); let a = tagged_box(); let top = [[10.0, 15.0, 10.0]]; let cpp = Brep::made(ffi::ops::pick_op(ffi::ops::Pick::OffsetFaces, a.cpp().unwrap(), &top, super::TOL, -2.0).unwrap()).history().unwrap(); @@ -771,18 +778,21 @@ mod history { #[test] fn tags_cross_a_thicken_of_a_curved_sheet() { + let _cpp = crate::route::on_cpp(); thicken_parity(true); } #[test] #[ignore = "solidcore's stitch in the shell drops the flat sheet's edge tags (write-up review-1031/bugs/thicken-flat-sheet-edge-tags.md, not filed yet)"] fn tags_cross_a_thicken_of_a_flat_sheet() { + let _cpp = crate::route::on_cpp(); thicken_parity(false); } /// A sheet moved along its normal, flat and curved: each face stands for itself. #[test] fn tags_cross_a_sheet_offset() { + let _cpp = crate::route::on_cpp(); for curved in [false, true] { let a = tagged_sheet(curved); let cpp = Brep::made(ffi::sheets::offset_sheet(a.cpp().unwrap(), 1.5).unwrap()).history().unwrap(); @@ -794,6 +804,7 @@ mod history { /// A cylinder hollowed, its top open: the walls round closed edges, on a curved face. #[test] fn tags_cross_a_shell_of_a_cylinder() { + let _cpp = crate::route::on_cpp(); crate::init().unwrap(); let a = Brep::made(ffi::make_cylinder(&[0.0; 3], 10.0, 20.0).unwrap()).tagged(0).unwrap(); let top = [[0.0, 0.0, 20.0]]; @@ -806,6 +817,7 @@ mod history { /// edges move with it. #[test] fn tags_cross_a_draft() { + let _cpp = crate::route::on_cpp(); let a = tagged_box(); let front = [[10.0, 0.0, 5.0]]; let (origin, normal, pull, angle) = ([0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], 5f64.to_radians()); diff --git a/crates/smlib/src/core/split_tests.rs b/crates/smlib/src/core/split_tests.rs index ddbb38f64..3257d6a88 100644 --- a/crates/smlib/src/core/split_tests.rs +++ b/crates/smlib/src/core/split_tests.rs @@ -159,7 +159,7 @@ fn cpp_case(name: &str) -> Got { let got = match &op { Op::Faces(faces, tools) => { let made: Vec = tools.iter().map(surface).collect(); - let handles: Vec<&ffi::ssi::SurfaceHandle> = made.iter().map(|s| s.handle()).collect(); + let handles: Vec<&ffi::ssi::SurfaceHandle> = made.iter().map(|s| s.handle().unwrap()).collect(); let faces: Vec = faces.iter().map(|&f| f as i64).collect(); match ffi::split::split_faces(body.cpp().unwrap(), &faces, &handles) { Ok((h, made)) => { @@ -170,7 +170,7 @@ fn cpp_case(name: &str) -> Got { Err(s) => Err(error(s)), } } - Op::Body(tool) => match ffi::split::split_body(body.cpp().unwrap(), surface(tool).handle()) { + Op::Body(tool) => match ffi::split::split_body(body.cpp().unwrap(), surface(tool).handle().unwrap()) { Ok((b, f)) => { let (vb, nb) = measure(&b); let (vf, nf) = measure(&f); @@ -211,11 +211,13 @@ macro_rules! cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::cpp_case(stringify!($m)); } } @@ -352,12 +354,13 @@ mod history { #[test] fn tags_cross_a_face_split() { + let _cpp = crate::route::on_cpp(); crate::init().unwrap(); let a = Brep::made_core(super::cube()).tagged(0).unwrap(); let p = super::plane_x(5.0); let s = super::surface(&p); let faces = [0i64, 1, 2, 3, 4, 5]; - let cpp = Brep::made(ffi::split::split_faces(a.cpp().unwrap(), &faces, &[s.handle()]).unwrap().0).history().unwrap(); + let cpp = Brep::made(ffi::split::split_faces(a.cpp().unwrap(), &faces, &[s.handle().unwrap()]).unwrap().0).history().unwrap(); let core = super::split_faces(a.core().unwrap(), &[0, 1, 2, 3, 4, 5], &[&p]).unwrap().unwrap().0; let core = Brep::made_core(core).history().unwrap(); assert_eq!(core.canonical(), cpp.canonical()); diff --git a/crates/smlib/src/core/sweep_tests.rs b/crates/smlib/src/core/sweep_tests.rs index 55e9c04f3..e1a568f52 100644 --- a/crates/smlib/src/core/sweep_tests.rs +++ b/crates/smlib/src/core/sweep_tests.rs @@ -416,11 +416,13 @@ macro_rules! cases { $(#[$ign])? $(#[$pign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::cpp_case(stringify!($m)); } } @@ -553,6 +555,7 @@ fn sweep_placed_reports_the_motions() { #[cfg(feature = "native")] #[test] fn the_cpp_kernel_places_the_profile_alike() { + let _cpp = crate::route::on_cpp(); crate::sweeps::ON_CPP.with(|c| c.set(true)); let (p, up) = straight_up(); let (q, arc) = round_z(); @@ -671,6 +674,7 @@ fn a_box_top_section_is_the_line_across_it() { #[cfg(feature = "native")] #[test] fn the_cpp_kernel_sections_a_face_alike() { + let _cpp = crate::route::on_cpp(); use crate::{Brep, ffi}; type Case = (&'static str, Box Body>, Brep, [[f64; 3]; 3]); let cases: [Case; 3] = [ diff --git a/crates/smlib/src/core/transform_tests.rs b/crates/smlib/src/core/transform_tests.rs index 56cf5be03..8d7050160 100644 --- a/crates/smlib/src/core/transform_tests.rs +++ b/crates/smlib/src/core/transform_tests.rs @@ -226,11 +226,13 @@ macro_rules! cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::cpp_case(stringify!($m)); } } @@ -304,6 +306,7 @@ mod history { #[test] fn tags_cross_a_copy() { + let _cpp = crate::route::on_cpp(); let a = tagged_box(); let cpp = Brep::made(ffi::copy(a.cpp().unwrap()).unwrap()).history().unwrap(); let core = Brep::made_core(super::copy(a.core().unwrap()).unwrap()).history().unwrap(); @@ -312,6 +315,7 @@ mod history { #[test] fn tags_cross_a_mirror_and_a_shear() { + let _cpp = crate::route::on_cpp(); let a = tagged_box(); let mirror = [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0; 4]]; let shear = [[1.0, 0.5, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [2.0, 3.0, 4.0, 1.0]]; diff --git a/crates/smlib/src/core/trim.rs b/crates/smlib/src/core/trim.rs index 1576a5e24..8c9dc8d7e 100644 --- a/crates/smlib/src/core/trim.rs +++ b/crates/smlib/src/core/trim.rs @@ -36,7 +36,7 @@ use solidcore::kernel::Kernel; use solidcore::nurbs::b_spline_surface::p1::SurfParamType; use solidcore::nurbs::b_spline_surface_n_lib::p2::EvaluateFlags; use solidcore::nurbs::b_spline_surface_n_lib::p2::OrientType; -use solidcore::query::api_queries::{edge_closest_point, face_closest_point_in_shape}; +use solidcore::query::api_queries::{edge_closest_point, face_closest_point_in_shape, face_internal_point}; use solidcore::query::brep::{BrepQuery, LiveBrepObjects}; use solidcore::surface::cone::p1::Cone; use solidcore::surface::surface::Surface; @@ -848,3 +848,12 @@ pub(crate) fn extend_sheet(sheet: &Body, point: [f64; 3], tol: f64, distance: f6 })? .map(Body::new) } + +/// A point inside each face, in the body's face order (`smlib_brep_face_points`: +/// `SmFace::CalculateAnInternalPoint`). +pub(crate) fn face_points(body: &Body) -> Result> { + super::with_body("smlib_brep_face_points", body, |k, b| { + let faces = b.face_list().to_vec(); + faces.into_iter().map(|f| face_internal_point(k, b, f).map(|p| [p.x, p.y, p.z])).collect() + }) +} diff --git a/crates/smlib/src/core/trim_tests.rs b/crates/smlib/src/core/trim_tests.rs index 8e3a424f9..46d65cdc0 100644 --- a/crates/smlib/src/core/trim_tests.rs +++ b/crates/smlib/src/core/trim_tests.rs @@ -178,11 +178,13 @@ macro_rules! cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::cpp_case(stringify!($m)); } } @@ -235,6 +237,7 @@ mod history { #[test] fn tags_cross_an_untrim() { + let _cpp = crate::route::on_cpp(); crate::init().unwrap(); let a = Brep::made_core(super::holed_sheet()).tagged(0).unwrap(); for (holes, outer) in [(None, false), (Some(&[][..]), true)] { @@ -384,11 +387,13 @@ macro_rules! extend_cases { #[test] $(#[$ign])? fn solidcore_matches_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); super::extend_parity(stringify!($m)); } #[cfg(feature = "native")] #[test] fn the_cpp_kernel_matches_the_closed_form() { + let _cpp = crate::route::on_cpp(); let _ = super::extend_cpp(stringify!($m)); } } diff --git a/crates/smlib/src/import.rs b/crates/smlib/src/import.rs index 2890f9e29..0bd88cbc4 100644 --- a/crates/smlib/src/import.rs +++ b/crates/smlib/src/import.rs @@ -651,7 +651,7 @@ mod tests; impl crate::Brep { /// A body of the kernel [`crate::route::Op::Convert`] routes to, from flat arrays. - fn from_arrays(a: &Arrays) -> crate::Result { + pub(crate) fn from_arrays(a: &Arrays) -> crate::Result { match crate::route::Op::Convert.backend() { crate::route::Backend::Smlib => crate::flat::Flat::from_arrays(a)?.import(), crate::route::Backend::Solidcore => crate::core::from_arrays(a).map(crate::Brep::made_core), diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs index df6e1b95e..2019d1608 100644 --- a/crates/smlib/src/lib.rs +++ b/crates/smlib/src/lib.rs @@ -79,6 +79,9 @@ pub enum Error { Version(i32), /// This build has no SMLib (the `native` feature is off). NotBuilt, + /// The kernel the call is routed to has no such operation (what it is). Nothing falls back + /// to the other kernel. + NotOnSolidcore(&'static str), /// A B-rep record SMLib cannot take (see [`import::Unsupported`]). Record(import::Unsupported), /// solidcore reported an error (the call, then its message). @@ -121,6 +124,7 @@ impl std::fmt::Display for Error { Error::Exception => write!(f, "SMLib raised an internal exception"), Error::Version(v) => write!(f, "SMLib C API version {v}, expected {}", ffi::ABI_VERSION), Error::NotBuilt => write!(f, "not supported yet: this build has no SMLib"), + Error::NotOnSolidcore(what) => write!(f, "not supported yet on solidcore: {what}"), Error::Record(u) => write!(f, "{u}"), Error::Solidcore(e) => write!(f, "solidcore: {e}"), Error::Internal(e) => write!(f, "solidcore failed internally in {e}"), @@ -295,12 +299,20 @@ impl Brep { /// Reads a native SMLib `.smb` file. pub fn read(path: &Path, ascii: bool) -> Result { + if route::Op::File.backend() == route::Backend::Solidcore { + c_path(path)?; + return core::file::read(path, ascii).map(Brep::made_core); + } init()?; ffi::read(&c_path(path)?, ascii).map(Brep::made).map_err(error) } /// Writes this body to a native SMLib `.smb` file. pub fn write(&self, path: &Path, ascii: bool) -> Result<()> { + if route::Op::File.backend() == route::Backend::Solidcore { + c_path(path)?; + return core::file::write(self.core()?, path, ascii); + } check(ffi::write(self.cpp()?, &c_path(path)?, ascii)) } diff --git a/crates/smlib/src/ops_tests.rs b/crates/smlib/src/ops_tests.rs index 85e3ab4b6..ae26a20e7 100644 --- a/crates/smlib/src/ops_tests.rs +++ b/crates/smlib/src/ops_tests.rs @@ -311,12 +311,6 @@ fn a_variable_round_follows_its_law() { let zero = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &knots, &[4.0, 0.0]).unwrap(); shot(&zero, "variable-to-zero"); assert_close(volume(&zero), 8000.0 - q * 20.0 * 16.0 / 3.0, 1e-5, "down to zero"); - // A law with a corner (4 → 2 → 4, straight on both halves): the round turns at the corner, - // each half taking away (1 - pi/4) (L / 2) (16 + 8 + 4) / 3; the same points joined smoothly - // (C1 cubic pieces, as RadiusSpline::through makes them) are built too. - let corner = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[4.0, 2.0, 4.0]).unwrap(); - shot(&corner, "variable-corner-4-2-4"); - assert_close(volume(&corner), 8000.0 - q * 20.0 * 28.0 / 3.0, 1e-6, "corner law"); // A law down to zero inside the edge would pinch the round to a point: refused. let pinch = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[4.0, 0.0, 4.0]); assert!(pinch.is_err(), "a law pinching to zero inside the edge"); @@ -385,6 +379,30 @@ fn draft_tilts_a_side_about_its_line_on_the_neutral_plane() { assert_untouched(&c, 8000.0, [6, 12, 8]); } +/// A law with a corner (4 → 2 → 4, straight on both halves): the round turns at the corner, each +/// half taking away (1 - pi/4) (L / 2) (16 + 8 + 4) / 3; the same points joined smoothly (C1 cubic +/// pieces, as RadiusSpline::through makes them) are built too. solidcore has no splitting of the +/// round at the corner (default-solidcore/bugs/variable-fillet-law-with-a-corner.md), and says so. +#[test] +#[ignore = "solidcore: no SplitFilletFacesAtRadiusCorners, so a law with a corner is refused"] +fn a_variable_round_turns_at_a_law_corner() { + variable_round_with_a_corner(); +} + +#[test] +fn a_variable_round_turns_at_a_law_corner_on_the_cpp_kernel() { + let _cpp = crate::route::on_cpp(); + variable_round_with_a_corner(); +} + +fn variable_round_with_a_corner() { + let c = cube(20.0); + let q = 1.0 - std::f64::consts::FRAC_PI_4; + let corner = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[4.0, 2.0, 4.0]).unwrap(); + shot(&corner, "variable-corner-4-2-4"); + assert_close(volume(&corner), 8000.0 - q * 20.0 * 28.0 / 3.0, 1e-6, "corner law"); +} + /// The corner of r5 rounds at (60, 40, 20) on a 60 x 40 x 20 box, set back 8 and left open: the /// box's six faces and the three rounds (9 faces, 30 edges, 22 vertices), a sheet SMLib's check /// passes, and one hole of twelve edges (each section and face curve in two), chained end to @@ -398,7 +416,8 @@ fn a_setback_corner_left_open_returns_its_hole() { let (open, holes) = b.blend_setback_open(Blend::Round, &edges, &[5.0; 3], &[[60.0, 40.0, 20.0]], &[8.0], 0.1).unwrap(); // The call is a profiler span like every other, timed by the C API. let report = mark.report(); - assert!(report.rows.iter().any(|r| r.category == "smlib" && r.name == "smlib_blend_setback_open"), "{report:?}"); + let on_cpp = crate::route::Op::Blend.backend() == crate::route::Backend::Smlib; + assert!(!on_cpp || report.rows.iter().any(|r| r.category == "smlib" && r.name == "smlib_blend_setback_open"), "{report:?}"); shot(&open, "setback_open"); assert_eq!(open.counts().unwrap(), [9, 30, 22]); assert!(!open.is_manifold_solid().unwrap()); diff --git a/crates/smlib/src/pcurves.rs b/crates/smlib/src/pcurves.rs index 3fd64a8f7..19554749d 100644 --- a/crates/smlib/src/pcurves.rs +++ b/crates/smlib/src/pcurves.rs @@ -22,7 +22,7 @@ impl Trims for SmlibTrims { fn trims(face: &TrimFace<'_>) -> Result>, String> { let (record, bare) = sheet(face)?; let mut arrays = crate::import::arrays_with_bare_uses(&record, &bare).map_err(|e| e.to_string())?; - let import = |a: &crate::import::Arrays| crate::flat::Flat::from_arrays(a).and_then(|f| f.import()).map_err(|e| e.to_string()); + let import = |a: &crate::import::Arrays| crate::Brep::from_arrays(a).map_err(|e| e.to_string()); let mut body = import(&arrays)?; if cover_gaps(&body, face, &bare, &mut arrays)? { body = import(&arrays)?; diff --git a/crates/smlib/src/route.rs b/crates/smlib/src/route.rs index 188087a32..ad461d0f6 100644 --- a/crates/smlib/src/route.rs +++ b/crates/smlib/src/route.rs @@ -12,7 +12,7 @@ //! //! `SOLIDCRAFT_KERNEL_ROUTES==[,…]` (for example `boolean=smlib,measure=smlib`) then //! moves single families on top of that choice, so the rig can score one family at a time -//! ([`Overrides`]). `.smb` files stay on SMLib whatever either says. +//! ([`Overrides`]). use std::sync::OnceLock; use std::sync::atomic::{AtomicU8, Ordering}; @@ -70,7 +70,7 @@ pub enum Op { Ssi, /// Sheet metal: flanges and flat patterns. Flat, - /// Native `.smb` files (C++ only: solidcore reads no SMLib file). + /// Native `.smb` files, which both kernels read and write. File, } @@ -139,15 +139,18 @@ impl Op { | Op::Sweep | Op::History | Op::Ssi - | Op::Flat => Backend::Solidcore, - Op::File => Backend::Smlib, + | Op::Flat + | Op::File => Backend::Solidcore, } } /// The kernel this family runs on now: `SOLIDCRAFT_KERNEL_ROUTES` for it, else - /// `SOLIDCRAFT_KERNEL`, else the preference, else [`Op::route`]. `.smb` files stay on SMLib - /// whatever is chosen. + /// `SOLIDCRAFT_KERNEL`, else the preference, else [`Op::route`]. pub fn backend(self) -> Backend { + #[cfg(test)] + if ON_CPP.with(std::cell::Cell::get) { + return Backend::Smlib; + } self.backend_under(choice()) } @@ -158,11 +161,8 @@ impl Op { } /// The kernel this family runs on under `c` with the overrides `o`, read from neither the - /// environment nor the preference. `.smb` files stay on SMLib whatever is chosen. + /// environment nor the preference. pub fn backend_with(self, c: Choice, o: &Overrides) -> Backend { - if self == Op::File { - return Backend::Smlib; - } if let Some(b) = o.get(self) { return b; } @@ -173,6 +173,26 @@ impl Op { } } +#[cfg(test)] +thread_local! { + /// Tests: this thread's operations run on the C++ kernel whatever the routing. + static ON_CPP: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Tests that exercise the C++ kernel opt in: until the guard drops, this thread's operations run +/// on it. Thread by thread, so that the other tests in the binary stay on the table's kernel. +#[cfg(test)] +pub(crate) fn on_cpp() -> impl Drop { + struct Guard; + impl Drop for Guard { + fn drop(&mut self) { + ON_CPP.with(|c| c.set(false)); + } + } + ON_CPP.with(|c| c.set(true)); + Guard +} + /// What answers the operations: the routing table, or one kernel for all of them. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum Choice { @@ -244,7 +264,7 @@ impl Overrides { /// A `SOLIDCRAFT_KERNEL_ROUTES` value: comma-separated `=`, spaces /// around each part allowed, a later item for the same family winning. Returns the overrides /// and a warning for each item ignored: an unknown family or kernel, an empty or overlong - /// item, `file` (always SMLib), items past [`Overrides::MAX_ITEMS`], or a whole value longer + /// item, items past [`Overrides::MAX_ITEMS`], or a whole value longer /// than [`Overrides::MAX_LEN`]. pub fn parse(text: &str) -> (Overrides, Vec) { let mut o = Overrides::NONE; @@ -277,10 +297,6 @@ impl Overrides { warnings.push(format!("`{shown}`: `{}` is not smlib or solidcore; ignored", backend.trim())); continue; }; - if op == Op::File { - warnings.push(format!("`{shown}`: .smb files stay on smlib; ignored")); - continue; - } if let Some(slot) = o.0.get_mut(op.index()) { *slot = Some(backend); } @@ -344,9 +360,10 @@ mod tests { assert_eq!(Choice::from_id("truck"), None); } + /// Every family, native files too, is on solidcore unless the C++ kernel is asked for. #[test] - fn files_stay_on_smlib() { - assert_eq!(Op::File.backend(), Backend::Smlib); + fn the_table_puts_every_family_on_solidcore() { + assert!(Op::ALL.iter().all(|op| op.route() == Backend::Solidcore)); } /// Each choice sends the families where it says, read without setting the process-wide @@ -355,11 +372,10 @@ mod tests { #[test] fn each_choice_routes_every_family_without_touching_the_preference() { for op in Op::ALL { - let want = |b: Backend| if op == Op::File { Backend::Smlib } else { b }; let none = &Overrides::NONE; assert_eq!(op.backend_with(Choice::Routed, none), op.route(), "{op:?}"); - assert_eq!(op.backend_with(Choice::Only(Backend::Smlib), none), want(Backend::Smlib), "{op:?}"); - assert_eq!(op.backend_with(Choice::Only(Backend::Solidcore), none), want(Backend::Solidcore), "{op:?}"); + assert_eq!(op.backend_with(Choice::Only(Backend::Smlib), none), Backend::Smlib, "{op:?}"); + assert_eq!(op.backend_with(Choice::Only(Backend::Solidcore), none), Backend::Solidcore, "{op:?}"); assert_eq!(op.backend_under(Choice::Routed), op.backend_with(Choice::Routed, overrides()), "{op:?}"); } } @@ -383,12 +399,14 @@ mod tests { assert_eq!(o.iter().collect::>(), [(Op::Measure, Backend::Solidcore), (Op::Boolean, Backend::Solidcore)]); for op in Op::ALL { let moved = matches!(op, Op::Boolean | Op::Measure); - let want = if moved { Backend::Solidcore } else { op.route() }; - assert_eq!(op.backend_with(Choice::Routed, &o), want, "{op:?}"); + assert_eq!(op.backend_with(Choice::Routed, &o), Backend::Solidcore, "{op:?}"); let want = if moved { Backend::Solidcore } else { Backend::Smlib }; assert_eq!(op.backend_with(Choice::Only(Backend::Smlib), &o), want, "{op:?}"); } - // Back to SMLib under an all-solidcore choice; the later item wins. + // Back to SMLib under the table; the later item wins. + let (o, _) = Overrides::parse("file=smlib"); + assert_eq!(Op::File.backend_with(Choice::Routed, &o), Backend::Smlib); + assert_eq!(Op::Sweep.backend_with(Choice::Routed, &o), Backend::Solidcore); let (o, _) = Overrides::parse("check=solidcore,check=smlib"); assert_eq!(Op::Check.backend_with(Choice::Only(Backend::Solidcore), &o), Backend::Smlib); assert_eq!(Op::Sweep.backend_with(Choice::Only(Backend::Solidcore), &o), Backend::Solidcore); @@ -399,10 +417,9 @@ mod tests { /// nothing panics or reads past the caps. #[test] fn overrides_ignore_bad_items_with_a_warning() { - let (o, w) = Overrides::parse("file=solidcore,truck=solidcore,boolean=truck,,=,boolean,BOOLEAN=solidcore,blend=solidcore=x,sweep=solidcore"); + let (o, w) = Overrides::parse("truck=solidcore,boolean=truck,,=,boolean,BOOLEAN=solidcore,blend=solidcore=x,sweep=solidcore"); assert_eq!(o.iter().collect::>(), [(Op::Sweep, Backend::Solidcore)]); - assert_eq!(w.len(), 8, "{w:?}"); - assert_eq!(Op::File.backend_with(Choice::Routed, &o), Backend::Smlib); + assert_eq!(w.len(), 7, "{w:?}"); let (o, w) = Overrides::parse(&"x".repeat(Overrides::MAX_LEN + 1)); assert!(o.is_empty() && w.len() == 1, "{w:?}"); let (o, w) = Overrides::parse(&format!("{}=solidcore,blend=solidcore", "a".repeat(200))); diff --git a/crates/smlib/src/split.rs b/crates/smlib/src/split.rs index 692a7b1f9..6452772a5 100644 --- a/crates/smlib/src/split.rs +++ b/crates/smlib/src/split.rs @@ -20,7 +20,7 @@ impl Brep { } init()?; let faces: Vec = faces.iter().map(|f| i64::try_from(*f).map_err(|_| Error::Argument)).collect::>()?; - let handles: Vec<&ffi::ssi::SurfaceHandle> = tools.iter().map(|t| t.handle()).collect(); + let handles: Vec<&ffi::ssi::SurfaceHandle> = tools.iter().map(|t| t.handle()).collect::>()?; match ffi::split::split_faces(self.cpp()?, &faces, &handles) { Ok((h, made)) => Ok(Some((Brep::made(h), made.into_iter().map(|m| usize::try_from(m).unwrap_or(0)).collect()))), Err(ffi::ops::ERR_NO_CUT) => Ok(None), @@ -38,7 +38,7 @@ impl Brep { return core::split::split_body(self.core()?, tool.spec()).map(|r| r.map(|(b, f)| (Brep::made_core(b), Brep::made_core(f)))); } init()?; - match ffi::split::split_body(self.cpp()?, tool.handle()) { + match ffi::split::split_body(self.cpp()?, tool.handle()?) { Ok((b, f)) => Ok(Some((Brep::made(b), Brep::made(f)))), Err(ffi::ops::ERR_NO_CUT) => Ok(None), Err(s) => Err(error(s)), diff --git a/crates/smlib/src/ssi.rs b/crates/smlib/src/ssi.rs index 6442e8cb5..aeed1c8f2 100644 --- a/crates/smlib/src/ssi.rs +++ b/crates/smlib/src/ssi.rs @@ -8,16 +8,19 @@ use solidcraft_geom::brep as b; -use crate::{Error, Result, error, ffi, init}; +use std::sync::OnceLock; -/// A surface with its UV domain, owned on the C side; with the description it was made from, from -/// which solidcore makes its own ([`crate::core::split`]). +use crate::{Error, Result, error, ffi, init, route}; + +/// A surface with its UV domain: the description it was made from, from which solidcore makes its +/// own ([`crate::core::split`]), and the C side's, made when the C++ kernel needs it. pub struct Surface { - handle: ffi::ssi::SurfaceHandle, + handle: OnceLock>, spec: Spec, } -/// What a [`Surface`] was made from: its constructor's arguments, which the C API has checked. +/// What a [`Surface`] was made from: its constructor's arguments, checked as the C API checks them +/// ([`Spec::check`]). #[derive(Clone, Debug, PartialEq)] pub(crate) enum Spec { Plane { origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], u: [f64; 2], v: [f64; 2] }, @@ -38,49 +41,161 @@ fn int(n: usize) -> Result { i32::try_from(n).map_err(|_| Error::Argument) } +/// The largest coordinate, degree and control net the C API takes (`SMLIB_SURFACE_MAX_*`). +const MAX_COORD: f64 = 1e8; +const MAX_DEGREE: usize = 25; +const MAX_POLES: usize = 1_000_000; + +fn bounded(v: &[f64]) -> bool { + v.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) +} + +/// Two non-zero axes that are not (nearly) parallel. +fn axes(x: &[f64; 3], y: &[f64; 3]) -> bool { + let len = |a: &[f64; 3]| (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt(); + let c = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]]; + bounded(x) && bounded(y) && len(x) > 1e-12 && len(y) > 1e-12 && len(&c) > 1e-9 * len(x) * len(y) +} + +/// An increasing interval inside `[lo, hi]` spanning at most `span`. +fn range(r: &[f64; 2], lo: f64, hi: f64, span: f64) -> bool { + bounded(r) && r[0] < r[1] && r[0] >= lo && r[1] <= hi && r[1] - r[0] <= span +} + +fn length(x: f64) -> bool { + x.is_finite() && x > 1e-9 && x <= MAX_COORD +} + +/// A knot vector of n + p + 1 non-decreasing values with a non-empty domain `[k[p], k[n]]`, no +/// interior knot repeated more than p times and no end knot more than p + 1. +fn knots(k: &[f64], n: usize, p: usize) -> bool { + if k.len() != n + p + 1 || !bounded(k) || k.windows(2).any(|w| w[1] < w[0]) { + return false; + } + let (Some(lo), Some(hi)) = (k.get(p).copied(), k.get(n).copied()) else { return false }; + let mut run = 1; + for w in k.windows(2) { + run = if w[1] == w[0] { run + 1 } else { 1 }; + if run > p + 1 || (run > p && w[1] > lo && w[1] < hi) { + return false; + } + } + lo < hi +} + +impl Spec { + /// The checks each of the C API's constructors makes of its arguments, so that a surface is + /// refused alike on either kernel, and without the C++ kernel. + fn check(&self) -> Result<()> { + let whole = |r: &[f64; 2]| range(r, -MAX_COORD, MAX_COORD, 2.0 * MAX_COORD); + let turn = |r: &[f64; 2]| range(r, -360.0, 360.0, 360.0); + let ok = match self { + Spec::Plane { origin, xaxis, yaxis, u, v } => bounded(origin) && axes(xaxis, yaxis) && whole(u) && whole(v), + Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height } => { + bounded(origin) && axes(xaxis, yaxis) && length(*radius) && turn(angle_deg) && range(height, -MAX_COORD, MAX_COORD, MAX_COORD) + } + Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height } => { + bounded(apex) + && axes(xaxis, yaxis) + && (0.01..=89.0).contains(half_angle_deg) + && range(height, 0.0, MAX_COORD, MAX_COORD) + && height[1] - height[0] > 1e-9 + } + Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg } => { + bounded(center) && axes(xaxis, yaxis) && length(*radius) && turn(lon_deg) && range(lat_deg, -90.0, 90.0, 180.0) + } + Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg } => { + bounded(center) + && axes(xaxis, yaxis) + && length(*major_radius) + && length(*minor_radius) + && minor_radius < major_radius + && turn(major_deg) + && turn(minor_deg) + } + Spec::Nurbs { degree: [p, q], nu, nv, knots_u, knots_v, points, weights } => { + (1..=MAX_DEGREE).contains(p) + && (1..=MAX_DEGREE).contains(q) + && *nu > *p + && *nv > *q + && nu.checked_mul(*nv).is_some_and(|n| n <= MAX_POLES && points.len() == n) + && knots(knots_u, *nu, *p) + && knots(knots_v, *nv, *q) + && points.iter().all(|c| bounded(c)) + && weights.as_ref().is_none_or(|w| w.len() == points.len() && w.iter().all(|x| (1e-6..=1e6).contains(x))) + } + }; + if ok { Ok(()) } else { Err(Error::Argument) } + } + + /// The C side's surface. + fn on_cpp(&self) -> Result { + init()?; + match self { + Spec::Plane { origin, xaxis, yaxis, u, v } => ffi::ssi::plane(origin, xaxis, yaxis, u, v), + Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height } => { + ffi::ssi::cylinder(origin, xaxis, yaxis, *radius, angle_deg, height) + } + Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height } => ffi::ssi::cone(apex, xaxis, yaxis, *half_angle_deg, height), + Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg } => ffi::ssi::sphere(center, xaxis, yaxis, *radius, lon_deg, lat_deg), + Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg } => { + ffi::ssi::torus(center, xaxis, yaxis, *major_radius, *minor_radius, major_deg, minor_deg) + } + Spec::Nurbs { degree, nu, nv, knots_u, knots_v, points, weights } => { + let flat: Vec = points.iter().flatten().copied().collect(); + ffi::ssi::nurbs([int(degree[0])?, int(degree[1])?], int(*nu)?, int(*nv)?, knots_u, knots_v, &flat, weights.as_deref()) + } + } + .map_err(error) + } +} + +/// Whether intersections run on the C++ kernel ([`route::Op::Ssi`]). +fn ssi_on_cpp() -> bool { + route::Op::Ssi.backend() == route::Backend::Smlib +} + impl Surface { - pub(crate) fn handle(&self) -> &ffi::ssi::SurfaceHandle { - &self.handle + /// The C side's surface, made the first time the C++ kernel needs it. + pub(crate) fn handle(&self) -> Result<&ffi::ssi::SurfaceHandle> { + self.handle.get_or_init(|| self.spec.on_cpp()).as_ref().map_err(Clone::clone) } pub(crate) fn spec(&self) -> &Spec { &self.spec } - fn made(handle: ffi::ssi::SurfaceHandle, spec: Spec) -> Surface { - Surface { handle, spec } + /// A surface from its checked description. With a family that takes surfaces on the C++ + /// kernel, its side is made now, so that what it refuses is refused here. + fn made(spec: Spec) -> Result { + spec.check()?; + let s = Surface { handle: OnceLock::new(), spec }; + if ssi_on_cpp() || route::Op::Split.backend() == route::Backend::Smlib { + s.handle()?; + } + Ok(s) } /// `origin + u*x + v*y` (x, y the axes made unit), for u in `u`, v in `v`. pub fn plane(origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], u: [f64; 2], v: [f64; 2]) -> Result { - init()?; - ffi::ssi::plane(&origin, &xaxis, &yaxis, &u, &v).map(|h| Surface::made(h, Spec::Plane { origin, xaxis, yaxis, u, v })).map_err(error) + Surface::made(Spec::Plane { origin, xaxis, yaxis, u, v }) } /// A cylinder of `radius` about the axis through `origin` along `xaxis × yaxis`, angle /// `angle_deg` from `xaxis` towards `yaxis`, for heights `height` measured from `origin`. pub fn cylinder(origin: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, angle_deg: [f64; 2], height: [f64; 2]) -> Result { - init()?; - ffi::ssi::cylinder(&origin, &xaxis, &yaxis, radius, &angle_deg, &height) - .map(|h| Surface::made(h, Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height })) - .map_err(error) + Surface::made(Spec::Cylinder { origin, xaxis, yaxis, radius, angle_deg, height }) } /// A full cone with its apex at `apex` along `xaxis × yaxis`, radius `h * tan(half_angle_deg)` /// at distance h along the axis, for h in `height` (from 0: through the apex). pub fn cone(apex: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], half_angle_deg: f64, height: [f64; 2]) -> Result { - init()?; - ffi::ssi::cone(&apex, &xaxis, &yaxis, half_angle_deg, &height) - .map(|h| Surface::made(h, Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height })) - .map_err(error) + Surface::made(Spec::Cone { apex, xaxis, yaxis, half_angle_deg, height }) } /// A sphere of `radius` at `center`, over longitudes `lon_deg` and latitudes `lat_deg`. pub fn sphere(center: [f64; 3], xaxis: [f64; 3], yaxis: [f64; 3], radius: f64, lon_deg: [f64; 2], lat_deg: [f64; 2]) -> Result { - init()?; - ffi::ssi::sphere(¢er, &xaxis, &yaxis, radius, &lon_deg, &lat_deg) - .map(|h| Surface::made(h, Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg })) - .map_err(error) + Surface::made(Spec::Sphere { center, xaxis, yaxis, radius, lon_deg, lat_deg }) } /// A ring torus at `center` about `xaxis × yaxis`, `major_deg` round the axis and `minor_deg` @@ -94,10 +209,7 @@ impl Surface { major_deg: [f64; 2], minor_deg: [f64; 2], ) -> Result { - init()?; - ffi::ssi::torus(¢er, &xaxis, &yaxis, major_radius, minor_radius, &major_deg, &minor_deg) - .map(|h| Surface::made(h, Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg })) - .map_err(error) + Surface::made(Spec::Torus { center, xaxis, yaxis, major_radius, minor_radius, major_deg, minor_deg }) } /// A (rational) B-spline surface: `nu × nv` control points, point (i, j) (i along u) at @@ -111,22 +223,15 @@ impl Surface { points: &[[f64; 3]], weights: Option<&[f64]>, ) -> Result { - init()?; - let flat: Vec = points.iter().flatten().copied().collect(); - ffi::ssi::nurbs([int(degree[0])?, int(degree[1])?], int(nu)?, int(nv)?, knots_u, knots_v, &flat, weights) - .map(|h| { - let spec = Spec::Nurbs { - degree, - nu, - nv, - knots_u: knots_u.to_vec(), - knots_v: knots_v.to_vec(), - points: points.to_vec(), - weights: weights.map(<[f64]>::to_vec), - }; - Surface::made(h, spec) - }) - .map_err(error) + Surface::made(Spec::Nurbs { + degree, + nu, + nv, + knots_u: knots_u.to_vec(), + knots_v: knots_v.to_vec(), + points: points.to_vec(), + weights: weights.map(<[f64]>::to_vec), + }) } /// A schema 4 record surface over the parameter box `domain` (`[[u0, u1], [v0, v1]]`, the @@ -185,12 +290,18 @@ impl Surface { /// The UV domain the intersection runs within, as `[u0, u1, v0, v1]`. pub fn domain(&self) -> Result<[f64; 4]> { - ffi::ssi::domain(&self.handle).map_err(error) + if !ssi_on_cpp() { + return Err(Error::NotOnSolidcore("a surface's SSI domain")); + } + ffi::ssi::domain(self.handle()?).map_err(error) } /// The surface's point at (u, v). pub fn evaluate(&self, u: f64, v: f64) -> Result<[f64; 3]> { - ffi::ssi::evaluate(&self.handle, u, v).map_err(error) + if !ssi_on_cpp() { + return Err(Error::NotOnSolidcore("evaluating an SSI surface")); + } + ffi::ssi::evaluate(self.handle()?, u, v).map_err(error) } } @@ -322,7 +433,10 @@ fn uv(r: &ffi::ssi::ResultHandle, i: i32, which: i32) -> Result Result { - let r = ffi::ssi::ssi(&a.handle, &b.handle, method.code(), approx_tol).map_err(error)?; + if !ssi_on_cpp() { + return Err(Error::NotOnSolidcore("surface/surface intersection through the kernel API")); + } + let r = ffi::ssi::ssi(a.handle()?, b.handle()?, method.code(), approx_tol).map_err(error)?; let n = ffi::ssi::curve_count(&r).map_err(error)?; let mut curves = Vec::new(); for i in 0..n { @@ -352,6 +466,7 @@ mod tests { /// A plane through a sphere's centre: one great circle. #[test] fn plane_through_sphere_is_a_circle() { + let _cpp = route::on_cpp(); let z = [0.0, 0.0, 1.0]; let (x, y) = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]); let plane = Surface::plane([0.0; 3], x, y, [-2.0, 2.0], [-2.0, 2.0]); @@ -373,15 +488,39 @@ mod tests { } } + /// Refused here, before any kernel: alike on either, and with no C++ kernel. #[test] fn bad_input_is_an_argument_error() { - match Surface::plane([0.0; 3], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0], [0.0, 1.0]) { - Err(Error::NotBuilt) => {} - r => assert_eq!(r.err(), Some(Error::Argument)), - } - match Surface::nurbs([1, 1], 2, 2, &[0.0, 0.0, 1.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 3], None) { - Err(Error::NotBuilt) => {} - r => assert_eq!(r.err(), Some(Error::Argument)), + let (x, y) = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]); + let refused = [ + Surface::plane([0.0; 3], x, x, [0.0, 1.0], [0.0, 1.0]), + Surface::plane([0.0; 3], x, y, [1.0, 0.0], [0.0, 1.0]), + Surface::plane([f64::NAN; 3], x, y, [0.0, 1.0], [0.0, 1.0]), + Surface::cylinder([0.0; 3], x, y, 0.0, [0.0, 360.0], [0.0, 1.0]), + Surface::cone([0.0; 3], x, y, f64::NAN, [0.0, 1.0]), + Surface::sphere([0.0; 3], x, y, 1.0, [0.0, 360.0], [-91.0, 90.0]), + Surface::torus([0.0; 3], x, y, 1.0, 2.0, [0.0, 360.0], [0.0, 360.0]), + Surface::nurbs([1, 1], 2, 2, &[0.0, 0.0, 1.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 3], None), + Surface::nurbs([1, 1], 2, 2, &[0.0, 0.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 4], None), + Surface::nurbs([1, 1], 2, 2, &[0.0, 0.0, 1.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 4], Some(&[0.0; 4])), + Surface::nurbs([0, 1], 2, 2, &[0.0, 0.0, 1.0], &[0.0, 0.0, 1.0, 1.0], &[[0.0; 3]; 4], None), + ]; + for (i, r) in refused.iter().enumerate() { + assert_eq!(r.as_ref().err(), Some(&Error::Argument), "{i}"); } } + + /// On solidcore a surface needs no C++ kernel, and the operations only the C API has say they + /// are not supported; none falls back. + #[test] + fn intersecting_on_solidcore_says_it_is_not_supported() { + if ssi_on_cpp() { + return; + } + let (x, y) = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]); + let s = Surface::plane([0.0; 3], x, y, [0.0, 1.0], [0.0, 1.0]).unwrap(); + assert!(matches!(intersect(&s, &s, Method::Global, 1e-6), Err(Error::NotOnSolidcore(_)))); + assert!(matches!(s.domain(), Err(Error::NotOnSolidcore(_)))); + assert!(matches!(s.evaluate(0.5, 0.5), Err(Error::NotOnSolidcore(_)))); + } } diff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rs index 720af08e6..9872e65d1 100644 --- a/crates/smlib/src/tests.rs +++ b/crates/smlib/src/tests.rs @@ -27,9 +27,75 @@ fn bad_arguments_are_errors() { assert_eq!(b.volume(f64::INFINITY).unwrap_err(), Error::Argument); } +/// `.smb` files on solidcore, in both forms and with a curved body, and a missing or corrupt file +/// is an error, not a panic. +#[test] +fn solidcore_reads_back_the_files_it_writes() { + use std::f64::consts::PI; + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-core-file-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cylinder = core::make_cylinder([1.0, 2.0, 3.0], 2.0, 5.0).map(Brep::made_core).unwrap(); + for ascii in [false, true] { + let path = dir.join(format!("cylinder-{ascii}.smb")); + core::file::write(cylinder.core().unwrap(), &path, ascii).unwrap(); + let back = core::file::read(&path, ascii).map(Brep::made_core).unwrap(); + let v = core::volume(back.core().unwrap(), 1e-7).unwrap(); + assert!((v - PI * 4.0 * 5.0).abs() < 1e-5, "ascii {ascii}: {v}"); + assert_eq!(core::counts(back.core().unwrap()).unwrap(), core::counts(cylinder.core().unwrap()).unwrap(), "ascii {ascii}"); + } + let body = cylinder.core().unwrap(); + assert!(core::file::write(body, &dir.join("missing/x.smb"), false).is_err()); + assert!(core::file::read(&dir.join("missing.smb"), false).is_err()); + let junk = dir.join("junk.smb"); + std::fs::write(&junk, b"not a B-rep file").unwrap(); + assert!(core::file::read(&junk, false).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// ASCII that is no B-rep file is refused like binary. It comes back as an empty body today: +/// default-solidcore/bugs/ascii-junk-reads-as-empty.md. +#[test] +#[ignore = "solidcore: an ASCII file of junk reads as an empty B-rep instead of an error"] +fn solidcore_refuses_an_ascii_file_of_junk() { + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-core-junk-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let junk = dir.join("junk.smb"); + std::fs::write(&junk, b"not a B-rep file").unwrap(); + let r = core::file::read(&junk, true); + let _ = std::fs::remove_dir_all(&dir); + assert!(r.is_err()); +} + +/// A file either kernel wrote reads on the other, with the same measure. +#[cfg(feature = "native")] +#[test] +fn each_kernel_reads_the_files_of_the_other() { + use std::f64::consts::PI; + let dir = std::env::temp_dir().join(format!("solidcraft-smlib-cross-file-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let want = PI * 4.0 * 5.0; + for ascii in [false, true] { + let from_core = dir.join(format!("core-{ascii}.smb")); + let body = core::make_cylinder([0.0; 3], 2.0, 5.0).unwrap(); + core::file::write(&body, &from_core, ascii).unwrap(); + crate::init().unwrap(); + let on_cpp = ffi::read(&c_path(&from_core).unwrap(), ascii).map(Brep::made).unwrap(); + let v = ffi::volume(on_cpp.cpp().unwrap(), 1e-7).unwrap(); + assert!((v - want).abs() < 1e-5, "C++ on solidcore's file, ascii {ascii}: {v}"); + let from_cpp = dir.join(format!("cpp-{ascii}.smb")); + let cpp = ffi::make_cylinder(&[0.0; 3], 2.0, 5.0).map(Brep::made).unwrap(); + crate::check(ffi::write(cpp.cpp().unwrap(), &c_path(&from_cpp).unwrap(), ascii)).unwrap(); + let on_core = core::file::read(&from_cpp, ascii).unwrap(); + let v = core::volume(&on_core, 1e-7).unwrap(); + assert!((v - want).abs() < 1e-5, "solidcore on C++'s file, ascii {ascii}: {v}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[cfg(feature = "native")] #[test] fn native_files_round_trip_and_failures_dump_their_inputs() { + let _cpp = route::on_cpp(); let dir = std::env::temp_dir().join(format!("solidcraft-smlib-test-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let b = Brep::make_box([0.0; 3], [2.0, 3.0, 4.0]).unwrap(); @@ -92,6 +158,7 @@ fn call_lines_give_the_function_and_the_c_api_time() { #[cfg(feature = "native")] #[test] fn every_call_is_a_profiler_span_timed_by_the_c_api() { + let _cpp = route::on_cpp(); solidcraft_profile::set_enabled(true); let mark = solidcraft_profile::mark(); // the C API's own box, whatever `Op::Primitive` routes to diff --git a/crates/smlib/src/trim.rs b/crates/smlib/src/trim.rs index 6c880d390..0583a9797 100644 --- a/crates/smlib/src/trim.rs +++ b/crates/smlib/src/trim.rs @@ -66,6 +66,9 @@ impl Brep { /// A point inside each face, in SMLib's face order: on the face's surface, inside its trims /// (`SmFace::CalculateAnInternalPoint`). pub fn face_points(&self) -> Result> { + if route::Op::Split.backend() == route::Backend::Solidcore { + return core::trim::face_points(self.core()?); + } init()?; let [faces, _, _] = self.counts()?; ffi::trim::face_points(self.cpp()?, faces).map_err(error) diff --git a/crates/smlib/tests/ssi_corpus.rs b/crates/smlib/tests/ssi_corpus.rs index d75ce76ae..7715eca52 100644 --- a/crates/smlib/tests/ssi_corpus.rs +++ b/crates/smlib/tests/ssi_corpus.rs @@ -587,6 +587,8 @@ fn runner_output( #[test] fn smlib_global_intersect_at_1e_6() { use solidcraft_smlib::ssi::{Method, intersect}; + // This scores the C++ kernel's intersector: it opts in (this binary builds no other bodies). + solidcraft_smlib::route::set_choice(solidcraft_smlib::route::Choice::Only(solidcraft_smlib::route::Backend::Smlib)); let t0 = std::time::Instant::now(); let cases = all_cases(); // SMLib serialises its calls, so the cases run one after another; only the scoring is parallel.