SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 15/509: kernel: a side-by-side runner for truck and SMLib booleans (and 1 more)
Brennen Herbruckaf6528b420c7
diff --git a/Cargo.lock b/Cargo.lockindex af4b1e2a3c..d1b04121fa 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4418,6 +4418,7 @@ version = "0.18.1"dependencies = ["cc","log",+ "solidcraft-geom",][[package]]diff --git a/crates/kernel/examples/smlib_booleans.rs b/crates/kernel/examples/smlib_booleans.rsnew file mode 100644index 0000000000..defccf4f40--- /dev/null+++ b/crates/kernel/examples/smlib_booleans.rs@@ -0,0 +1,402 @@+//! Side-by-side booleans: truck (today's kernel) and SMLib on the same cases, compared on+//! volume, face and edge counts and history. It reports; it never changes which kernel the app+//! uses.+//!+//! ```sh+//! scripts/fetch-smlib.sh+//! cargo run --release -p solidcraft-kernel --features smlib --example smlib_booleans -- \+//! [--seeds N] [--out DIR]+//! ```+//!+//! Cases: named pairs of primitives whose results are known by hand (the ones the kernel's+//! boolean and history tests build), then `fuzz::boolean_shapes(seed)` for seeds 0..N (the+//! random pairs of `solidcraft-cli fuzz` and the robustness runs). Each case runs union,+//! intersection and cut. Writes `smlib-booleans.json` and `smlib-booleans.md` into DIR (default+//! `target/smlib-booleans`).+//!+//! SMLib runs in a child process per case (this same program, with `--smlib-case`), so a crash+//! inside it is reported as that case's result instead of ending the run.+//!+//! History is compared by its shape, since the two kernels number faces differently until the+//! SMLib export renumbers into canonical order: how many result faces are Kept, Modified, Split,+//! Merged and Generated, and how many edges come from an operand edge, are new where two faces+//! meet, or have no origin.++#[cfg(not(feature = "smlib"))]+fn main() {+ eprintln!("smlib_booleans needs SMLib: run scripts/fetch-smlib.sh, then add --features smlib");+ std::process::exit(2);+}++#[cfg(feature = "smlib")]+fn main() {+ if let Err(e) = run::main() {+ eprintln!("smlib_booleans: {e}");+ std::process::exit(1);+ }+}++#[cfg(feature = "smlib")]+mod run {+ use std::fmt::Write as _;+ use std::path::PathBuf;+ use std::time::Instant;++ use serde_json::{Value, json};+ use solidcraft_geom::brep::history::{Change, EdgeOrigin, History};+ use solidcraft_kernel::fuzz::{Shape, boolean_shapes};+ use solidcraft_kernel::{BoolOp, boolean, measure};+ use solidcraft_smlib::history::Order;++ const OPS: [BoolOp; 3] = [BoolOp::Union, BoolOp::Intersect, BoolOp::Cut];++ /// Relative volume difference that still counts as the same result: truck measures from a+ /// fine tessellation (`measure`), SMLib integrates exactly.+ const VOLUME_REL: f64 = 1e-3;++ /// What one kernel made of one case: its volume, face and edge counts, history shape and+ /// time, or why it made nothing.+ #[derive(Clone, Debug, Default)]+ struct Outcome {+ error: Option<String>,+ empty: bool,+ volume: f64,+ faces: usize,+ edges: usize,+ history: Option<HistoryShape>,+ ms: f64,+ }++ /// A history's shape: faces Kept, Modified, Split, Merged, Generated; edges from an operand+ /// edge, new where two faces meet, without origin.+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+ struct HistoryShape {+ faces: [usize; 5],+ edges: [usize; 3],+ }++ impl HistoryShape {+ fn of(h: &History) -> HistoryShape {+ let mut s = HistoryShape::default();+ for f in &h.faces {+ let i = match f.change {+ Change::Kept => 0,+ Change::Modified => 1,+ Change::Split => 2,+ Change::Merged => 3,+ Change::Generated => 4,+ };+ if let Some(n) = s.faces.get_mut(i) {+ *n += 1;+ }+ }+ for e in &h.edges {+ let i = if e.origins.iter().any(|o| matches!(o, EdgeOrigin::Edge { .. })) {+ 0+ } else if e.origins.is_empty() {+ 2+ } else {+ 1+ };+ if let Some(n) = s.edges.get_mut(i) {+ *n += 1;+ }+ }+ s+ }++ fn text(&self) -> String {+ let [k, m, s, g, n] = self.faces;+ let [e, meet, none] = self.edges;+ format!("K{k} M{m} S{s} J{g} G{n} / e{e} x{meet} -{none}")+ }+ }++ fn op_name(op: BoolOp) -> &'static str {+ match op {+ BoolOp::Union => "union",+ BoolOp::Intersect => "intersect",+ BoolOp::Cut => "cut",+ }+ }++ fn truck(a: &Shape, b: &Shape, op: BoolOp) -> Outcome {+ let t0 = Instant::now();+ let mut o = Outcome::default();+ let result = a.body().and_then(|ba| b.body().map(|bb| (ba, bb))).and_then(|(ba, bb)| boolean(&ba, &bb, op));+ o.ms = t0.elapsed().as_secs_f64() * 1e3;+ match result {+ Err(e) => o.error = Some(e.to_string()),+ Ok(None) => o.empty = true,+ Ok(Some(body)) => {+ o.faces = body.face_count();+ o.edges = body.edge_count();+ o.history = body.history().map(HistoryShape::of);+ match measure(&body) {+ Ok(m) => o.volume = m.volume,+ Err(e) => o.error = Some(format!("measure: {e}")),+ }+ }+ }+ o+ }++ fn smlib(a: &Shape, b: &Shape, op: BoolOp) -> Outcome {+ let t0 = Instant::now();+ let mut o = Outcome::default();+ let result = (|| -> Result<Option<solidcraft_smlib::Brep>, String> {+ let ta = side::shape(a)?.tagged(0).map_err(|e| e.to_string())?;+ let tb = side::shape(b)?.tagged(1).map_err(|e| e.to_string())?;+ side::boolean(&ta, &tb, op)+ })();+ o.ms = t0.elapsed().as_secs_f64() * 1e3;+ match result {+ Err(e) => o.error = Some(e),+ Ok(None) => o.empty = true,+ Ok(Some(r)) => {+ let counts = r.counts().map_err(|e| e.to_string());+ let volume = r.volume(1e-6).map_err(|e| e.to_string());+ let history = r+ .history()+ .map_err(|e| e.to_string())+ .and_then(|raw| raw.history(&[Order::default(), Order::default()], &Order::default()).map_err(|e| e.to_string()));+ match (counts, volume) {+ (Ok([f, e, _]), Ok(v)) => {+ o.faces = f;+ o.edges = e;+ o.volume = v;+ }+ (Err(e), _) | (_, Err(e)) => o.error = Some(e),+ }+ o.history = history.ok().as_ref().map(HistoryShape::of);+ }+ }+ o+ }++ /// The SMLib side, through `solidcraft-smlib`. Primitives and booleans arrive with the+ /// operation shims (smlib_primitives.cpp, smlib_ops.cpp); until a call exists it answers+ /// "not supported yet" and the report counts the case as not run on SMLib.+ mod side {+ use solidcraft_kernel::BoolOp;+ use solidcraft_kernel::fuzz::Shape;+ use solidcraft_smlib::Brep;++ fn not_yet(what: &str) -> String {+ format!("not supported yet: {what} through the SMLib C API")+ }++ pub fn shape(s: &Shape) -> Result<Brep, String> {+ match s {+ Shape::Box { a, b } => Brep::make_box(*a, [b[0] - a[0], b[1] - a[1], b[2] - a[2]]).map_err(|e| e.to_string()),+ Shape::Cylinder { .. } => Err(not_yet("cylinder")),+ Shape::Sphere { .. } => Err(not_yet("sphere")),+ Shape::Torus { .. } => Err(not_yet("torus")),+ }+ }++ /// `a op b`; `None` when the result is empty.+ pub fn boolean(_a: &Brep, _b: &Brep, op: BoolOp) -> Result<Option<Brep>, String> {+ Err(not_yet(match op {+ BoolOp::Union => "union",+ BoolOp::Intersect => "intersection",+ BoolOp::Cut => "cut",+ }))+ }+ }++ /// Pairs whose results are known by hand.+ fn named() -> Vec<(String, Shape, Shape)> {+ let bx = |a: [f64; 3], b: [f64; 3]| Shape::Box { a, b };+ let z = [0.0, 0.0, 1.0];+ vec![+ ("overlapping boxes".into(), bx([0.0; 3], [10.0; 3]), bx([5.0; 3], [15.0; 3])),+ ("boxes sharing faces".into(), bx([0.0; 3], [10.0; 3]), bx([5.0, 0.0, 0.0], [15.0, 10.0, 10.0])),+ ("boxes apart".into(), bx([0.0; 3], [10.0; 3]), bx([20.0, 0.0, 0.0], [30.0, 10.0, 10.0])),+ ("slot through a bar".into(), bx([0.0; 3], [30.0, 10.0, 10.0]), bx([10.0, -1.0, -1.0], [20.0, 11.0, 11.0])),+ ("pocket".into(), bx([0.0; 3], [10.0; 3]), bx([3.0; 3], [7.0, 7.0, 23.0])),+ ("hole through a box".into(), bx([0.0; 3], [10.0; 3]), Shape::Cylinder { base: [5.0, 5.0, -5.0], axis: z, radius: 2.0, height: 20.0 }),+ (+ "crossing cylinders".into(),+ Shape::Cylinder { base: [0.0, 0.0, -10.0], axis: z, radius: 4.0, height: 20.0 },+ Shape::Cylinder { base: [-10.0, 0.0, 0.0], axis: [1.0, 0.0, 0.0], radius: 3.0, height: 20.0 },+ ),+ ("sphere into a box corner".into(), bx([0.0; 3], [10.0; 3]), Shape::Sphere { center: [10.0; 3], radius: 5.0 }),+ (+ "torus around a post".into(),+ Shape::Cylinder { base: [0.0; 3], axis: z, radius: 3.0, height: 10.0 },+ Shape::Torus { center: [0.0, 0.0, 5.0], major: 4.0, minor: 2.0 },+ ),+ ]+ }++ fn outcome_from_json(v: &Value) -> Outcome {+ let n = |k: &str| v.get(k).and_then(Value::as_u64).and_then(|x| usize::try_from(x).ok()).unwrap_or(0);+ let f = |k: &str| v.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN);+ let arr = |h: &Value, k: &str| -> Vec<usize> {+ h.get(k)+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(Value::as_u64).filter_map(|x| usize::try_from(x).ok()).collect())+ .unwrap_or_default()+ };+ let history = v+ .get("history")+ .filter(|h| !h.is_null())+ .and_then(|h| Some(HistoryShape { faces: arr(h, "faces").try_into().ok()?, edges: arr(h, "edges").try_into().ok()? }));+ Outcome {+ error: v.get("error").and_then(Value::as_str).map(str::to_string),+ empty: v.get("empty").and_then(Value::as_bool).unwrap_or(false),+ volume: f("volume"),+ faces: n("faces"),+ edges: n("edges"),+ history,+ ms: f("ms"),+ }+ }++ /// [`smlib`] for case `index` and operation `op`, in a child process.+ fn smlib_isolated(index: usize, op: usize, seeds: u64) -> Outcome {+ let exe = match std::env::current_exe() {+ Ok(e) => e,+ Err(e) => return Outcome { error: Some(format!("cannot start a child: {e}")), ..Outcome::default() },+ };+ let run = std::process::Command::new(exe)+ .args(["--seeds", &seeds.to_string(), "--smlib-case", &index.to_string(), &op.to_string()])+ .stderr(std::process::Stdio::null())+ .output();+ match run {+ Err(e) => Outcome { error: Some(format!("cannot start a child: {e}")), ..Outcome::default() },+ Ok(out) if !out.status.success() => Outcome { error: Some(format!("crashed ({})", out.status)), ..Outcome::default() },+ Ok(out) => match serde_json::from_slice::<Value>(&out.stdout) {+ Ok(v) => outcome_from_json(&v),+ Err(e) => Outcome { error: Some(format!("unreadable child output: {e}")), ..Outcome::default() },+ },+ }+ }++ fn outcome_json(o: &Outcome) -> Value {+ json!({+ "error": o.error,+ "empty": o.empty,+ "volume": o.volume,+ "faces": o.faces,+ "edges": o.edges,+ "history": o.history.map(|h| json!({"faces": h.faces, "edges": h.edges})),+ "ms": o.ms,+ })+ }++ /// How the two compare: "same", what differs, or why it couldn't be compared.+ fn verdict(t: &Outcome, s: &Outcome) -> (String, &'static str) {+ if s.error.as_deref().is_some_and(|e| e.starts_with("not supported yet")) {+ return ("not run on SMLib".into(), "skipped");+ }+ match (&t.error, &s.error) {+ (Some(_), Some(_)) => return ("both failed".into(), "failed"),+ (Some(_), None) => return ("truck failed, SMLib didn't".into(), "smlib-only"),+ (None, Some(_)) => return ("SMLib failed, truck didn't".into(), "truck-only"),+ (None, None) => {}+ }+ if t.empty || s.empty {+ return if t.empty == s.empty { ("both empty".into(), "same") } else { ("one empty".into(), "differs") };+ }+ let mut diffs = Vec::new();+ let scale = t.volume.abs().max(s.volume.abs()).max(1e-9);+ if (t.volume - s.volume).abs() > VOLUME_REL * scale {+ diffs.push(format!("volume {:.4} vs {:.4}", t.volume, s.volume));+ }+ if t.faces != s.faces {+ diffs.push(format!("faces {} vs {}", t.faces, s.faces));+ }+ if t.edges != s.edges {+ diffs.push(format!("edges {} vs {}", t.edges, s.edges));+ }+ match (t.history, s.history) {+ (Some(a), Some(b)) if a != b => diffs.push("history".into()),+ (None, Some(_)) => diffs.push("no truck history".into()),+ (Some(_), None) => diffs.push("no SMLib history".into()),+ _ => {}+ }+ if diffs.is_empty() { ("same".into(), "same") } else { (diffs.join(", "), "differs") }+ }++ pub fn main() -> Result<(), String> {+ let mut seeds = 32u64;+ let mut out = PathBuf::from("target/smlib-booleans");+ let mut child = None;+ let mut args = std::env::args().skip(1);+ while let Some(a) = args.next() {+ match a.as_str() {+ "--seeds" => seeds = args.next().and_then(|n| n.parse().ok()).ok_or("--seeds takes a number")?,+ "--out" => out = args.next().map(PathBuf::from).ok_or("--out takes a directory")?,+ "--smlib-case" => {+ let mut n = || args.next().and_then(|n| n.parse::<usize>().ok()).ok_or("--smlib-case takes a case and an operation");+ child = Some((n()?, n()?));+ }+ other => return Err(format!("unknown argument {other}")),+ }+ }+ let mut cases = named();+ cases.extend((0..seeds).map(|s| {+ let (a, b) = boolean_shapes(s);+ (format!("seed {s}"), a, b)+ }));+ if let Some((index, op)) = child {+ let ((_, a, b), op) = cases.get(index).zip(OPS.get(op)).ok_or("no such case")?;+ solidcraft_smlib::init().map_err(|e| e.to_string())?;+ println!("{}", outcome_json(&smlib(a, b, *op)));+ return Ok(());+ }+ solidcraft_smlib::init().map_err(|e| e.to_string())?;++ let mut rows = Vec::new();+ let mut md = String::new();+ let mut tally = std::collections::BTreeMap::<&str, usize>::new();+ for (index, (name, a, b)) in cases.iter().enumerate() {+ for (k, op) in OPS.into_iter().enumerate() {+ let t = truck(a, b, op);+ let s = smlib_isolated(index, k, seeds);+ let (what, class) = verdict(&t, &s);+ *tally.entry(class).or_default() += 1;+ let cell = |o: &Outcome| match (&o.error, o.empty) {+ (Some(e), _) => format!("error: {}", e.replace('|', "/")),+ (None, true) => "empty".into(),+ (None, false) => format!(+ "{:.3} · {}f {}e · {} · {:.0} ms",+ o.volume,+ o.faces,+ o.edges,+ o.history.map_or("no history".into(), |h| h.text()),+ o.ms+ ),+ };+ let _ = writeln!(md, "| {name} | {} | {} | {} | {what} |", op_name(op), cell(&t), cell(&s));+ rows.push(json!({+ "case": name, "a": a, "b": b, "op": op_name(op),+ "truck": outcome_json(&t), "smlib": outcome_json(&s),+ "verdict": class, "detail": what,+ }));+ }+ }++ let summary: Vec<String> = tally.iter().map(|(k, v)| format!("{k} {v}")).collect();+ let mut report = String::new();+ let _ = writeln!(report, "# Booleans: truck and SMLib side by side\n");+ let _ = writeln!(report, "{} cases × 3 operations: {}.\n", cases.len(), summary.join(", "));+ let _ = writeln!(+ report,+ "History shape: faces **K**ept, **M**odified, **S**plit, **J**oined (merged), **G**enerated; \+ edges from an operand **e**dge, new where faces meet (**x**), without origin (**-**).\n"+ );+ let _ = writeln!(report, "| case | op | truck | SMLib | verdict |\n|---|---|---|---|---|");+ report.push_str(&md);++ std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;+ let json = json!({ "cases": cases.len(), "tally": tally, "rows": rows });+ let text = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;+ std::fs::write(out.join("smlib-booleans.json"), text).map_err(|e| e.to_string())?;+ std::fs::write(out.join("smlib-booleans.md"), &report).map_err(|e| e.to_string())?;+ println!("{} cases × 3: {} ({})", cases.len(), summary.join(", "), out.display());+ Ok(())+ }+}diff --git a/crates/smlib/Cargo.toml b/crates/smlib/Cargo.tomlindex 520f14da34..ff3a8e9913 100644--- a/crates/smlib/Cargo.toml+++ b/crates/smlib/Cargo.toml@@ -26,6 +26,7 @@ native = [][dependencies]log = { workspace = true }+solidcraft-geom = { workspace = true }[build-dependencies]cc = { version = "1.2", features = ["parallel"] }diff --git a/crates/smlib/src/ffi.rs b/crates/smlib/src/ffi.rsindex 6cb72bfc02..452b066287 100644--- a/crates/smlib/src/ffi.rs+++ b/crates/smlib/src/ffi.rs@@ -179,6 +179,8 @@ mod calls {pub use calls::*;+pub mod history;+/// Where [`set_log`] sends SMLib's log lines.#[cfg(feature = "native")]static SINK: std::sync::OnceLock<fn(i32, String)> = std::sync::OnceLock::new();diff --git a/crates/smlib/src/ffi/history.rs b/crates/smlib/src/ffi/history.rsnew file mode 100644index 0000000000..e3a0f24ac1--- /dev/null+++ b/crates/smlib/src/ffi/history.rs@@ -0,0 +1,53 @@+//! The history block of `capi/include/smlib.h` (`smlib_history_tag`, `smlib_history_read`),+//! declared by hand. Part of the FFI boundary, like its parent: called only through+//! [`crate::history`].+#![allow(unsafe_code)]++use super::Handle;+#[cfg(feature = "native")]+use super::{ERR_BUFFER, OK, RawBrep, new_brep};++/// `SMLIB_HISTORY_VERSION` this crate reads.+pub const VERSION: i64 = 1;++#[cfg(feature = "native")]+unsafe extern "C" {+ fn smlib_history_tag(brep: *const RawBrep, operand: i32, out: *mut *mut RawBrep) -> i32;+ fn smlib_history_read(result: *const RawBrep, buf: *mut i64, cap: i64, out_len: *mut i64) -> i32;+}++#[cfg(feature = "native")]+pub fn tag(b: &Handle, operand: i32) -> Result<Handle, i32> {+ new_brep(|out| unsafe { smlib_history_tag(b.raw(), operand, out) })+}++/// The result's history records, sized by asking first.+#[cfg(feature = "native")]+pub fn read(b: &Handle) -> Result<Vec<i64>, i32> {+ let mut len = 0i64;+ let mut buf: Vec<i64> = Vec::new();+ loop {+ let cap = i64::try_from(buf.len()).map_err(|_| ERR_BUFFER)?;+ let ptr = if buf.is_empty() { std::ptr::null_mut() } else { buf.as_mut_ptr() };+ match unsafe { smlib_history_read(b.raw(), ptr, cap, &mut len) } {+ OK => {+ buf.truncate(usize::try_from(len).map_err(|_| ERR_BUFFER)?);+ return Ok(buf);+ }+ // Asked again with room for what it said; a second shortfall would mean the body+ // changed, which a handle never does.+ ERR_BUFFER if buf.is_empty() => buf.resize(usize::try_from(len).map_err(|_| ERR_BUFFER)?, 0),+ s => return Err(s),+ }+ }+}++#[cfg(not(feature = "native"))]+pub fn tag(_: &Handle, _: i32) -> Result<Handle, i32> {+ Err(super::NOT_BUILT)+}++#[cfg(not(feature = "native"))]+pub fn read(_: &Handle) -> Result<Vec<i64>, i32> {+ Err(super::NOT_BUILT)+}diff --git a/crates/smlib/src/history.rs b/crates/smlib/src/history.rsnew file mode 100644index 0000000000..e338213bce--- /dev/null+++ b/crates/smlib/src/history.rs@@ -0,0 +1,186 @@+//! Face and edge history out of SMLib operations, in [`solidcraft_geom::brep::history`]'s terms.+//!+//! SMLib carries identity through its own edits: every split, merge, copy and coincidence an+//! operation makes passes the attributes of what it changes on to what it makes. So each operand+//! is tagged ([`Brep::tagged`]: face i and edge i become operand k's face i and edge i), the+//! operation runs on the tagged copies, and the result's tags say where each face and edge came+//! from ([`Brep::history`]). Nothing is sampled or guessed.+//!+//! Indices here are SMLib's own: positions in a body's face and edge lists, which a copy keeps.+//! [`Raw::history`] renumbers them into canonical order (docs/native-brep.md) with the+//! [`Order`] the export gives each body.++use std::collections::BTreeSet;++use solidcraft_geom::brep::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, Failed, History, Side};++use crate::{Brep, Error, Result, error, ffi};++/// A result face as SMLib reports it: how it relates to its origins, and the (operand, face)+/// pairs it came from, sorted.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RawFace {+ pub change: Change,+ pub origins: Vec<(usize, usize)>,+}++/// A result edge as SMLib reports it: the result faces it bounds (ascending) and the (operand,+/// edge) pairs it came from, sorted; none where it is new (where its faces meet).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RawEdge {+ pub faces: Vec<usize>,+ pub origins: Vec<(usize, usize)>,+}++/// A result's history in SMLib's own face and edge order.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Raw {+ pub faces: Vec<RawFace>,+ pub edges: Vec<RawEdge>,+}++/// Where one body's faces and edges go in canonical order: `faces[i]` is the canonical index of+/// SMLib's face i, likewise for edges. Empty means SMLib's order is the canonical one.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Order {+ pub faces: Vec<usize>,+ pub edges: Vec<usize>,+}++impl Brep {+ /// A copy whose face i and edge i are tagged as face i and edge i of operand `operand` (in+ /// SMLib's order, which the copy keeps). Run an operation on tagged copies, then read its+ /// result's [`Brep::history`].+ pub fn tagged(&self, operand: usize) -> Result<Brep> {+ let operand = i32::try_from(operand).map_err(|_| Error::Argument)?;+ ffi::history::tag(&self.0, operand).map(Brep).map_err(error)+ }++ /// The history of this body, made by an operation from tagged operands: each face's and+ /// edge's origins among them. Faces and edges no tag reached have none.+ pub fn history(&self) -> Result<Raw> {+ let v = ffi::history::read(&self.0).map_err(error)?;+ Raw::decode(&v).ok_or(Error::Exception)+ }+}++impl Raw {+ /// Decodes `smlib_history_read`'s records; `None` where they don't read as its layout.+ fn decode(v: &[i64]) -> Option<Raw> {+ let mut r = Reader(v.iter());+ if r.next()? != usize::try_from(ffi::history::VERSION).ok()? {+ return None;+ }+ let (nf, ne) = (r.next()?, r.next()?);+ // Every entry takes at least two values: no more entries than values.+ if nf.saturating_add(ne) > v.len() {+ return None;+ }+ let mut faces = Vec::with_capacity(nf);+ for _ in 0..nf {+ let change = match r.next()? {+ 0 => Change::Kept,+ 1 => Change::Modified,+ 2 => Change::Split,+ 3 => Change::Merged,+ 4 => Change::Generated,+ _ => return None,+ };+ let n = r.next()?;+ faces.push(RawFace { change, origins: r.pairs(n)? });+ }+ let mut edges = Vec::with_capacity(ne);+ for _ in 0..ne {+ let m = r.next()?;+ let bounds = (0..m).map(|_| r.next()).collect::<Option<Vec<_>>>()?;+ let n = r.next()?;+ edges.push(RawEdge { faces: bounds, origins: r.pairs(n)? });+ }+ r.0.next().is_none().then_some(Raw { faces, edges })+ }++ /// As a [`History`] over `operands.len()` operands, every index renumbered into canonical+ /// order: operand k's through `operands[k]`, the result's through `result`. An edge with no+ /// origin is where its two faces meet; one bounding other than two faces, or a face new to+ /// the operation, has no origin at all.+ pub fn history(&self, operands: &[Order], result: &Order) -> std::result::Result<History, Failed> {+ let bad = |what: &'static str| Failed(what);+ let map = |order: &[usize], i: usize| -> std::result::Result<usize, Failed> {+ if order.is_empty() { Ok(i) } else { order.get(i).copied().ok_or(bad("an index lies outside its body's order")) }+ };+ let operand = |k: usize| operands.get(k).ok_or(bad("an origin lies on no operand"));+ let face_origin = |(k, f): (usize, usize)| -> std::result::Result<FaceOrigin, Failed> {+ let o = operand(k)?;+ Ok(FaceOrigin::Face { operand: k, face: map(&o.faces, f)? })+ };+ // The result's faces and edges, each at its canonical place.+ let place = |order: &[usize], n: usize| -> std::result::Result<Vec<usize>, Failed> {+ let at: Vec<usize> = (0..n).map(|i| map(order, i)).collect::<std::result::Result<_, _>>()?;+ let distinct: BTreeSet<usize> = at.iter().copied().collect();+ if distinct.len() != n || at.iter().any(|c| *c >= n) {+ return Err(bad("the result's order is no permutation"));+ }+ Ok(at)+ };+ let (fat, eat) = (place(&result.faces, self.faces.len())?, place(&result.edges, self.edges.len())?);++ let mut faces: Vec<Option<FaceProv>> = vec![None; self.faces.len()];+ for (f, at) in self.faces.iter().zip(&fat) {+ let origins: BTreeSet<FaceOrigin> = f.origins.iter().map(|o| face_origin(*o)).collect::<std::result::Result<_, _>>()?;+ faces[*at] = Some(FaceProv { origins: origins.into_iter().collect(), change: f.change });+ }+ let faces: Vec<FaceProv> = faces.into_iter().collect::<Option<_>>().ok_or(bad("the result's order is no permutation"))?;++ let mut edges: Vec<Option<EdgeProv>> = vec![None; self.edges.len()];+ for (e, at) in self.edges.iter().zip(&eat) {+ let bounds: BTreeSet<usize> = e+ .faces+ .iter()+ .map(|f| fat.get(*f).copied().ok_or(bad("an edge lies on a face outside the result")))+ .collect::<std::result::Result<_, _>>()?;+ let bounds: Vec<usize> = bounds.into_iter().collect();+ let origins = if e.origins.is_empty() {+ // New: where its two faces meet, each side what that face came from.+ let side = |f: usize| faces.get(f).and_then(|p| Side::new(p.origins.iter().copied()));+ match bounds.as_slice() {+ [a, b] => side(*a).zip(side(*b)).map(|(a, b)| EdgeOrigin::meet(a, b)).into_iter().collect(),+ _ => Vec::new(),+ }+ } else {+ let set: BTreeSet<EdgeOrigin> = e+ .origins+ .iter()+ .map(|(k, i)| {+ let o = operand(*k)?;+ Ok(EdgeOrigin::Edge { operand: *k, edge: map(&o.edges, *i)? })+ })+ .collect::<std::result::Result<_, Failed>>()?;+ set.into_iter().collect()+ };+ edges[*at] = Some(EdgeProv { faces: bounds, origins });+ }+ let edges: Vec<EdgeProv> = edges.into_iter().collect::<Option<_>>().ok_or(bad("the result's order is no permutation"))?;+ Ok(History { operands: operands.len(), faces, edges })+ }+}++/// Reads non-negative values off the records.+struct Reader<'a>(std::slice::Iter<'a, i64>);++impl Reader<'_> {+ fn next(&mut self) -> Option<usize> {+ self.0.next().and_then(|x| usize::try_from(*x).ok())+ }++ /// `n` pairs; `None` past the end (so a huge `n` costs nothing).+ fn pairs(&mut self, n: usize) -> Option<Vec<(usize, usize)>> {+ let mut v = Vec::with_capacity(n.min(self.0.len() / 2));+ for _ in 0..n {+ v.push((self.next()?, self.next()?));+ }+ Some(v)+ }+}++#[cfg(test)]+mod tests;diff --git a/crates/smlib/src/history/tests.rs b/crates/smlib/src/history/tests.rsnew file mode 100644index 0000000000..2646c02345--- /dev/null+++ b/crates/smlib/src/history/tests.rs@@ -0,0 +1,107 @@+use super::*;+use solidcraft_geom::brep::history::{Change, EdgeOrigin, FaceOrigin};++fn face(operand: usize, face: usize) -> FaceOrigin {+ FaceOrigin::Face { operand, face }+}++/// Two boxes joined across a face, as `smlib_history_read` lays it out: face 0 is operand 0's+/// face 2 kept, face 1 operand 1's face 4 trimmed, face 2 both boxes' coplanar faces 0 merged.+/// Edge 0 is new between faces 0 and 1, edge 1 is operand 0's edge 7, edge 2 joins edge 3 of+/// each box and bounds faces 1 and 2.+const RECORDS: &[i64] = &[+ 1, 3, 3, //+ 0, 1, 0, 2, //+ 1, 1, 1, 4, //+ 3, 2, 0, 0, 1, 0, //+ 2, 0, 1, 0, //+ 2, 0, 2, 1, 0, 7, //+ 2, 1, 2, 2, 0, 3, 1, 3,+];++#[test]+fn decodes_the_c_layout() {+ let raw = Raw::decode(RECORDS).unwrap();+ assert_eq!(raw.faces.len(), 3);+ assert_eq!(raw.faces[2], RawFace { change: Change::Merged, origins: vec![(0, 0), (1, 0)] });+ assert_eq!(raw.edges[0], RawEdge { faces: vec![0, 1], origins: vec![] });+ assert_eq!(raw.edges[2].origins, vec![(0, 3), (1, 3)]);+}++#[test]+fn hostile_records_are_refused() {+ // Wrong version, truncated, trailing values, counts far past the data, an unknown change.+ assert_eq!(Raw::decode(&[2, 0, 0]), None);+ assert_eq!(Raw::decode(&RECORDS[..RECORDS.len() - 1]), None);+ assert_eq!(Raw::decode(&[RECORDS, &[0]].concat()), None);+ assert_eq!(Raw::decode(&[1, i64::MAX, 0]), None);+ assert_eq!(Raw::decode(&[1, 1, 0, 0, i64::MAX]), None);+ assert_eq!(Raw::decode(&[1, 1, 0, 9, 0]), None);+ assert_eq!(Raw::decode(&[1, 1, 0, 0, -1]), None);+ assert_eq!(Raw::decode(&[]), None);+}++#[test]+fn new_edges_are_where_their_faces_meet() {+ let raw = Raw::decode(RECORDS).unwrap();+ let h = raw.history(&[Order::default(), Order::default()], &Order::default()).unwrap();+ assert_eq!(h.operands, 2);+ assert_eq!(h.faces[0].origins, vec![face(0, 2)]);+ assert_eq!(h.faces[0].change, Change::Kept);+ assert_eq!(h.edges[0].origins, vec![EdgeOrigin::meet(face(0, 2), face(1, 4))]);+ assert_eq!(h.edges[1].origins, vec![EdgeOrigin::Edge { operand: 0, edge: 7 }]);+ assert_eq!(h.edges[2].origins, vec![EdgeOrigin::Edge { operand: 0, edge: 3 }, EdgeOrigin::Edge { operand: 1, edge: 3 }]);+ assert_eq!(h.edges[2].faces, vec![1, 2]);+ h.check_counts((3, 3), &[(3, 8), (5, 4)]).unwrap();+}++#[test]+fn renumbers_into_canonical_order() {+ let raw = Raw::decode(RECORDS).unwrap();+ // Operand 0's SMLib face 2 is its canonical face 5, edge 7 its edge 0; the result's faces+ // and edges are listed backwards.+ let a = Order { faces: vec![1, 2, 5, 0, 3, 4], edges: vec![1, 2, 3, 4, 5, 6, 7, 0] };+ let b = Order { faces: vec![0, 1, 2, 3, 4], edges: vec![0, 1, 2, 3] };+ let result = Order { faces: vec![2, 1, 0], edges: vec![2, 1, 0] };+ let h = raw.history(&[a, b], &result).unwrap();+ assert_eq!(h.faces[2].origins, vec![face(0, 5)]);+ assert_eq!(h.faces[0].origins, vec![face(0, 1), face(1, 0)]);+ assert_eq!(h.edges[1].origins, vec![EdgeOrigin::Edge { operand: 0, edge: 0 }]);+ // The new edge now bounds result faces 2 and 1, and meets the renumbered origins.+ assert_eq!(h.edges[2].faces, vec![1, 2]);+ assert_eq!(h.edges[2].origins, vec![EdgeOrigin::meet(face(0, 5), face(1, 4))]);+}++#[test]+fn bad_orders_are_errors() {+ let raw = Raw::decode(RECORDS).unwrap();+ let ok = Order::default();+ // An origin on an operand that isn't there.+ assert!(raw.history(std::slice::from_ref(&ok), &ok).is_err());+ // An operand order too short for an origin.+ assert!(raw.history(&[Order { faces: vec![0], edges: vec![] }, ok.clone()], &ok).is_err());+ // A result order that isn't a permutation.+ assert!(raw.history(&[ok.clone(), ok.clone()], &Order { faces: vec![0, 0, 1], edges: vec![] }).is_err());+ assert!(raw.history(&[ok.clone(), ok.clone()], &Order { faces: vec![0, 1, 3], edges: vec![] }).is_err());+}++#[cfg(feature = "native")]+#[test]+fn a_tagged_body_is_its_own_history() {+ let b = Brep::make_box([0.0; 3], [1.0, 2.0, 3.0]).unwrap();+ let raw = b.tagged(4).unwrap().history().unwrap();+ assert_eq!((raw.faces.len(), raw.edges.len()), (6, 12));+ for (i, f) in raw.faces.iter().enumerate() {+ assert_eq!(f, &RawFace { change: Change::Kept, origins: vec![(4, i)] });+ }+ for (i, e) in raw.edges.iter().enumerate() {+ assert_eq!(e.origins, vec![(4, i)]);+ assert_eq!(e.faces.len(), 2);+ }+ // Untagged: every face new, every edge where two of them meet.+ let raw = b.history().unwrap();+ assert!(raw.faces.iter().all(|f| f.change == Change::Generated && f.origins.is_empty()));+ let h = raw.history(&[], &Order::default()).unwrap();+ assert!(h.edges.iter().all(|e| e.origins.is_empty()));+ assert_eq!(b.tagged(usize::MAX).unwrap_err(), Error::Argument);+}diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rsindex d36236173f..0bf58f6306 100644--- a/crates/smlib/src/lib.rs+++ b/crates/smlib/src/lib.rs@@ -16,6 +16,7 @@ use std::sync::Once;use std::sync::atomic::{AtomicI32, Ordering};mod ffi;+pub mod history;/// Why an SMLib call failed.#[derive(Clone, Debug, PartialEq, Eq)]