SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Kernel rig export: review fixes
jyviko7b0906b918e5
diff --git a/apps/solidcraft-cli/src/kernel_cases.rs b/apps/solidcraft-cli/src/kernel_cases.rsindex bb30f7990e..47fe521312 100644--- a/apps/solidcraft-cli/src/kernel_cases.rs+++ b/apps/solidcraft-cli/src/kernel_cases.rs@@ -743,7 +743,7 @@ fn check_case_in(}let ran = s.run_script(&commands);// The trace ends with the commands: grading reads the bodies through the kernel too.- if let Some(c) = capture.as_deref_mut() {+ if let Some(c) = &mut capture {c.events = solidcraft_engine::kernel::smlib_trace::finish();c.ran = Some(match &ran {Ok(_) => s.world_state().map(|w| w.bodies.iter().map(|b| (b.name.clone(), b.body.record().clone())).collect()).map_err(|e| e.to_string()),diff --git a/apps/solidcraft-cli/src/kernel_cases_export.rs b/apps/solidcraft-cli/src/kernel_cases_export.rsindex e160abe17b..5e19fc161b 100644--- a/apps/solidcraft-cli/src/kernel_cases_export.rs+++ b/apps/solidcraft-cli/src/kernel_cases_export.rs@@ -151,11 +151,15 @@ pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<()(_, true) => {}(None, false) => why_not.push("the case did not run".into()),(Some(Err(e)), false) => {- // The run stopped. It stopped in the kernel when the last operation traced failed: the- // engine reports that failure in its own words.+ // The run stopped. It stopped in the kernel when the last operation that failed is+ // followed by no operation but copies (a copy or a tagged copy, which build nothing):+ // nothing was built after it, so the engine's error reports that failure in its own+ // words. An operation that ran after it means the engine went on and failed itself.outcome = json!({"ran": false, "engine_error": e});- match t.calls.len().checked_sub(1).and_then(|i| t.calls.get(i).map(|c| (i, c))) {- Some((i, c)) if c.3.is_err() => {+ let last_failed = t.calls.iter().rposition(|c| c.3.is_err());+ let built_after = |i: usize| t.calls.iter().skip(i + 1).any(|c| !matches!(c.0, "copy" | "tagged"));+ match last_failed.filter(|&i| !built_after(i)).and_then(|i| t.calls.get(i).map(|c| (i, c))) {+ Some((i, c)) => {failed_call = Some(i);ends.extend(c.1.iter().copied());if let Err(k) = c.3 {@@ -165,15 +169,15 @@ pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<()}}}- Some(_) => why_not.push(format!("the failure is SolidCraft's, not a kernel operation's: {e}")),- None => why_not.push(format!("no kernel operation ran before the failure: {e}")),+ None if t.calls.is_empty() => why_not.push(format!("no kernel operation ran before the failure: {e}")),+ None => why_not.push(format!("the failure is SolidCraft's, not a kernel operation's: {e}")),}}(Some(Ok(world)), false) => {let operands = t.operands();let mut made = 0;for (name, record) in world {- let from_op = t.exports.iter().rev().find(|(_, r)| *r == record).map(|(id, _)| *id).filter(|id| t.producer.contains_key(id));+ let from_op = t.exports.iter().rev().find(|(id, r)| *r == record && t.producer.contains_key(id)).map(|(id, _)| *id);let operand = t.imports.iter().filter(|(i, (r, _, _))| *r == record && operands.contains(i)).map(|(i, _)| *i).min();match (from_op, operand) {(Some(id), _) => {@@ -274,8 +278,12 @@ pub fn write(root: &Path, dir: &str, out: &Value, capture: Capture) -> Result<()let path = folder.join(format!("{id}.json"));let text = serde_json::to_string(&entry).map_err(|e| e.to_string())?;std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;+ // Cases run in parallel processes: each writes its own file and renames it over the shared+ // one, so no reader sees a torn file (every process writes the same fix set).let fixes = serde_json::to_string_pretty(&smlib_trace::fixes()).map_err(|e| e.to_string())?;- std::fs::write(root.join("fixes.json"), fixes).map_err(|e| format!("{}: {e}", root.display()))+ let own = root.join(format!("fixes.json.{}", std::process::id()));+ std::fs::write(&own, fixes).map_err(|e| format!("{}: {e}", own.display()))?;+ std::fs::rename(&own, root.join("fixes.json")).map_err(|e| format!("{}: {e}", root.display()))}#[cfg(test)]diff --git a/crates/smlib/src/core/picked.rs b/crates/smlib/src/core/picked.rsindex 02a6b8d934..a7c6d50098 100644--- a/crates/smlib/src/core/picked.rs+++ b/crates/smlib/src/core/picked.rs@@ -1,16 +1,20 @@//! What a pick by points chose, as indices into the body's own lists: for the operations a trace//! records ([`crate::trace`]), so the corpus names its edges, faces and corners by topology//! index as well as by the points the operation was given. Each point is picked alone, by the-//! same picker the operation runs, on the body as the operation received it.+//! picker the operation runs, on a copy of the body as the operation received it: a pick builds+//! query caches on the body it reads, and the body traced stays as an untraced run leaves it.use std::sync::PoisonError;+use solidcore::geom::vector3d::Vec3;use solidcore::topology::brep::p1 as brep_p1;+use solidcore::topology::brep::p3::brep_copy;use solidcore::topology::{edge, vertex};use super::Body;use super::blend::{Miss, pick_edges, pick_vertices};use super::offset::pick_faces;+use super::trim::{face_at, nearest_edge};use crate::Result;use crate::trace::{Pick, PickKind};@@ -19,7 +23,7 @@ use crate::trace::{Pick, PickKind};/// edge, its end points; for a vertex, its point.pub(crate) fn picks(body: &Body, kind: PickKind, points: &[[f64; 3]], tolerance: f64) -> Result<Vec<Pick>> {super::run_on("trace pick", &[], |k| {- let mut b = body.0.lock().unwrap_or_else(PoisonError::into_inner);+ let mut b = brep_copy(k, &body.0.lock().unwrap_or_else(PoisonError::into_inner))?;let mut out = Vec::with_capacity(points.len());for p in points {let one = std::slice::from_ref(p);@@ -28,19 +32,26 @@ pub(crate) fn picks(body: &Body, kind: PickKind, points: &[[f64; 3]], tolerance:let all = brep_p1::edges(&b, None)?;match pick_edges(k, &b, one, tolerance)? {Ok((es, _)) => match es.first() {- Some(&e) => {- let mut ends = Vec::with_capacity(2);- for v in [edge::start_vertex(&b, e)?, edge::end_vertex(&b, e)?].into_iter().flatten() {- let q = vertex::point(&b, v)?;- ends.push([q.x, q.y, q.z]);- }- Pick { index: all.iter().position(|&x| x == e), at: ends, miss: None }- }+ Some(&e) => Pick { index: all.iter().position(|&x| x == e), at: ends(&b, e)?, miss: None },None => Pick::missed("none"),},Err(m) => Pick::missed(miss(m)),}}+ PickKind::NearestEdge => {+ let all = brep_p1::edges(&b, None)?;+ match nearest_edge(k, &b, &all, Vec3::new(p[0], p[1], p[2])) {+ (d, Some(e)) if d <= tolerance => Pick { index: all.iter().position(|&x| x == e), at: ends(&b, e)?, miss: None },+ _ => Pick::missed("none"),+ }+ }+ PickKind::NearestFace => {+ let all = brep_p1::faces(&b, None)?;+ match face_at(k, &mut b, Vec3::new(p[0], p[1], p[2]), tolerance)? {+ Some(f) => Pick { index: all.iter().position(|&x| x == f), at: Vec::new(), miss: None },+ None => Pick::missed("none"),+ }+ }PickKind::Face => {let all = brep_p1::faces(&b, None)?;match pick_faces(k, &mut b, one, tolerance)? {@@ -67,11 +78,20 @@ pub(crate) fn picks(body: &Body, kind: PickKind, points: &[[f64; 3]], tolerance:};out.push(pick);}- b.refresh_cached_topology();Ok(out)})}+/// Edge `e`'s end points.+fn ends(b: &solidcore::topology::Brep, e: solidcore::topology::EdgeId) -> solidcore::Result<Vec<[f64; 3]>> {+ let mut out = Vec::with_capacity(2);+ for v in [edge::start_vertex(b, e)?, edge::end_vertex(b, e)?].into_iter().flatten() {+ let q = vertex::point(b, v)?;+ out.push([q.x, q.y, q.z]);+ }+ Ok(out)+}+fn miss(m: Miss) -> &'static str {match m {Miss::None(_) => "none",diff --git a/crates/smlib/src/core/trim.rs b/crates/smlib/src/core/trim.rsindex cf7099a1d7..8d9d8d44be 100644--- a/crates/smlib/src/core/trim.rs+++ b/crates/smlib/src/core/trim.rs@@ -77,7 +77,7 @@ const ONE: BrepId = BrepId::from_index(0);/// `face_at`: the face of `b` nearest `p`, within `tol` (`SmApiFaceClosestPoint`; a face whose/// query fails is skipped).-fn face_at(k: &mut Kernel, b: &mut Brep, p: Point3, tol: f64) -> solidcore::Result<Option<FaceId>> {+pub(super) fn face_at(k: &mut Kernel, b: &mut Brep, p: Point3, tol: f64) -> solidcore::Result<Option<FaceId>> {let all = brep_p1::faces(b, None)?;let mut shapes = Vec::with_capacity(all.len());for &f in &all {@@ -503,7 +503,7 @@ fn edge_distance(k: &Kernel, b: &Brep, e: EdgeId, p: Vec3) -> f64 {}/// `nearest_edge`: the distance to the nearest of `edges`, with that edge.-fn nearest_edge(k: &Kernel, b: &Brep, edges: &[EdgeId], p: Vec3) -> (f64, Option<EdgeId>) {+pub(super) fn nearest_edge(k: &Kernel, b: &Brep, edges: &[EdgeId], p: Vec3) -> (f64, Option<EdgeId>) {let (mut best, mut which) = (f64::INFINITY, None);for &e in edges {let d = edge_distance(k, b, e, p);diff --git a/crates/smlib/src/trace.rs b/crates/smlib/src/trace.rsindex 68e61b1e0b..ade5df6f92 100644--- a/crates/smlib/src/trace.rs+++ b/crates/smlib/src/trace.rs@@ -105,9 +105,16 @@ pub(crate) fn maybe(op: &'static str, inputs: &[&Brep], r: &Result<Option<Brep>>/// What a pick by points is of.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum PickKind {+ /// The edge nearest each point, unambiguous (`pick_edges`, the blends' picker).Edge,+ /// The face nearest each point, unambiguous (`pick_faces`, the offsets' picker).Face,+ /// The vertex nearest each point, unambiguous (`pick_vertices`, the setbacks' picker).Vertex,+ /// The nearest edge (`nearest_edge`, an extension's picker).+ NearestEdge,+ /// The nearest face (`face_at`, an untrim's picker).+ NearestFace,}/// What one point picked: the entity's index in the body's list of its kind, and where it is@@ -140,8 +147,8 @@ pub(crate) fn picks(body: &Brep, kind: PickKind, points: &[[f64; 3]], tolerance:Err(e) => json!({"error": e.to_string()}),};let kind = match kind {- PickKind::Edge => "edge",- PickKind::Face => "face",+ PickKind::Edge | PickKind::NearestEdge => "edge",+ PickKind::Face | PickKind::NearestFace => "face",PickKind::Vertex => "vertex",};json!({"kind": kind, "points": points, "tolerance": tolerance, "picked": picked})diff --git a/crates/smlib/src/trim.rs b/crates/smlib/src/trim.rsindex 601f40e4b6..715776235c 100644--- a/crates/smlib/src/trim.rs+++ b/crates/smlib/src/trim.rs@@ -41,7 +41,7 @@ impl Brep {"untrim_face",&[self],&r,- || json!({"face": trace::picks(self, trace::PickKind::Face, &[point], tolerance), "holes": holes, "outer": outer, "in_place": in_place}),+ || json!({"face": trace::picks(self, trace::PickKind::NearestFace, &[point], tolerance), "holes": holes, "outer": outer, "in_place": in_place}),);r}@@ -58,7 +58,7 @@ impl Brep {Continuation::Tangent => "tangent",Continuation::Curvature => "curvature",};- json!({"edge": trace::picks(self, trace::PickKind::Edge, &[point], tolerance), "distance": distance, "how": how})+ json!({"edge": trace::picks(self, trace::PickKind::NearestEdge, &[point], tolerance), "distance": distance, "how": how})});r}diff --git a/xtask/src/kernel_cases.rs b/xtask/src/kernel_cases.rsindex 3a600f8daf..40940facdc 100644--- a/xtask/src/kernel_cases.rs+++ b/xtask/src/kernel_cases.rs@@ -159,6 +159,20 @@ fn run_case(o: &Options, case: &Path) -> Value {cmd.arg(format!("--validation={v}"));}if let Some(d) = &o.export {+ // This run's entry replaces the last one's; a case that hangs or crashes now leaves none,+ // so the manifest marks it, never an entry from an earlier run.+ if let Ok(under) = case.strip_prefix(root().join("tests/kernel-cases")) {+ // Case ids hold dots (`m5x0.7`): the names are built whole, never by extension.+ let entry = d.join(under);+ let id = entry.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+ for stale in [entry.with_file_name(format!("{id}.json")), entry.with_file_name(format!("{id}.bodies.json.gz"))] {+ if let Err(e) = std::fs::remove_file(&stale)+ && e.kind() != std::io::ErrorKind::NotFound+ {+ eprintln!("kernel-cases: {}: {e}", stale.display());+ }+ }+ }let mut export = std::ffi::OsString::from("--export=");export.push(d);cmd.arg(export);diff --git a/xtask/src/kernel_corpus.rs b/xtask/src/kernel_corpus.rsindex d3364bfb6f..598400976d 100644--- a/xtask/src/kernel_corpus.rs+++ b/xtask/src/kernel_corpus.rs@@ -20,10 +20,6 @@ use crate::root;fn reason_kind(why: &str) -> &'static str {if why.starts_with("SolidCraft has no command") {"SolidCraft has no command for it yet"- } else if why.starts_with("graded on what SolidCraft computes") {- "graded on SolidCraft's own measures (continuity, mesh, files, command answers, construction, flat pattern)"- } else if why.contains("graded merged across analytic surfaces") {- "counts graded merged across analytic surfaces (SolidCraft's merged_topology)"} else if why.starts_with("no kernel operation ran before the failure") || why.starts_with("the failure is SolidCraft's") {"refused or failed in SolidCraft, not in a kernel operation"} else if why.contains("is no kernel operation's output nor an operand") {@@ -143,9 +139,9 @@ pub(crate) fn manifest(dir: &Path, results: &[Value], golden: Option<&Value>) ->for f in files {let e = read(&f);let area = e["area"].as_str().unwrap_or("?").to_string();- let a = areas.entry(area.clone()).or_insert_with(|| {- json!({"cases": 0, "expressible": 0, "operation_expressible": 0, "not_expressible": 0, "chain": {}, "reasons": {}, "ungraded": {}})- });+ let a = areas.entry(area.clone()).or_insert_with(+ || json!({"cases": 0, "expressible": 0, "operation_expressible": 0, "not_expressible": 0, "chain": {}, "reasons": {}, "ungraded": {}}),+ );let bump = |a: &mut Value, k: &str| a[k] = json!(a[k].as_u64().unwrap_or(0) + 1);bump(a, "cases");if e["expressible"].as_bool() == Some(true) {@@ -172,7 +168,8 @@ pub(crate) fn manifest(dir: &Path, results: &[Value], golden: Option<&Value>) ->}}let m = json!({- "solidcraft": git(&["rev-parse", "HEAD"]),+ // A copy without git (synced to a build machine) names no commit: say so, never "".+ "solidcraft": Some(git(&["rev-parse", "HEAD"])).filter(|c| !c.is_empty()),"solidcore": solidcore_pin(),"fixes": "fixes.json","areas": areas,@@ -194,8 +191,6 @@ mod tests {#[test]fn every_reason_the_export_gives_has_its_kind() {for (why, kind) in [- ("graded on what SolidCraft computes: continuity", "graded on SolidCraft's own measures"),- ("faces graded merged across analytic surfaces (6), the records have 8", "counts graded merged"),("the failure is SolidCraft's, not a kernel operation's: x", "refused or failed in SolidCraft"),("body \"Body1\" is no kernel operation's output nor an operand: SolidCraft built it", "a final body built or changed"),("the rig's run hang: no result", "the rig's run hung"),