diff --git a/assets/locales/pending/help-menu-version.json b/assets/locales/pending/help-menu-version.json index 41c8d34fd..ef569008a 100644 --- a/assets/locales/pending/help-menu-version.json +++ b/assets/locales/pending/help-menu-version.json @@ -1,7 +1,13 @@ { + "ar": { + "help.version": "الإصدار {version}" + }, "en": { "help.version": "Version {version}" }, + "he": { + "help.version": "גרסה {version}" + }, "ja": { "help.version": "バージョン {version}" }, diff --git a/assets/locales/pending/patch-continuity-corners.json b/assets/locales/pending/patch-continuity-corners.json new file mode 100644 index 000000000..5ffe39d63 --- /dev/null +++ b/assets/locales/pending/patch-continuity-corners.json @@ -0,0 +1,23 @@ +{ + "en": { + "ui.patch_continuity_corner_tip": "The patch meets the faces round it at the chosen continuity along each side. At a corner where those faces meet each other with different curvatures, it stays tangent (G1) there." + }, + "ar": { + "ui.patch_continuity_corner_tip": "تلتقي الرقعة بالأوجه المحيطة بها بالاستمرارية المختارة على طول كل جانب. وعند زاوية تلتقي فيها تلك الأوجه بعضها ببعض بانحناءات مختلفة، تبقى مماسّة (G1) هناك." + }, + "de": { + "ui.patch_continuity_corner_tip": "Der Patch schließt entlang jeder Seite mit der gewählten Stetigkeit an die umgebenden Flächen an. An einer Ecke, an der diese Flächen mit unterschiedlicher Krümmung aufeinandertreffen, bleibt er dort tangential (G1)." + }, + "he": { + "ui.patch_continuity_corner_tip": "הטלאי פוגש את הפאות שסביבו ברציפות שנבחרה לאורך כל צלע. בפינה שבה הפאות האלה נפגשות זו עם זו בעקמומיות שונה, הוא נשאר משיק (G1) שם." + }, + "ja": { + "ui.patch_continuity_corner_tip": "パッチは各辺に沿って、周囲の面と選んだ連続性でつながります。周囲の面どうしが異なる曲率で接するコーナーでは、そこで接線 (G1) にとどまります。" + }, + "ko": { + "ui.patch_continuity_corner_tip": "패치는 각 변을 따라 주변 면과 선택한 연속성으로 이어집니다. 주변 면끼리 서로 다른 곡률로 만나는 모서리에서는 그곳에서 접선(G1)으로 유지됩니다." + }, + "zh": { + "ui.patch_continuity_corner_tip": "补面沿每条边以所选的连续性与周围的面相接。在周围的面彼此以不同曲率相接的角上,补面在该处保持相切 (G1)。" + } +} diff --git a/assets/locales/pending/section-hatch-by-part.json b/assets/locales/pending/section-hatch-by-part.json index 85c32ee63..240a79979 100644 --- a/assets/locales/pending/section-hatch-by-part.json +++ b/assets/locales/pending/section-hatch-by-part.json @@ -1,9 +1,19 @@ { + "ar": { + "prefs.section_hatch": "تهشير المقطع", + "prefs.section_hatch_by_part": "حسب الجزء", + "prefs.section_hatch_one": "نمط واحد" + }, "en": { "prefs.section_hatch": "Section hatch", "prefs.section_hatch_by_part": "By part", "prefs.section_hatch_one": "One style" }, + "he": { + "prefs.section_hatch": "קווקוו חתך", + "prefs.section_hatch_by_part": "לפי חלק", + "prefs.section_hatch_one": "סגנון אחד" + }, "ja": { "prefs.section_hatch": "断面ハッチング", "prefs.section_hatch_by_part": "部品ごと", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index a3087b522..fdc08e2e4 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -1833,6 +1833,16 @@ pub enum FeatureKind { file: String, meshes: Vec, }, + /// Repair Part (#8371): faces SMLib refuses rebuilt on their own surfaces, free edges that + /// pair up within `gap` sewn, and, when `patch_holes`, the loops of free edges left patched + /// and sewn in (`kernel::repair`). + Repair { + body: BodyName, + #[walk(length = "Gap")] + gap: Expr, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + patch_holes: bool, + }, } /// A fillet corner set back: the vertex at `vertex`, where every edge is rounded, has its corner @@ -2506,6 +2516,7 @@ impl FeatureKind { FeatureKind::Import { .. } => "BaseFeature", FeatureKind::MeshImport { .. } => "MeshFeature", FeatureKind::MeshConvert { .. } => "MeshConvertFeature", + FeatureKind::Repair { .. } => "RepairFeature", } } /// Default name prefix (`Extrude` → `Extrude1`). @@ -2589,6 +2600,7 @@ impl FeatureKind { FeatureKind::Import { .. } => "Import", FeatureKind::MeshImport { .. } => "Mesh", FeatureKind::MeshConvert { .. } => "ConvertMesh", + FeatureKind::Repair { .. } => "Repair", } } } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 07fa86238..0ea238841 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -535,6 +535,10 @@ pub struct ModelState { /// How the pieces a join split off into bodies of their own touched the others (by feature /// id), for its notice. kept_separate: BTreeMap, + /// For a feature saved before format 14 that split a body, a digest of the later features' + /// picks its pieces were named by (by feature id, see [`crate::lineage::order_legacy_lumps`]): + /// the state stands for the feature only while those picks are the same. + legacy_picks: BTreeMap, } /// How a piece a join split off into a body of its own (`Touching::Separate`) touched the @@ -645,7 +649,7 @@ impl ModelState { /// After a feature evaluated to this state from `before` with cache key `key`: bodies it /// made or changed take that key, sketches it made a digest of their solved geometry (see /// [`quantize`]); the rest keep theirs. - fn stamp(&mut self, before: &Arc, f: &Feature, key: u64, mats: Vec) { + fn stamp(&mut self, doc: &Document, before: &Arc, f: &Feature, key: u64, mats: Vec) { let feature = f.id; let depth = before.bodies.iter().filter_map(|b| b.names.depth()).max().unwrap_or(0) + 1; let sheets = if f.kind.is_sheet() { self.sheets.clone() } else { Vec::new() }; @@ -654,7 +658,13 @@ impl ModelState { // the feature was saved when they were named in that order). if !f.shell_piece_order { crate::lineage::order_lumps(&mut self.bodies, &origin); + } else { + crate::lineage::order_legacy_lumps(&mut self.bodies, before, doc, f); } + match crate::lineage::legacy_picks_digest(&self.bodies, before, doc, f) { + 0 => self.legacy_picks.remove(&f.id), + d => self.legacy_picks.insert(f.id, d), + }; // The bodies before the feature by name, in their order (names repeat only in damaged // states): every lookup below is the first match of a linear search, without walking // every earlier body for every body, after every feature. @@ -734,6 +744,7 @@ struct CachedEval { error: Option, warning: Option, import_report: Option>, + repair: Option>, ms: f64, state: Arc, /// What the state costs, worked out once when it was stored (see @@ -943,6 +954,9 @@ pub struct FeatureResult { /// (`warning` is the first of them as the kernel words them). #[serde(skip_serializing_if = "Option::is_none")] pub import_report: Option>, + /// What a Repair Part feature changed, face by face (the command's reply says it). + #[serde(skip)] + pub repair: Option>, pub ms: f64, pub skipped: bool, /// Not evaluated on the document's current inputs: a feature at or after a sketch shown live @@ -1324,6 +1338,15 @@ fn context_digest(doc: &Document, vals: &BTreeMap) -> u64 { h.finish() } +/// Whether `after`, a state feature `f` evaluated to from `before` in an earlier evaluation, is +/// still its result in `doc`: a feature saved before format 14 names the pieces it splits a body +/// into as the later features pick them ([`crate::lineage::order_legacy_lumps`]), which neither +/// its fingerprint nor its cache key cover. (A script replays those features after it: the state +/// made before they were there named the pieces otherwise.) +fn legacy_current(doc: &Document, f: &Feature, before: &ModelState, after: &ModelState) -> bool { + !f.shell_piece_order || after.legacy_picks.get(&f.id).copied().unwrap_or(0) == crate::lineage::legacy_picks_digest(&after.bodies, before, doc, f) +} + /// The cache key of a feature evaluation: its own inputs, the document context and the state it /// starts from. Features that replay other features' definitions (patterns and mirrors of /// features) also take the chain fingerprint, which covers every earlier definition. @@ -1856,9 +1879,11 @@ impl Model { if f.suppressed && !rolled_back { reserved.extend(f.body_names.iter().map(|n| n.trim()).filter(|n| !n.is_empty()).map(str::to_string)); } + // A feature that names its pieces as later features pick them (saved before format 14) + // has a result only while those picks are what they were. if reuse && !unkept - && let Some(old) = self.results.get(i).filter(current) + && let Some(old) = self.results.get(i).filter(current).filter(|old| old.skipped || legacy_current(doc, f, &state, &old.state)) { if !old.skipped { state = old.state.clone(); @@ -1874,6 +1899,7 @@ impl Model { error: None, warning: None, import_report: None, + repair: None, ms: 0.0, skipped: true, stale: false, @@ -1893,7 +1919,13 @@ impl Model { cache_key(f, fp, fingerprint(doc, 0, f, &vals, false, &self.step_digests) ^ placement_digest(doc, f, Some(&state)), ctx, &state); let kept = self.kept.0.as_ref().filter(|_| !self.no_cache); if !self.no_cache - && let Some(c) = self.cache.lock().ok().and_then(|mut m| m.get(key)).or_else(|| kept.and_then(|k| k.get(key))) + && let Some(c) = self + .cache + .lock() + .ok() + .and_then(|mut m| m.get(key)) + .or_else(|| kept.and_then(|k| k.get(key))) + .filter(|c| c.error.is_some() || legacy_current(doc, f, &state, &c.state)) { if let Some(k) = kept { k.put(key, &c); @@ -1910,6 +1942,7 @@ impl Model { error: c.error, warning: c.warning, import_report: c.import_report, + repair: c.repair, ms: c.ms, skipped: false, stale: false, @@ -1921,7 +1954,12 @@ impl Model { } // An active result hidden by the marker, or evaluated ahead on these same inputs // (the same chain of definitions from the start). Changed inputs never reuse it. - if let Some(r) = rolled.as_ref().filter(current).or_else(|| primed.as_ref().and_then(|p| p.get(&f.id)).filter(current)) { + if let Some(r) = rolled + .as_ref() + .filter(current) + .or_else(|| primed.as_ref().and_then(|p| p.get(&f.id)).filter(current)) + .filter(|r| r.error.is_some() || legacy_current(doc, f, &state, &r.state)) + { restored += 1; if r.error.is_none() { state = r.state.clone(); @@ -1944,6 +1982,7 @@ impl Model { } let mut warning = None; let mut import_report = None; + let mut repair = None; // Face references by name: move each face point onto its named face (on the body the // feature names, when it names one and the face is there). let renamed; @@ -1967,7 +2006,8 @@ impl Model { let r = match frame_error.or(bad_param) { Some(e) => Err(kernel::KernelError::Failed(e)), None => kernel::guard(&f.name, || { - eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report).map_err(|e| kernel::KernelError::Failed(e.to_string())) + eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report, &mut repair) + .map_err(|e| kernel::KernelError::Failed(e.to_string())) }), }; if r.is_ok() { @@ -2002,7 +2042,7 @@ impl Model { } _ => mats, }; - next.stamp(&state, f, key, mats); + next.stamp(doc, &state, f, key, mats); for b in &mut next.bodies { if !b.transferred { b.component = match doc.body_components.get(&b.name) { @@ -2023,6 +2063,7 @@ impl Model { error: error.clone(), warning: warning.clone(), import_report: import_report.clone(), + repair: repair.clone(), ms, bytes: state.added_bytes(&before), state: state.clone(), @@ -2041,6 +2082,7 @@ impl Model { error, warning, import_report, + repair, ms, skipped: false, stale: false, @@ -3216,7 +3258,8 @@ pub fn edge_refs(st: &ModelState, body: &Option, pts: &[Vec3]) } /// Persistent names of the edges picked at `pts`, each on the body it lies on (see -/// [`picked_bodies`]). +/// [`picked_bodies`]): of the edge a blend takes at each pick (at a vertex where a seam meets a +/// rim, the rim), else of the nearest edge. pub fn edge_names_for(st: &ModelState, body: &Option, pts: &[Vec3]) -> Vec { let Some(on) = picked_bodies(st, body, pts) else { return Vec::new() }; let mut out = vec![String::new(); pts.len()]; @@ -3230,7 +3273,14 @@ pub fn edge_names_for(st: &ModelState, body: &Option, pts: &[Ve // The body's names are worked out once for all its picks. let idx: Vec = on.iter().enumerate().filter(|(_, t)| **t == ti).map(|(i, _)| i).collect(); let at: Vec = idx.iter().filter_map(|i| pts.get(*i).copied()).collect(); - for (i, n) in idx.into_iter().zip(crate::naming::edge_names_at(b, &at)) { + let names = match kernel::blend_edges(&b.body, &at) { + Ok(edges) => { + let all = crate::naming::edge_names(b); + edges.iter().map(|e| all.get(*e).cloned().unwrap_or_default()).collect() + } + Err(_) => crate::naming::edge_names_at(b, &at), + }; + for (i, n) in idx.into_iter().zip(names) { if let Some(slot) = out.get_mut(i) { *slot = n; } @@ -3542,6 +3592,19 @@ fn off_the_ends(mb: &ModelBody, edge: usize, p: Vec3) -> Vec3 { /// The edges a tapered fillet tapered (a point on each, with its taper). type Tapered = Vec<(Vec3, kernel::Taper)>; +/// A blend's refusal when the feature blended the picked edges' tangent chains too (tangent +/// propagation, the default), saying so and how to blend the picked edges alone. +fn with_propagation_hint(e: DocError) -> DocError { + const HINT: &str = " (tangent propagation blended the picked edges' tangent chain with them; with it off, tangent_chain: false, only the picked edges are blended)"; + match e { + DocError::Kernel(kernel::KernelError::TooLarge(m)) => DocError::Kernel(kernel::KernelError::TooLarge(m + HINT)), + DocError::Kernel(kernel::KernelError::Invalid(m)) => DocError::Kernel(kernel::KernelError::Invalid(m + HINT)), + DocError::Kernel(kernel::KernelError::Failed(m)) => DocError::Kernel(kernel::KernelError::Failed(m + HINT)), + DocError::Invalid(m) => DocError::Invalid(m + HINT), + e => e, + } +} + /// Body `mb` with blend `f` applied at `edges` (radius or distance `r`), the radii a fitted fillet /// used (when it reduced any) and the edges it tapered. fn blend_body( @@ -6237,6 +6300,7 @@ fn eval_feature( st: &mut ModelState, warning: &mut Option, import_report: &mut Option>, + repair: &mut Option>, ) -> Result<()> { // Its tools meet bodies in other placements where those are shown (#3383). let _frames = ToolFrames::install(doc, f, st); @@ -6782,12 +6846,15 @@ fn eval_feature( let Some(mb) = st.bodies.get(*ti) else { return Err(DocError::Invalid("body".into())) }; let mut w = None; let edges = blend_edges_on(mb, f, edges, idx, &mut w)?; + let picked = edges.len(); let edges = if chain { kernel::tangent_chain(&mb.body, &edges)? } else { edges }; if let Some(w) = w { notes.push(w); } let mut note = None; - let (nb, used, tapered) = blend_body(vals, f, mb, &edges, r, &mut note)?; + let propagated = edges.len() > picked; + let (nb, used, tapered) = + blend_body(vals, f, mb, &edges, r, &mut note).map_err(|e| if propagated { with_propagation_hint(e) } else { e })?; if let Some(n) = note { notes.push(n); } @@ -7019,6 +7086,30 @@ fn eval_feature( *target = result; Ok(()) } + FeatureKind::Repair { body, gap, patch_holes } => { + let gap = val(vals, gap, Kind::Length)?; + let index = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; + let source = st.bodies.get(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; + let (repaired, report) = kernel::repair(&source.body, &kernel::RepairOptions { gap, patch_holes: *patch_holes })?; + let repaired = repaired.with_color(source.body.color()); + let result = ModelBody::new(source.name.clone(), repaired, source.feature); + let mut left: Vec = + report.refused.iter().map(|r| format!("SMLib still refuses face {} ({:?}): {}", r.face + 1, r.surface, r.why)).collect(); + left.extend( + report + .holes + .iter() + .filter(|h| !h.patched) + .map(|h| h.why.clone().unwrap_or_else(|| format!("a hole of {} edges is left open", h.edges.len()))), + ); + if !left.is_empty() { + *warning = Some(left.join("; ")); + } + let target = st.bodies.get_mut(index).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; + *target = result; + *repair = Some(Arc::new(report)); + Ok(()) + } FeatureKind::MeshImport { meshes, .. } => { for (k, (name, b)) in mesh_bodies(meshes)?.into_iter().enumerate() { let name = copy_body_name(st, f, k, &name); @@ -7815,6 +7906,50 @@ mod chain_tests { } assert_eq!(tangent_face_chain(b, &[Vec3::new(20.0, 15.0, 20.0); 2]), pts); } + + fn fillet(at: Vec3, radius: &str, tangent_chain: bool) -> FeatureKind { + FeatureKind::Fillet { + edges: vec![crate::Position(at)], + radius: radius.into(), + body: None, + style: crate::FilletStyle::Constant, + fit: Default::default(), + corner: Default::default(), + setbacks: Vec::new(), + tangent_chain, + } + } + + /// A 20 box's top edge along y rounded r2, then the top front edge (along x) rounded r3: that + /// edge runs on tangentially into the round's end arc, so by default (tangent propagation) + /// the arc is rounded with it, which an r3 round on an r2 arc cannot be: refused, saying that + /// propagation blended the chain and how to blend the edge alone. With propagation off the + /// edge is rounded alone, ending on the r2 round. + #[test] + fn a_propagated_chain_that_cannot_build_says_how_to_blend_the_edge_alone() { + let build = |chain: bool| { + let mut doc = Document::new("T"); + let solid = FeatureKind::Box { + corner: crate::point_expr(Vec3::ZERO), + length: "20".into(), + width: "20".into(), + height: "20".into(), + operation: Operation::NewBody, + }; + doc.add_feature(solid, None).unwrap(); + doc.add_feature(fillet(Vec3::new(20.0, 10.0, 20.0), "2", true), None).unwrap(); + let last = doc.add_feature(fillet(Vec3::new(10.0, 0.0, 20.0), "3", chain), None).unwrap(); + let mut m = Model::new(); + m.evaluate(&doc); + (m.result(last).and_then(|r| r.error.clone()), m.state().bodies.first().map(|b| b.body.face_count())) + }; + let (on, _) = build(true); + let on = on.expect("the propagated chain is refused"); + assert!(on.contains("with it off, tangent_chain: false, only the picked edges are blended"), "{on}"); + let (off, faces) = build(false); + assert_eq!(off, None); + assert_eq!(faces, Some(8)); + } } #[cfg(test)] diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index 3d52ce028..2469c78f7 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -231,6 +231,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ("import", json!({"type": "import", "file": "a.step", "step": ""})), ("mesh_convert", json!({"type": "mesh_convert", "body": "B", "tolerance": "mesh_convert.tolerance"})), ("mesh_import", json!({"type": "mesh_import", "file": "a.stl", "meshes": []})), + ("repair", json!({"type": "repair", "body": "B", "gap": "repair.gap", "patch_holes": true})), ] } diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index 43da6a37f..5ec3fb98d 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -428,3 +428,7 @@ mesh_convert Tolerance = mesh_convert.tolerance (Length) expressions: mesh_convert.tolerance mesh_import +repair + inputs: + Gap = repair.gap (Length) + expressions: repair.gap diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 30add0647..6a04464bb 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -207,3 +207,4 @@ move import mesh_convert mesh_import +repair diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 48bc04e7f..f24d1e402 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -238,3 +238,5 @@ import mesh_convert remap_bodies: body mesh_import +repair + remap_bodies: body diff --git a/crates/doc/src/format/pending/repair-part.rs b/crates/doc/src/format/pending/repair-part.rs new file mode 100644 index 000000000..9718c18cf --- /dev/null +++ b/crates/doc/src/format/pending/repair-part.rs @@ -0,0 +1,5 @@ +//! A design can hold Repair Part (#8371): a `repair` feature with the `body` it repairs, the +//! widest `gap` between free edges it sews (a length expression) and `patch_holes` (default false, +//! not saved: the loops of free edges left are patched and sewn in). Older designs need no +//! transformation: they have no such feature. The last release refuses a design saved with this +//! (the newer format number). diff --git a/crates/doc/src/lineage.rs b/crates/doc/src/lineage.rs index 5264e8982..60f34d644 100644 --- a/crates/doc/src/lineage.rs +++ b/crates/doc/src/lineage.rs @@ -11,7 +11,7 @@ use std::sync::{Arc, OnceLock}; -use solidcraft_geom::Region2; +use solidcraft_geom::{Region2, Vec3}; use solidcraft_kernel::Body; use solidcraft_kernel::history::{BodyHistory, Change, FaceOrigin, FaceProv, History}; @@ -568,6 +568,150 @@ impl crate::ModelBody { } } +/// The pieces feature `f` (saved before format 14) split a body into, named so the later +/// features of the design find them. Those builds named the pieces in truck's shell order, which +/// SMLib's need not follow, and a later feature names the piece it works on (`body`) and keeps +/// the points it picked on it: each name goes to the piece nearest the points the features +/// naming it picked. Pieces no later feature names keep the order they came in; so do all of +/// them where the picks do not tell the pieces apart. +pub(crate) fn order_legacy_lumps(bodies: &mut [crate::ModelBody], before: &crate::ModelState, doc: &crate::Document, f: &crate::Feature) { + for members in made_families(bodies, before) { + order_legacy_family(bodies, &members, doc, f); + } +} + +/// The families of [`lump_families`] the feature that left `bodies` after `before` made: a family +/// it left as it was keeps its names. +fn made_families(bodies: &[crate::ModelBody], before: &crate::ModelState) -> Vec> { + lump_families(bodies) + .into_iter() + .filter(|members| members.iter().filter_map(|i| bodies.get(*i)).any(|b| !before.bodies.iter().any(|o| o.body.same(&b.body)))) + .collect() +} + +/// What [`order_legacy_lumps`] named the pieces of `bodies` (the state feature `f` left after +/// `before`) by: a digest of each piece name with the points the later features of `doc` naming +/// it picked, 0 where `f` was saved since format 14 or split nothing. Those features come after +/// `f`, so the state is `f`'s only while this is the same: a script replays them after it, and +/// an edit may change what they pick or name. +pub(crate) fn legacy_picks_digest(bodies: &[crate::ModelBody], before: &crate::ModelState, doc: &crate::Document, f: &crate::Feature) -> u64 { + use std::hash::{Hash, Hasher}; + if !f.shell_piece_order { + return 0; + } + let families = made_families(bodies, before); + if families.is_empty() { + return 0; + } + let mut h = std::collections::hash_map::DefaultHasher::new(); + for members in families { + let mut names: Vec = members.iter().filter_map(|i| bodies.get(*i).map(|b| b.name.clone())).collect(); + names.sort(); + for (name, points) in names.iter().zip(later_picks(doc, f, &names)) { + name.hash(&mut h); + for p in points { + [p.x, p.y, p.z].map(f64::to_bits).hash(&mut h); + } + } + } + // 0 means "nothing named so"; a digest that happens to be 0 must not read as that. + h.finish().max(1) +} + +/// The pieces each body a feature cut in two or more came out as (the bodies whose lineage is +/// that one operand), as [`order_lumps`] finds them. +fn lump_families(bodies: &[crate::ModelBody]) -> Vec> { + let mut families: Vec<(*const Operand, Vec)> = Vec::new(); + for (i, b) in bodies.iter().enumerate() { + let Made::Traced(l) = &b.made else { continue }; + let [op] = l.operands.as_slice() else { continue }; + if !matches!(op.as_ref(), Operand::Stage(_)) { + continue; + } + let key = Arc::as_ptr(op); + match families.iter_mut().find(|(k, _)| *k == key) { + Some((_, members)) => members.push(i), + None => families.push((key, vec![i])), + } + } + families.into_iter().map(|(_, m)| m).filter(|m| m.len() > 1).collect() +} + +/// Per name of `names`: the points the features after `f` in `doc` that name that body picked +/// on it. +fn later_picks(doc: &crate::Document, f: &crate::Feature, names: &[String]) -> Vec> { + let later = doc.features.iter().skip_while(|g| g.id != f.id).skip(1); + let mut picks: Vec> = vec![Vec::new(); names.len()]; + for g in later { + let Ok(kind) = serde_json::to_value(&g.kind) else { continue }; + let Some(k) = kind.get("body").and_then(|b| b.as_str()).and_then(|b| names.iter().position(|n| n == b)) else { continue }; + for key in ["edges", "faces", "face", "position"] { + let point = |v: &serde_json::Value| -> Option { + let a = v.as_array().filter(|a| a.len() == 3)?; + Some(Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?)) + }; + let found: Vec = match kind.get(key) { + Some(v) => { + point(v).map(|p| vec![p]).unwrap_or_else(|| v.as_array().map(|a| a.iter().filter_map(point).collect()).unwrap_or_default()) + } + None => Vec::new(), + }; + if let Some(slot) = picks.get_mut(k) { + slot.extend(found); + } + } + } + picks +} + +fn order_legacy_family(bodies: &mut [crate::ModelBody], members: &[usize], doc: &crate::Document, f: &crate::Feature) { + if members.len() > 64 { + return; + } + let names: Vec = members.iter().filter_map(|i| bodies.get(*i).map(|b| b.name.clone())).collect(); + let picks = later_picks(doc, f, &names); + // How far piece `i` is from the points of name `k` (the mesh's nearest triangle). + let far = |piece: usize, pts: &[Vec3]| -> f64 { + let Some(b) = members.get(piece).and_then(|i| bodies.get(*i)) else { return f64::INFINITY }; + let m = b.mesh(); + pts.iter() + .map(|p| { + m.triangles + .iter() + .filter_map(|t| m.tri(t)) + .map(|[a, b, c]| solidcraft_geom::compare::closest_on_triangle(*p, a, b, c).dist(*p)) + .fold(f64::INFINITY, f64::min) + }) + .fold(0.0, f64::max) + }; + let mut order: Vec> = vec![None; names.len()]; + let mut taken = vec![false; members.len()]; + for (k, pts) in picks.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + let best = + (0..members.len()).filter(|i| !taken.get(*i).copied().unwrap_or(true)).map(|i| (far(i, pts), i)).min_by(|a, b| a.0.total_cmp(&b.0)); + let Some((d, i)) = best else { return }; + // Only a piece the points lie on: a pick off every piece tells nothing. + let size = members.get(i).and_then(|m| bodies.get(*m)).map_or(1.0, |b| b.body.size().max(1.0)); + if d > size * 1e-3 { + return; + } + if let (Some(o), Some(t)) = (order.get_mut(k), taken.get_mut(i)) { + *o = Some(i); + *t = true; + } + } + let mut free = (0..members.len()).filter(|i| !taken.get(*i).copied().unwrap_or(true)); + let order: Vec = order.into_iter().map(|o| o.or_else(|| free.next())).collect::>().unwrap_or_default(); + if order.len() != names.len() { + return; + } + for (name, piece) in names.into_iter().zip(order) { + if let Some(b) = members.get(piece).and_then(|i| bodies.get_mut(*i)) { + b.name = name; + } + } +} + /// Name the pieces a body fell into after their faces: of the bodies in `bodies` that are lumps /// of one body (made in the same step, from one stage), the one whose least face name sorts first /// takes the first of their body names, and so on. The kernel's shell order, which named them diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs index c243906de..35f9b3329 100644 --- a/crates/doc/src/model_cache.rs +++ b/crates/doc/src/model_cache.rs @@ -364,6 +364,10 @@ impl SavedModel { tapered: serde_json::from_value(field("tapered")?).map_err(invalid)?, // A join's notice is for the evaluation that made it, not kept with the cache. kept_separate: BTreeMap::new(), + // Not kept either: a saved model's states carry no lineage, so the check of a + // legacy split's picks (`lineage::legacy_picks_digest`) finds no pieces in them + // and takes them as the design's evaluation they were saved as. + legacy_picks: BTreeMap::new(), }; held = held.saturating_add(st.bodies.len()).saturating_add(st.sketches.len()).saturating_add(st.sheets.len()); if held > MAX_HELD { @@ -596,6 +600,7 @@ impl Model { .get("import_report") .map(|v| serde_json::from_value::(v.clone()).map(Arc::new).map_err(|_| bad("saved model: import report"))) .transpose()?, + repair: None, ms, skipped: r.get("skipped").and_then(Json::as_bool).ok_or_else(|| bad("saved model: skipped"))?, stale: false, @@ -634,6 +639,7 @@ impl Model { error: None, warning: r.warning.clone(), import_report: r.import_report.clone(), + repair: r.repair.clone(), ms: r.ms, bytes: r.state.retained_bytes(), state: r.state.clone(), diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs index af308f904..c6d877c53 100644 --- a/crates/doc/src/placed_mesh.rs +++ b/crates/doc/src/placed_mesh.rs @@ -156,11 +156,55 @@ fn mesh_outlines(positions: &[Vec3], triangles: &[[u32; 3]]) -> Vec> { [(_, _, i), (_, _, j)] => normal(*i as usize).zip(normal(*j as usize)).is_some_and(|(n, m)| n.dot(m) <= cos), _ => true, }; - if visible && let (Some(&a), Some(&b)) = (positions.get(a as usize), positions.get(b as usize)) { - edges.push(vec![a, b]); + if visible && positions.get(a as usize).is_some() && positions.get(b as usize).is_some() { + edges.push((a, b)); } } - edges + straight_runs(positions, &edges) +} + +/// The outline sides `sides` (vertex index pairs) as polylines: sides that run on straight +/// through a vertex no other outline side meets are one line. A mesh whose straight edges are +/// in pieces (a box exported at a grid's spacing) then has one outline per edge, as its CAD +/// model did, and a click on it measures the whole edge. +fn straight_runs(positions: &[Vec3], sides: &[(u32, u32)]) -> Vec> { + let mut at: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (i, &(a, b)) in sides.iter().enumerate() { + at.entry(a).or_default().push(i); + at.entry(b).or_default().push(i); + } + let point = |v: u32| positions.get(v as usize).copied().unwrap_or(Vec3::ZERO); + let other = |i: usize, v: u32| sides.get(i).map_or(v, |&(a, b)| if a == v { b } else { a }); + // The side that continues `i` straight on through `v`, when `v` joins exactly two. + let next = |i: usize, v: u32| -> Option { + let [p, q] = at.get(&v)?.as_slice() else { return None }; + let j = if *p == i { *q } else { *p }; + let (into, out) = ((point(v) - point(other(i, v))).normalized()?, (point(other(j, v)) - point(v)).normalized()?); + (into.dot(out) > 1.0 - 1e-9).then_some(j) + }; + let mut used = vec![false; sides.len()]; + // Marks side `i` used; false when it already was. + let mut take = |i: usize| used.get_mut(i).is_some_and(|u| !std::mem::replace(u, true)); + let mut runs = Vec::new(); + for (i, &(a, b)) in sides.iter().enumerate() { + if !take(i) { + continue; + } + let mut run = std::collections::VecDeque::from([a, b]); + for (mut side, mut end, front) in [(i, b, false), (i, a, true)] { + while let Some(j) = next(side, end).filter(|j| take(*j)) { + end = other(j, end); + side = j; + if front { + run.push_front(end); + } else { + run.push_back(end); + } + } + } + runs.push(run.into_iter().map(point).collect()); + } + runs } /// Only proper rotations and translations preserve triangle winding, normal lengths and the @@ -182,7 +226,8 @@ mod tests { #[test] fn mesh_outlines_keep_boundaries_and_creases_without_smooth_facet_lines() { - for (degrees, expected) in [(0.0f64, 4), (15.0, 4), (30.0, 5), (45.0, 5), (90.0, 5)] { + // Flat (0 degrees), the sides from Y through the origin to -Y run straight on: one line. + for (degrees, expected) in [(0.0f64, 3), (15.0, 4), (30.0, 5), (45.0, 5), (90.0, 5)] { let angle = degrees.to_radians(); let p = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(0., -angle.cos(), angle.sin())]; let triangles = [[0, 1, 2], [1, 0, 3]]; @@ -215,6 +260,12 @@ mod tests { let edges = mesh_outlines(&p, &triangles); assert_eq!(edges.len(), 2 * n as usize); assert!(edges.iter().all(|e| e[0].z == e[1].z)); + // A straight edge in pieces (a node at its middle, where the facets of the face meet) + // is one outline; its corners stay corners. + let p = [Vec3::ZERO, Vec3::X * 2., Vec3::new(2., 1., 0.), Vec3::Y, Vec3::X]; + let edges = mesh_outlines(&p, &[[0, 4, 3], [4, 1, 2], [4, 2, 3]]); + assert_eq!(edges.len(), 4, "{edges:?}"); + assert!(edges.iter().any(|e| e == &[Vec3::ZERO, Vec3::X, Vec3::X * 2.] || e == &[Vec3::X * 2., Vec3::X, Vec3::ZERO]), "{edges:?}"); // Bad indices and zero-area facets do not invent outlines or panic. assert!(mesh_outlines(&[Vec3::ZERO, Vec3::X, Vec3::X * 2.], &[[0, 1, 99], [0, 1, 2]]).is_empty()); } diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index c9edbb1d2..37a5dff11 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -426,7 +426,10 @@ fn projected_edges(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, edges: & let mut out = Vec::new(); for (e, exact) in edges.iter().zip(exact_edges(body, plane, edges)) { match exact { - Some(g) => out.extend(g), + Some(mut g) => { + at_vertices(body, mesh, plane, *e, &mut g); + out.extend(g); + } None => { if let Some(pts) = mesh.edges.get(*e) { out.extend(fit_world(plane, pts)); @@ -437,6 +440,51 @@ fn projected_edges(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, edges: & out } +/// Edge `e`'s exact pieces `g` with their outer ends on the edge's vertices, where they lie +/// within the edge's and the reading's tolerance of them. An edge's curve need only pass within +/// its tolerance of its vertices, and an arc is read off a NURBS within the planar-edge +/// tolerance: one SMLib made (a shell's offset corner) ended 2e-6 mm from the line it meets, and +/// the two ends, not taken for one point, left the loop open, so an offset of one curve found +/// no chain to follow. The vertex is the point both edges share. +fn at_vertices(body: &crate::ModelBody, mesh: &Mesh, plane: &Plane, e: usize, g: &mut [LinkGeom]) { + let record = body.body.record(); + let Some(edge) = record.edges.get(e) else { return }; + let Some((first, last)) = mesh.edges.get(e).and_then(|pts| pts.first().zip(pts.last())) else { return }; + // The pieces are read within the planar-edge tolerance of the edge's curve, which passes + // within its own tolerance of the vertices. + let tol = edge.vertices.iter().filter_map(|v| record.vertices.get(*v as usize)).map(|v| v.tolerance).fold(edge.tolerance, f64::max) + + body.body.planar_edges_tolerance(); + // Each vertex moves the piece end nearest it (the pieces' order and direction need not be + // the edge's). + for v in [plane.to_local(*first), plane.to_local(*last)] { + let mut best: Option<(f64, &mut Vec2)> = None; + for piece in g.iter_mut() { + if let LinkGeom::Line(a, b) | LinkGeom::Arc { a, b, .. } | LinkGeom::Conic { a, b, .. } = piece { + for p in [a, b] { + let d = p.dist(v); + if d <= tol && best.as_ref().is_none_or(|(bd, _)| d < *bd) { + best = Some((d, p)); + } + } + } + } + if let Some((_, p)) = best { + *p = v; + } + } + // An arc is its centre and two ends on one circle: with its ends moved, its centre moves to + // the nearest point equally far from both (on their bisector), or the sketch would move an + // end back off the vertex onto the circle through the other. + for piece in g.iter_mut() { + if let LinkGeom::Arc { c, a, b } = piece + && let Some(across) = Vec2::new(a.y - b.y, b.x - a.x).normalized() + { + let mid = (*a + *b) * 0.5; + *c = mid + across * (*c - mid).dot(across); + } + } +} + /// A boundary segment as the link geometry that is the same curve. fn link_geom(s: &Seg2) -> Option { Some(match *s { diff --git a/crates/doc/src/thread_forms.rs b/crates/doc/src/thread_forms.rs index cc508afe6..b4f430242 100644 --- a/crates/doc/src/thread_forms.rs +++ b/crates/doc/src/thread_forms.rs @@ -400,7 +400,7 @@ impl ThreadForm { } None => { let d = num(body).ok_or_else(bad)?; - let p = self.coarse(d).ok_or_else(|| format!("no coarse pitch for M{} (give it: M{}x1)", show(d), show(d)))?; + let p = self.coarse(d).ok_or_else(|| no_coarse_pitch(d).unwrap_or_else(bad))?; (d, p, p * n) } } @@ -663,6 +663,18 @@ fn inches(s: &str) -> Option { num(s) } +/// The refusal for a plain `M` with no ISO coarse pitch: the two coarsest fine pitches to +/// give that suit the diameter. `None` for a diameter no metric thread has. +pub fn no_coarse_pitch(d: f64) -> Option { + const PITCHES: [f64; 9] = [2.0, 1.5, 1.25, 1.0, 0.75, 0.5, 0.35, 0.25, 0.2]; + if !(d.is_finite() && d > 0.2 && d <= 1e4) { + return None; + } + let first = PITCHES.iter().position(|p| *p <= 0.12 * d).unwrap_or(PITCHES.len() - 1); + let pitches: Vec = PITCHES.iter().skip(first).take(2).filter(|p| **p < d).map(|p| format!("M{}x{}", show(d), show(*p))).collect(); + (!pitches.is_empty()).then(|| format!("M{} has no coarse ISO pitch: give one, e.g. {}", show(d), pitches.join(" or "))) +} + fn show(v: f64) -> String { let s = format!("{v:.6}"); s.trim_end_matches('0').trim_end_matches('.').to_string() diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 0a08e8477..76910333c 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -87,7 +87,8 @@ fn volume(s: &Session, body: &str) -> f64 { /// Dividing one of the cut's intersection edges met a point that projects onto neither surface, /// and the fallback unwrapped that same failed projection: a kernel panic, recorded as a crash. /// Nothing panics now; the box loses the eighth of the ball inside it, or the cut is refused -/// and the box is left whole. +/// and the box is left whole. The side face is picked by its point (the report's face index +/// was truck's order): `p3` is its corner (15, -5, 0) and `l4` the box's upright edge there. #[test] fn revolve_cut_round_a_box_corner_does_not_panic() { use std::sync::Arc; @@ -98,7 +99,7 @@ fn revolve_cut_round_a_box_corner_does_not_panic() { ("sketch.rectangle.two_point", json!({"p0": [-5.4, 7.0], "p1": [15.0, -5.0]})), ("sketch.finish", json!({})), ("solid.extrude", json!({"direction": "positive", "distance": "10 mm", "operation": "new", "profiles": [0], "sketch": 1})), - ("sketch.create", json!({"plane": {"body": "Body1", "face": [12.721266146083186, -5.0, 7.034827173055135], "index": 1, "path": []}})), + ("sketch.create", json!({"plane": {"face": [12.721266146083186, -5.0, 7.034827173055135]}})), ("sketch.circle.center", json!({"center": "p3", "radius": 4.664761515876241})), ("sketch.options", json!({"slice": true})), ("sketch.finish", json!({})), @@ -176,8 +177,8 @@ fn step_export_of_an_enclosure_with_a_screw_hole_finishes_and_reads_back() { let s = replay(include_str!("../../../examples/regressions/step_export_screw_hole_enclosure.json")); let state = s.model.state(); let body = &state.body("Unterteil").unwrap().body; - // 27 faces; the kernel splits each of the three whole turns (the hole, two standoffs) in two. - assert_eq!(body.face_count(), 30); + // 27 faces, as the file holds them: each whole turn (the hole, two standoffs) is one face. + assert_eq!(body.face_count(), 27); let (text, file_faces) = read_back(&s, body); assert_eq!(text.matches("CYLINDRICAL_SURFACE(").count(), 7, "the seven round faces stay cylinders"); assert_eq!(file_faces, 27); @@ -581,16 +582,24 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/oblique_cuts_through_chamfered_ring.json")).unwrap(); let steps = script.get("commands").and_then(Value::as_array).unwrap(); let mut s = Session::default(); - let mut volumes = Vec::new(); + // The ring after the move and after each cut, and what each cut took away (the ring before it + // less the ring after it: a small body that measures to its own accuracy, where the difference + // of the whole ring's volumes is lost in the integration's 1e-6 of 1149 mm³). + let mut rings: Vec = Vec::new(); for step in steps { let reply = s.execute(step["command"].as_str().unwrap(), &step["params"]).unwrap(); if step["command"] == "solid.extrude" { assert!(reply["warning"].is_null(), "{reply}"); } if matches!(step["command"].as_str(), Some("solid.move" | "solid.extrude")) { - volumes.push(s.model.state().body("R").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume); + rings.push(s.model.state().body("R").unwrap().body.clone()); } } + let taken = |k: usize| -> f64 { + let piece = solidcraft_kernel::boolean(&rings[k], &rings[k + 1], solidcraft_kernel::BoolOp::Cut).unwrap().unwrap(); + solidcraft_kernel::measure(&piece).unwrap().volume + }; + let volumes: Vec = rings.iter().map(|b| b.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume).collect(); // Pappus: the profile's moment about the axis turned through 240°. let profile = [(16.6, 0.0), (17.5, 0.0), (18.5, 1.0), (18.5, 7.0), (17.5, 8.0), (16.6, 8.0), (16.4, 7.8), (16.4, 0.2)]; let moment: f64 = (0..profile.len()) @@ -600,14 +609,14 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { }) .sum(); let ring = moment.abs() * 4.0 * std::f64::consts::PI / 3.0; - let [whole, first, second, notched] = volumes[..] else { panic!("{volumes:?}") }; + let [whole, _, _, _] = volumes[..] else { panic!("{volumes:?}") }; // Volumes from meshes at 1e-5 mm: within a few millionths of the ring's. assert!((whole - ring).abs() < 1e-5 * ring, "{whole} vs {ring}"); // The ring and the two prisms are mirror images across XZ. - let (cut1, cut2) = (whole - first, first - second); - assert!(cut1 > 5.0 && (cut1 - cut2).abs() < 1e-6, "{cut1} vs {cut2}"); - let notch = ring_notch(); - assert!(((second - notched) - notch).abs() < 1e-4, "{} vs {notch}", second - notched); + let (cut1, cut2) = (taken(0), taken(1)); + assert!(cut1 > 5.0 && (cut1 - cut2).abs() < 1e-6 * cut1, "{cut1} vs {cut2}"); + let (notched, notch) = (taken(2), ring_notch()); + assert!((notched - notch).abs() < 1e-5 * notch, "{notched} vs {notch}"); let state = s.model.state(); let body = &state.body("R").unwrap().body; assert!(body.validity().is_empty(), "{:?}", body.validity()); @@ -620,8 +629,7 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { ); assert!(coarse < fine && coarse > fine - 2.0, "area meshed at 0.05: {coarse} vs {fine}"); println!( - "ring {whole:.6} / {ring:.6} mm³; cuts {cut1:.6}, {cut2:.6}; notch {:.6} / {notch:.6}; area meshed at 0.05 {coarse:.4} / {fine:.4}", - second - notched + "ring {whole:.6} / {ring:.6} mm³; cuts {cut1:.6}, {cut2:.6}; notch {notched:.6} / {notch:.6}; area meshed at 0.05 {coarse:.4} / {fine:.4}" ); } @@ -633,17 +641,18 @@ fn notch_into_a_ring_chamfer_is_cut_exactly() { let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/oblique_cuts_through_chamfered_ring.json")).unwrap(); let steps = script.get("commands").and_then(Value::as_array).unwrap(); let mut s = Session::default(); - let measure = - |s: &Session| s.model.state().body("R").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume; s.run_script(&Value::Array(steps[..5].to_vec())).unwrap(); - let before = measure(&s); + let before = s.model.state().body("R").unwrap().body.clone(); // The notch's sketch and its cut. for step in &steps[steps.len() - 4..] { let reply = s.execute(step["command"].as_str().unwrap(), &step["params"]).unwrap(); assert!(reply["warning"].is_null(), "{reply}"); } - let (got, want) = (before - measure(&s), ring_notch()); - assert!((got - want).abs() < 1e-4, "{got} vs {want}"); + // What the cut took: the ring before it less the ring after it, measured as a body of its own + // (the difference of the two rings' volumes is lost in the integration's 1e-6 of 1149 mm³). + let piece = solidcraft_kernel::boolean(&before, &s.model.state().body("R").unwrap().body, solidcraft_kernel::BoolOp::Cut).unwrap().unwrap(); + let (got, want) = (solidcraft_kernel::measure(&piece).unwrap().volume, ring_notch()); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); } /// What the ring's notch takes: a band 0.9 wide about a radius, from 17.6 out along it, and from diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 10c488839..54b29b690 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -14,15 +14,24 @@ use serde_json::{Value, json}; use solidcraft_doc::FeatureKind; use super::CommandSpec; -use crate::params::{bad, bool_, str_}; +use super::features::{add_feature, check_expr}; +use crate::params::{bad, bool_, expr, str_}; +use crate::schema::browser::{RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn}; +use crate::schema::{TypedContract, output_schema_for}; use crate::{Result, Session}; +const REPAIR_CONTRACT: TypedContract = TypedContract::new(); + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("body.rename", "Rename Body", rename_body).icon("rename").params("body: its name, name: the new name (features that use the body follow)"), // The import and failed operations offer it for a part the modelling kernel refuses. - planned!("body.repair", "Repair Part", "8371") + CommandSpec::new("body.repair", "Repair Part", crate::checked!("body.repair", repair_body)) .icon("body") - .params("planned: body: its name (a part the modelling kernel refuses: one its import marks as needing repair)"), + .contract(&REPAIR_CONTRACT) + .output(output_schema_for::) + .params( + "body: its name (a part the modelling kernel refuses, or an open part that should be a solid); gap?: expr (default 0.2 mm, at most 1 mm: free edges that pair up within it are sewn, each sewn edge carrying its own gap as its tolerance); patch_holes?: bool (default false: loops of free edges left are patched, in the plane of the faces around them where those are that plane, else tangent to them, and sewn in; otherwise the reply offers the patches); name? → the feature, and repair: what changed face by face (rebuilt and refused faces, sewn gaps, holes with their surface.patch), faces and largest edge tolerance before and after, closed, modelling, volume. Refused with why when nothing applies", + ), CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", redefine_sketch) .icon("plane") .params("sketch: id or name; plane: as sketch.create; frame?: as sketch.create; author_path?: exact owner occurrence ids; explicitly rebinds or freezes the plane while preserving geometry and dimension names"), @@ -806,6 +815,76 @@ pub(crate) fn counted(f: &solidcraft_doc::Feature, i: usize) -> bool { f.body_names.get(i).is_none_or(|n| n.trim().is_empty()) && (f.shell_piece_order || i < f.body_names.len() || !first) } +/// Repair Part (#8371): a feature, which repairs the part as it evaluates (a part with nothing +/// to repair fails it, with why, and the command changes nothing); the reply is what that +/// evaluation changed, face by face. +fn repair_body(s: &mut Session, p: &Value) -> Result { + use solidcraft_doc::expr::Kind; + use solidcraft_kernel::{Continuity, SurfaceKind}; + let cmd = "body.repair"; + let name = str_(p, "body").filter(|b| !b.trim().is_empty()).ok_or_else(|| bad(cmd, "`body` must name the part to repair"))?.to_string(); + let state = s.model.state(); + let source = state.body(&name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?; + if source.body.is_mesh() { + return Err(bad(cmd, "a mesh body has no faces to repair: convert it first")); + } + let gap = expr(p, "gap").unwrap_or_else(|| "0.2 mm".into()); + check_expr(s, &gap, Kind::Length, cmd, "gap")?; + let patch_holes = bool_(p, "patch_holes").unwrap_or(false); + let v = add_feature(s, p, FeatureKind::Repair { body: name.clone().into(), gap, patch_holes })?; + let field = |k: &str| v.get(k).cloned().unwrap_or(Value::Null); + let feature = field("feature").as_u64().unwrap_or(0); + let report = s + .model + .result(feature) + .and_then(|r| r.repair.clone()) + .ok_or_else(|| crate::EngineError::Other(format!("{cmd}: the feature kept no report of the repair")))?; + let repaired = s.model.state().body(&name).map(|b| b.body.clone()); + let volume = repaired.filter(|_| report.closed).and_then(|b| solidcraft_kernel::measure(&b).ok()).map(|m| m.volume); + let surface = |k: SurfaceKind| format!("{k:?}").to_lowercase(); + let face = |face: usize, k: SurfaceKind, why: &str| RepairFace { face, surface: surface(k), why: why.to_string() }; + let done = RepairDone { + rebuilt: report.rebuilt.iter().map(|r| face(r.face, r.surface, &r.why)).collect(), + refused: report.refused.iter().map(|r| face(r.face, r.surface, &r.why)).collect(), + sewn: report.sewn.iter().map(|g| RepairSewn { faces: g.faces, gap: g.gap, at: [g.at.x, g.at.y, g.at.z] }).collect(), + holes: report + .holes + .iter() + .map(|h| { + let g = if h.continuity == Continuity::G0 { "g0" } else { "g1" }; + let edges: Vec<[f64; 3]> = h.edges.iter().map(|q| [q.x, q.y, q.z]).collect(); + RepairHole { + faces: h.faces.clone(), + continuity: g.into(), + patched: h.patched, + why: h.why.clone(), + patch: json!({"command": "surface.patch", "params": {"body": name, "edges": edges, "continuity": g}}), + } + }) + .collect(), + faces: report.faces, + largest_edge_tolerance: report.largest_edge_tolerance, + closed: report.closed, + modelling: report.modelling, + volume, + }; + let list = + |k: &str| v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); + let reply = RepairResult { + feature, + name: field("name").as_str().unwrap_or_default().to_string(), + bodies: list("bodies"), + created_bodies: list("created_bodies"), + changed_bodies: list("changed_bodies"), + removed_bodies: list("removed_bodies"), + warning: field("warning").as_str().map(str::to_string), + ms: field("ms").as_f64(), + repair: done, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + fn rename_body(s: &mut Session, p: &Value) -> Result { let cmd = "body.rename"; let old = str_(p, "body").ok_or_else(|| bad(cmd, "`body` must be a body name"))?.to_string(); @@ -1066,6 +1145,44 @@ mod tests { s.model.state().bodies.iter().map(|b| b.name.clone()).collect() } + #[test] + fn repair_part_patches_a_missing_face_as_one_undoable_feature() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); + run(&mut s, "surface.unstitch", json!({"body": "Box", "faces": [[5, 5, 10]]})); + let open = |s: &Session| s.model.state().body("Box").is_some_and(|b| b.body.is_surface()); + assert!(open(&s)); + // A hole alone: nothing is sewn, and the reason names the hole. + let err = s.execute("body.repair", &json!({"body": "Box"})).unwrap_err().to_string(); + assert!(err.contains("a loop of 4 edges"), "{err}"); + let features = s.doc.features.len(); + let v = run(&mut s, "body.repair", json!({"body": "Box", "patch_holes": true})); + assert_eq!(s.doc.features.len(), features + 1); + let done = &v["repair"]; + assert_eq!(done["holes"][0]["patched"], json!(true), "{v}"); + assert_eq!(done["holes"][0]["continuity"], json!("g0"), "{v}"); + assert_eq!(done["holes"][0]["patch"]["command"], json!("surface.patch"), "{v}"); + assert_eq!(done["faces"], json!([5, 6])); + assert_eq!((done["closed"].clone(), done["modelling"].clone()), (json!(true), json!(true))); + assert!((done["volume"].as_f64().unwrap() - 1000.0).abs() < 1e-6, "{v}"); + assert_eq!(v["changed_bodies"], json!(["Box"])); + assert!(!open(&s)); + // Saved and opened again, the feature repairs the part again. + let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert!(cold.model.state().body("Box").is_some_and(|b| !b.body.is_surface())); + run(&mut s, "edit.undo", json!({})); + assert!(open(&s)); + // A solid with nothing to repair, an unknown body, a gap out of range: refused, nothing added. + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "Solid"})); + for p in + [json!({"body": "Solid"}), json!({"body": "Nope"}), json!({}), json!({"body": "Box", "gap": "5 mm"}), json!({"body": "Box", "gap": "-1"})] + { + let n = s.doc.features.len(); + assert!(s.execute("body.repair", &p).is_err(), "{p}"); + assert_eq!(s.doc.features.len(), n, "{p}"); + } + } + #[test] fn body_rename_preserves_plastic_rules_and_current_visibility_through_history() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 506101442..816143638 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -2343,16 +2343,8 @@ fn clearance_diameter(size: &str, fit: &str) -> Option { /// The pitches to try for a plain `M` that has no ISO coarse pitch, `None` for anything else. fn fine_only_hint(t: &str) -> Option { - const PITCHES: [f64; 9] = [2.0, 1.5, 1.25, 1.0, 0.75, 0.5, 0.35, 0.25, 0.2]; let diameter = t.trim().strip_prefix(['M', 'm']).and_then(|d| d.trim().parse::().ok()); - if let Some(d) = diameter.filter(|d| d.is_finite() && *d > 0.2 && *d <= 1e4) { - let first = PITCHES.iter().position(|p| *p <= 0.12 * d).unwrap_or(PITCHES.len() - 1); - let pitches: Vec = PITCHES.iter().skip(first).take(2).filter(|p| **p < d).map(|p| format!("M{d}x{p}")).collect(); - if !pitches.is_empty() { - return Some(format!("M{d} has no coarse ISO pitch: give one, e.g. {}", pitches.join(" or "))); - } - } - None + diameter.and_then(solidcraft_doc::thread_forms::no_coarse_pitch) } /// Largest nominal diameter automatic thread sizing knows (the last ISO coarse size). diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 53db16ec3..aeb96898d 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -968,7 +968,14 @@ fn loft_cut_through_a_shelled_basin_in_either_order() { assert!(r.is_ok(), "{pad:?} reverse {reverse}: {r:?}"); let v = volume(&mut s); assert!((v - want).abs() < 1.0, "{pad:?} reverse {reverse}: {v} vs {want}"); - assert_eq!(measure(&mut s)["body_count"], 1); + // The loft's top section is the basin's whole outline at z = 10, so the cut leaves the + // walls above it touching the rest only along their outer rim: two bodies, as a cut's + // pieces are (18480 mm³ of walls from z = 10 to 30, and the floor part below). + let m = measure(&mut s); + assert_eq!(m["body_count"], 2, "{m}"); + let upper = + m["bodies"].as_array().unwrap().iter().find(|b| b["bbox"]["min"][2].as_f64().is_some_and(|z| (z - 10.0).abs() < 1e-9)).unwrap(); + assert!((upper["volume_mm3"].as_f64().unwrap() - 18480.0).abs() < 1e-6, "{upper}"); } } // As a new body and joined: a valid solid of positive volume either way. diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 1b7de0a78..6bdaf6e5b 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -130,7 +130,7 @@ fn exporter_up(import: &solidcraft_kernel::StepImport) -> Option<(&'static str, if import.system.trim().starts_with("SolidCraft") { return Some(("z", "SolidCraft")); } - let named = import.system.to_ascii_lowercase().contains("solidworks"); + let named = [&import.system, &import.preprocessor, &import.description].iter().any(|h| h.to_ascii_lowercase().contains("solidworks")); named.then_some(("y", "SolidWorks")) } diff --git a/crates/engine/src/cmd/joints_cam_tests.rs b/crates/engine/src/cmd/joints_cam_tests.rs index 3ed46a746..780426cd3 100644 --- a/crates/engine/src/cmd/joints_cam_tests.rs +++ b/crates/engine/src/cmd/joints_cam_tests.rs @@ -158,7 +158,9 @@ fn picked_edges_give_the_sketch_s_table() { s.doc.assembly.links.first().map(|l| (l.lift.clone(), l.offset)).unwrap_or_default() }; let (sketch, a) = table(json!({"sketch": "CamSketch"})); - let (edges, b) = table(json!({"edges": [[E + R, 0, 5]]})); + // Picked on the rim a quarter turn from where the extruded circle's seam meets it: a pick on + // that vertex could be either edge. + let (edges, b) = table(json!({"edges": [[E, R, 5]]})); assert_eq!((sketch.len(), edges.len()), (360, 360)); assert!(sketch.iter().zip(&edges).all(|(x, y)| close(*x, *y, 1e-3)) && close(a, b, 1e-3)); // A second disc of the cam's component touching it in the same plane is not part of its loop. @@ -171,7 +173,7 @@ fn picked_edges_give_the_sketch_s_table() { assert!(touching.len() == 360 && touching.iter().zip(&sketch).all(|(x, y)| close(*x, *y, 1e-3)), "{touching:?}"); let mut s = cam_on_base(); tappet(&mut s, 0.0, E + R); - run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E + R, 0, 5]]}})); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E, R, 5]]}})); assert!(matches!( s.doc.assembly.links.first().and_then(|l| l.coupling.clone()), Some(Coupling::Cam(c)) if matches!(&c.profile, CamProfile::Edges { names, .. } if names.first().is_some_and(|n| !n.is_empty())) diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index b8ca196fa..7dd5023ea 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -235,21 +235,40 @@ fn interference_finds_a_peg_overlapping_a_small_rib() { assert!((lo[0].as_f64().unwrap_or(0.0) - 19.7).abs() < 1e-6 && (hi[0].as_f64().unwrap_or(0.0) - 19.85).abs() < 1e-6, "{i}"); } -/// An arc revolved up to a post ends on the post's wall, where the two bodies can't be -/// intersected: the pair is listed as unchecked instead of passing as clear. +/// A pair interference can't check is listed as unchecked, with its reason, instead of passing +/// as clear. Truck could not intersect an arc revolved up to a post's wall; SMLib does, exactly, +/// so the pair that can't be checked is now an imported mesh beside a solid. #[test] fn interference_lists_a_pair_it_could_not_check() { + // A quarter ring revolved round z through the post, brought in as an imported mesh (an STL + // of it): a mesh body has no exact surfaces to intersect, so its pair with the post is listed + // as not checked, with the reason, rather than read as clear. + let dir = std::env::temp_dir().join(format!("solidcraft-unchecked-pair-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let stl = dir.join("arc.stl"); + let mut source = Session::default(); + run(&mut source, "sketch.create", json!({"name": "Profile", "plane": "XZ"})); + run(&mut source, "sketch.rectangle.two_point", json!({"p0": [10, 0], "p1": [15, 5]})); + run(&mut source, "sketch.finish", json!({})); + run( + &mut source, + "solid.revolve", + json!({"sketch": "Profile", "axis": {"origin": [0, 0, 0], "dir": [0, 0, 1]}, "angle": "90 deg", "body_name": "Arc"}), + ); + run(&mut source, "file.export", json!({"path": stl.to_string_lossy()})); let mut s = Session::default(); run(&mut s, "solid.cylinder", json!({"base": [0, 14, -5], "radius": 4, "height": 15, "body_name": "Post"})); - run(&mut s, "sketch.create", json!({"name": "Profile", "plane": "XZ"})); - run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 0], "p1": [15, 5]})); - run(&mut s, "sketch.finish", json!({})); - run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"origin": [0, 0, 0], "dir": [0, 0, 1]}, "to": [4, 14, 2], "body_name": "Arc"})); + run(&mut s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); + let _ = std::fs::remove_dir_all(&dir); + let mesh: Vec = s.world_state().unwrap().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect(); + assert_eq!(mesh.len(), 1, "{mesh:?}"); let i = run(&mut s, "inspect.interference", json!({})); assert_eq!(i["count"], 0, "{i}"); let unchecked = i["unchecked"].as_array().cloned().unwrap_or_default(); assert_eq!(unchecked.len(), 1, "{i}"); - assert!(unchecked[0]["reason"].as_str().is_some_and(|r| r.starts_with("not verified") && !r.contains("displacement")), "{i}"); + assert_eq!(unchecked[0]["a"].as_str(), mesh.first().map(String::as_str), "{i}"); + assert_eq!(unchecked[0]["reason"], "mesh body: not checked", "{i}"); // Bodies that are clear of each other, or overlap plainly, leave the list empty. let mut s = two_cubes(); let i = run(&mut s, "inspect.interference", json!({})); diff --git a/crates/engine/src/cmd/script_tests.rs b/crates/engine/src/cmd/script_tests.rs index 1528d6174..a091f1dc4 100644 --- a/crates/engine/src/cmd/script_tests.rs +++ b/crates/engine/src/cmd/script_tests.rs @@ -103,12 +103,13 @@ fn ids_names_suppression_marker_and_failures_survive() { run(&mut s, "parameters.add", json!({"name": "twice_depth", "expression": format!("{depth} * 2")})); run(&mut s, "parameters.comment", json!({"name": depth, "comment": "plate depth"})); run(&mut s, "parameters.favorite", json!({"name": depth})); - // A fillet that a parameter change makes too big fails, and the design keeps it. + // A fillet that a parameter change makes impossible (a radius below zero) fails, and the + // design keeps it. (A convex round wider than its faces is built now, by subtraction.) run(&mut s, "parameters.add", json!({"name": "r", "expression": "1 mm"})); // Pick only the plate's edge, clear of the overlapping box's edge. run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": "r"})); let fillet = s.doc.features.last().unwrap().id; - run(&mut s, "parameters.change", json!({"name": "r", "expression": "50 mm"})); + run(&mut s, "parameters.change", json!({"name": "r", "expression": "-1 mm"})); assert!(s.model.result(fillet).and_then(|r| r.error.clone()).is_some(), "the fillet fails"); run(&mut s, "timeline.rollback", json!({"position": 3})); let mut t = replay(&script(&mut s)); diff --git a/crates/engine/src/cmd/sketch_face_tests.rs b/crates/engine/src/cmd/sketch_face_tests.rs index 31602ad32..6669201cf 100644 --- a/crates/engine/src/cmd/sketch_face_tests.rs +++ b/crates/engine/src/cmd/sketch_face_tests.rs @@ -75,11 +75,26 @@ fn explicit_rebind_preserves_geometry_dimensions_context_and_one_undo() { #[test] fn unsupported_face_has_explicit_fixed_alternative_and_no_live_projection() { let mut s = Session::default(); - // A top half Offset Face raised: no construction certificate and no exact history name yet. - run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Base"})); - run(&mut s, "solid.split_face", json!({"faces":[[10,15,20]],"plane":{"origin":[20,0,0],"normal":[1,0,0]}})); - run(&mut s, "solid.offset_face", json!({"faces":[[10,15,20]],"distance":5})); - let mut pick = top_pick(&s, "Base"); + // A rib's wall: a rib reports no roles for the faces it builds (Traced::unnamed), so the + // wall has no construction certificate and no exact history name to attach by. + run(&mut s, "solid.box", json!({"length":40,"width":20,"height":5,"corner":[0,0,0],"body_name":"L"})); + run(&mut s, "solid.box", json!({"length":5,"width":20,"height":40,"corner":[0,0,0],"operation":"join"})); + run(&mut s, "sketch.create", json!({"plane":{"origin":[0,10,0],"x_dir":[1,0,0],"y_dir":[0,0,1]},"name":"RibSketch"})); + run(&mut s, "sketch.line", json!({"points":[[5,25],[25,5]],"ids":["l1"]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.rib", json!({"sketch":"RibSketch","curves":["l1"],"thickness":4})); + let mut pick = { + let world = s.world_state().unwrap(); + let body = world.body("L").unwrap(); + let face = body + .body + .faces(0.01) + .unwrap() + .into_iter() + .find(|face| face.plane_normal.is_some_and(|n| n.dot(Vec3::Y) > 0.999) && (face.centroid.y - 12.0).abs() < 1e-6) + .unwrap(); + json!({"body":"L","index":face.index,"face":[face.centroid.x,face.centroid.y,face.centroid.z]}) + }; let before = s.doc.to_json(); let error = s.execute("sketch.create", &json!({"plane":pick})).unwrap_err(); assert!(error.to_string().contains("fixed"), "{error}"); @@ -353,6 +368,10 @@ fn freezing_rebuilt_arc_borders_keeps_authored_dimension_entity_indices() { run(&mut s, "sketch.line", json!({"points":[format!("{arc}.end"),format!("{arc}.start")],"infer":false})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch":profile,"distance":10,"operation":"new","body_name":"Sector"})); + // A notch clear of the sector until `notch` moves it across the arc at 90°: then the top face's + // arc border is rebuilt in two arcs and the notch's sides. + run(&mut s, "parameters.add", json!({"name":"notch","expression":"30 mm"})); + run(&mut s, "solid.box", json!({"corner":["-1 mm","notch","-1 mm"],"length":2,"width":2,"height":12,"operation":"cut","targets":["Sector"]})); let pick = top_pick(&s, "Sector"); let id = run(&mut s, "sketch.create", json!({"plane":pick}))["sketch"].as_u64().unwrap(); let circle = run(&mut s, "sketch.circle.center", json!({"center":[20,20],"radius":2}))["curves"][0].as_str().unwrap().to_owned(); @@ -360,7 +379,8 @@ fn freezing_rebuilt_arc_borders_keeps_authored_dimension_entity_indices() { run(&mut s, "sketch.finish", json!({})); let before_count = s.model.state().sketch(id).unwrap().sketch.curves.len(); run(&mut s, "parameters.change", json!({"name":"turn","expression":"300 deg"})); - assert!(s.model.result(id).unwrap().error.is_none()); + run(&mut s, "parameters.change", json!({"name":"notch","expression":"9 mm"})); + assert!(s.model.result(id).unwrap().error.is_none(), "{:?}", s.model.result(id).unwrap().error); let visible = s.model.state().sketch(id).unwrap().sketch.clone(); assert_ne!(visible.curves.len(), before_count, "fixture must rebuild projected topology"); let mut pick = top_pick(&s, "Sector"); @@ -744,17 +764,29 @@ fn a_sketch_on_a_face_meshes_its_body_once() { assert!(s.model.state().body("Base").unwrap().cached_mesh().is_some(), "the sketch's projection meshed a copy of the body"); } /// Issue 6720: a face picked by its point alone was refused on a body with many faces. The -/// search charged the whole mesh once per face, and the 5 000 facets a modelled thread leaves -/// put a plain block past the limit. The search reads each face's own triangles now. +/// search charged the whole mesh once per face, and the 5 000 facets a modelled thread left put a +/// plain block past the limit. The search reads each face's own triangles now. A modelled thread +/// is a few exact helical faces on SMLib, so the many faces are a block drilled with 256 holes: +/// the old charge (every face times the whole mesh) is past the 2 000 000 budget, the new one +/// (the mesh once, plus a test per face) well inside it. #[test] -fn a_face_picked_by_point_on_a_block_with_a_modelled_thread_is_found() { +fn a_face_picked_by_point_on_a_block_with_many_faces_is_found() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"corner":[-20,-20,0],"length":40,"width":40,"height":20,"body_name":"Block"})); - run(&mut s, "solid.cylinder", json!({"base":[0,0,-1],"radius":3.4,"height":22,"body_name":"Bore"})); - run(&mut s, "solid.combine", json!({"target":"Block","tools":["Bore"],"operation":"cut"})); - run(&mut s, "solid.thread", json!({"face":[3.4,0,10],"designation":"M8","modeled":true})); - assert!(s.model.state().body("Block").unwrap().body.face_count() > 1000); - run(&mut s, "sketch.create", json!({"plane":{"face":[15,15,20],"fixed":true}})); + run(&mut s, "sketch.create", json!({"plane":"XY","offset":20,"name":"Drills"})); + for i in 0..16 { + for j in 0..16 { + run(&mut s, "sketch.point", json!({"point":[-15.0 + 2.0 * f64::from(i), -15.0 + 2.0 * f64::from(j)]})); + } + } + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.hole", json!({"sketch":"Drills","diameter":0.8})); + let body = s.model.state().body("Block").unwrap().body.clone(); + // The search's own mesh (sketch_face: the tolerance it meshes the body at). + let mesh = body.mesh(&solidcraft_kernel::MeshTolerance::chord((body.size() * 1e-4).max(1e-5))).unwrap(); + let (faces, triangles) = (body.face_count(), mesh.triangles.len()); + assert!(faces > 256 && faces * triangles > 2_000_000 && faces + triangles < 2_000_000, "{faces} faces, {triangles} triangles"); + run(&mut s, "sketch.create", json!({"plane":{"face":[19,19,20],"fixed":true}})); let plane = run(&mut s, "sketch.inspect", json!({}))["plane"].clone(); assert!((plane["origin"][2].as_f64().unwrap() - 20.0).abs() < 1e-6, "{plane}"); } diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index c0e16df1f..feaebfecc 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -270,6 +270,9 @@ fn add_link_unless_present( // The link is the edge that was picked, not whichever is nearest the picked point later. let edge_name = solidcraft_doc::project::resolved_edge_name(&st, &r); let link = sk.add_link_with_wires(kind, r.source, &r.geom, &r.wires)?; + // The wires' exact curves, as a refresh of the link gives them (an included edge's record + // curve): a link made now is the one its sketch would resolve. + sk.set_link_wire_curves(&link, &r.exact)?; if let Some(l) = sk.links.iter_mut().find(|l| l.id == link) { l.face_name = name; l.edge_name = edge_name; diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index 0f5a9e451..7a49f87c1 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -452,10 +452,11 @@ fn tilted_circles_project_to_exact_ellipses_and_splines_stay_splines() { run(&mut s, "sketch.create", json!({"plane": "XY", "offset": -10})); // The base circle (centred at the origin) seen from above. let r = run(&mut s, "sketch.project", json!({"refs": [{"edge": [0, 5, 0]}]})); - // One seam half: exact conics (rational quadratic arcs). + // The rim is one closed circle edge: an exact ellipse, x semi-axis 5·cos 45° (the tilt), y 5. let si = inspect(&mut s); let c = si["curves"].as_array().unwrap().iter().find(|c| c["id"] == r["links"][0]["curves"][0]).unwrap().clone(); - assert_eq!(c["type"], "conic", "{c}"); + assert_eq!(c["type"], "ellipse", "{c}"); + assert!((c["minor_radius"].as_f64().unwrap() - 5.0 * std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{c}"); let st = s.model.state(); let sk = &st.sketch(s.active_sketch.unwrap()).unwrap().sketch; for ci in sk.link_curves(r["links"][0]["link"].as_str().unwrap()) { @@ -465,7 +466,7 @@ fn tilted_circles_project_to_exact_ellipses_and_splines_stay_splines() { assert!((e - 1.0).abs() < 1e-9, "{q:?}"); } } - // The whole face (both halves of its rim, plus its seam) gives the full ellipse. + // The whole face (its rim, plus its seam) gives the full ellipse. let r = run(&mut s, "sketch.project", json!({"refs": [{"face": [0, 0, 0]}]})); let si = inspect(&mut s); let types: Vec = r["links"][0]["curves"] @@ -708,11 +709,18 @@ fn a_face_engraved_with_text_projects_its_letters_exactly_and_extrudes() { assert!(r.error.is_none(), "{r:?}"); let face = before - volume(&mut s); assert!((face - taken).abs() < 1e-6 * before, "{face} {taken}"); - // Its sketch got the letters as Bézier pieces. + // Its sketch got the letters as their exact pieces: the outline's quadratic Béziers, which are + // parabolic arcs, come in as conics (or as control-point splines). let st = s.model.state(); let sketch = &st.sketches.last().unwrap().sketch; - let pieces = - sketch.curves.iter().filter(|c| c.link.is_some() && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. })).count(); + let pieces = sketch + .curves + .iter() + .filter(|c| { + c.link.is_some() + && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. } | solidcraft_sketch::CurveKind::Conic { .. }) + }) + .count(); assert!(pieces > 100, "{pieces}"); } @@ -730,12 +738,23 @@ fn a_face_sketch_saved_with_fitted_letters_reopens_and_builds_the_same() { let r = s.model.result(id).unwrap(); assert!(r.error.is_none(), "{name}: {:?}", r.error); } - // The build that saved it measured 5916.018831 mm³. - assert!((volume - 5916.018830904924).abs() < 1e-3, "{volume}"); + // The 30 x 20 x 10 block less the "S" 1 deep (its profile's exact area, Sketch2's smaller + // region) and the r 2 circle 3 deep, clear of the letter: 5916.010767. (The build that saved + // it measured 5916.018831, 8e-3 off; SMLib's integral is within 1e-8 of the closed form.) + let letter = s.model.state().sketches.iter().find(|k| k.name == "Sketch2").unwrap().profiles.iter().map(|p| p.area).fold(f64::INFINITY, f64::min); + let want = 6000.0 - letter - 3.0 * std::f64::consts::PI * 4.0; + assert!((volume - want).abs() < 1e-8 * 6000.0, "{volume} vs {want}"); + // The letter's exact pieces in the face's link: its quadratic Béziers, as conics (or splines). let st = s.model.state(); let sketch = &st.sketches.last().unwrap().sketch; - let pieces = - sketch.curves.iter().filter(|c| c.link.is_some() && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. })).count(); + let pieces = sketch + .curves + .iter() + .filter(|c| { + c.link.is_some() + && matches!(c.kind, solidcraft_sketch::CurveKind::Spline { control: true, .. } | solidcraft_sketch::CurveKind::Conic { .. }) + }) + .count(); assert!(pieces > 0, "{pieces}"); } @@ -812,6 +831,21 @@ fn intersect_curves(steps: &[(&str, Value)], plane: Value) -> std::result::Resul Ok(linked_curves(&inspect(&mut s))) } +/// The lines among `curves` as an outline: each line's ends rounded and the lower first, the lines +/// sorted. A section's chains are walked from either end (the mesh's triangle order picks which), +/// so a line's direction says nothing about the cut. +fn outline(curves: &[Value]) -> Vec<[f64; 4]> { + let mut ends: Vec<[f64; 4]> = line_ends(curves) + .into_iter() + .map(|e| { + let e = e.map(f64::round); + if [e[2], e[3]] < [e[0], e[1]] { [e[2], e[3], e[0], e[1]] } else { e } + }) + .collect(); + ends.sort_by(|a, b| a.partial_cmp(b).unwrap()); + ends +} + fn line_ends(curves: &[Value]) -> Vec<[f64; 4]> { let at = |c: &Value, k: &str, i: usize| c[k][i].as_f64().unwrap_or(f64::NAN); curves @@ -827,10 +861,8 @@ fn line_ends(curves: &[Value]) -> Vec<[f64; 4]> { fn intersect_keeps_its_exact_cuts() { let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))]; for offset in [10, 0] { - let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": offset})).unwrap()); - ends.iter_mut().for_each(|e| *e = e.map(|v| v.round())); - ends.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]], "offset {offset}"); + let ends = outline(&intersect_curves(&block, json!({"plane": "XY", "offset": offset})).unwrap()); + assert_eq!(ends, vec![[0.0, 0.0, 0.0, 30.0], [0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 40.0, 30.0], [40.0, 0.0, 40.0, 30.0]], "offset {offset}"); } for (steps, plane, radius) in [ (vec![("solid.cylinder", json!({"base": [0, 0, 0], "radius": 7, "height": 30}))], json!({"plane": "XY", "offset": 12}), 7.0), @@ -839,11 +871,25 @@ fn intersect_keeps_its_exact_cuts() { let c = intersect_curves(&steps, plane).unwrap(); assert!(c.len() == 1 && c[0]["type"] == "circle" && (c[0]["radius"].as_f64().unwrap() - radius).abs() < 1e-4, "{c:?}"); } + // The tilted cylinder's cut is an ellipse the section leaves as the mesh's segments, as many + // as the tessellation crosses (21 on truck's mesh, 20 on SMLib's): each end on the cylinder + // within the section's own reach of the surface, the display tolerance (a thousandth of the + // mesh's size, doc::project::fit_segments), which the old pin of one end to 1e-4 assumed of + // one mesh. let tilted = [("solid.cylinder", json!({"base": [0, 0, 0], "radius": 5, "height": 40, "axis": [1, 0, 1]}))]; - let ends = line_ends(&intersect_curves(&tilted, json!({"plane": "XY", "offset": 10})).unwrap()); - assert_eq!(ends.len(), 21); - let first = [2.941, -0.2891, 3.3932, -1.7819]; - assert!(ends[0].iter().zip(first).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", ends[0]); + let curves = intersect_curves(&tilted, json!({"plane": "XY", "offset": 10})).unwrap(); + let ends = line_ends(&curves); + assert!(ends.len() == curves.len() && ends.len() >= 16, "{curves:?}"); + let axis = solidcraft_geom::Vec3::new(1.0, 0.0, 1.0).normalized().unwrap(); + // The cylinder's box: its axis 40 along (1, 0, 1)/√2 and its ends' discs of radius 5 span + // (40 + 2·5)/√2 in x and z and 10 in y. + let span = 50.0 * std::f64::consts::FRAC_1_SQRT_2; + let reach = 1e-3 * (2.0 * span * span + 100.0).sqrt(); + for e in &ends { + for p in [solidcraft_geom::Vec3::new(e[0], e[1], 10.0), solidcraft_geom::Vec3::new(e[2], e[3], 10.0)] { + assert!(((p - axis * p.dot(axis)).len() - 5.0).abs() < reach, "{p:?}"); + } + } } /// A plane crossing a curved face's rim cuts it on the surface, not on the mesh's chord: a @@ -870,8 +916,6 @@ fn intersect_crosses_a_curved_face_on_the_surface() { #[test] fn intersect_on_a_top_face_gives_its_outline() { let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))]; - let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": 20})).unwrap()); - ends.iter_mut().for_each(|e| *e = e.map(|v| v.round())); - ends.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]]); + let ends = outline(&intersect_curves(&block, json!({"plane": "XY", "offset": 20})).unwrap()); + assert_eq!(ends, vec![[0.0, 0.0, 0.0, 30.0], [0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 40.0, 30.0], [40.0, 0.0, 40.0, 30.0]]); } diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 0383998f5..dc1d320e0 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -19,7 +19,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.patch", "Patch", patch) .at("SURFACE", "CREATE") .icon("surface_patch") - .params("sketch?: id|name and profiles? (planar patches of sketch regions) | edges: [[x,y,z]] (points on a closed loop of a body's edges: one face on them, planar when the loop is, else a smooth B-spline surface) and body?; continuity?: g0|g1|g2 (edges only, default g0: how the patch meets the faces beside the loop — g1 their tangent planes, g2 also their curvature across the edges) or [{edge: [x,y,z], g: g0|g1|g2}] (those edges so, the rest g0) or {all, edges}; points?: [[x,y,z]] (edges only, up to 64: points the patch passes through); crown?: number −0.9…3 (default 0: only a fitted patch, whose middle becomes fuller by this many times the loop's size — the bump vanishes on the loop, so the face still meets the picked edges and the continuity across them; a loop that is planar and g0 is the exact plane whatever the crown; with points, crown needs a g1 or g2 edge); name?, body_name?"), + .params("sketch?: id|name and profiles? (planar patches of sketch regions) | edges: [[x,y,z]] (points on a closed loop of a body's edges: one face on them, planar when the loop is, else a smooth B-spline surface) and body?; continuity?: g0|g1|g2|g3|g4 (edges only, default g0: how the patch meets the faces beside the loop — g1 their tangent planes, g2 also their curvature across the edges, g3 also its rate of change, g4 the change of that rate) or [{edge: [x,y,z], g: g0|g1|g2|g3|g4}] (those edges so, the rest g0) or {all, edges}; points?: [[x,y,z]] (edges only, up to 64: points the patch passes through); crown?: number −0.9…3 (default 0: only a fitted patch, whose middle becomes fuller by this many times the loop's size — the bump vanishes on the loop, so the face still meets the picked edges and the continuity across them; a loop that is planar and g0 is the exact plane whatever the crown; with points, crown needs a g1 or higher edge); name?, body_name?"), CommandSpec::new("surface.stitch", "Stitch", stitch) .at("SURFACE", "MODIFY") .icon("surface_stitch") diff --git a/crates/engine/src/face_name_tests.rs b/crates/engine/src/face_name_tests.rs index e2e5b9b13..672d5cc99 100644 --- a/crates/engine/src/face_name_tests.rs +++ b/crates/engine/src/face_name_tests.rs @@ -43,8 +43,8 @@ fn top_and_hole_names(s: &mut Session) -> (String, Vec) { } /// A 60 x 40 x 10 plate with a hole of radius 5: its top face is a rectangle with a hole in it, -/// whose centroid (the plate's middle, (30, 20, 10)) is in the hole; the hole's wall is two half -/// cylinders, whose centroids are inside the cylinder, 2r/π from its axis. +/// whose centroid (the plate's middle, (30, 20, 10)) is in the hole; the hole's wall is one +/// whole cylinder (SMLib's, closed on its seam), whose centroid is on its axis, halfway up. #[test] fn model_faces_gives_a_point_on_each_face_and_the_hole_axis_and_radius() { let mut s = Session::default(); @@ -61,10 +61,10 @@ fn model_faces_gives_a_point_on_each_face_and_the_hole_axis_and_radius() { Some(c) => { let radial = (at.x - 30.0).hypot(at.y - 20.0); assert!((radial - 5.0).abs() < 1e-9 && at.z > 0.0 && at.z < 10.0, "{at:?}"); - // The centroid of a half cylinder's wall is 2r/π = 3.18 from the axis, not on the wall. + // The centroid of a whole cylinder's wall is on its axis, not on the wall. let centroid = vec(&f["centroid"]); let inside = (centroid.x - 30.0).hypot(centroid.y - 20.0); - assert!((2.5..4.0).contains(&inside), "the centroid of a half cylinder is inside it: {inside}"); + assert!(inside < 1e-9 && (centroid.z - 5.0).abs() < 1e-9, "the centroid of the hole's wall is on its axis: {centroid:?}"); // The hole's axis: the line through (30, 20) along z, its radius 5. let (origin, axis) = (vec(&c["origin"]), vec(&c["axis"])); assert!((origin.x - 30.0).abs() < 1e-9 && (origin.y - 20.0).abs() < 1e-9, "{origin:?}"); @@ -122,10 +122,11 @@ fn convert_to_sheet_metal_takes_the_plates_face_by_name() { let span = at.iter().cloned().fold(f64::MIN, f64::max) - at.iter().cloned().fold(f64::MAX, f64::min); assert!(span > 9.8 && span < 10.0 + 1e-6, "{span}"); } - // The plate is still 100 x 60 x 2.5 less the hole: 15000 - π·5²·2.5 = 14803.65 mm³ for a round hole, a little more - // (less than 2% of the hole's 196.35 mm³) for a polygon inside the circle. + // The plate is still 100 x 60 x 2.5 less the hole, which is round: 15000 - π·5²·2.5 = + // 14803.65 mm³, within the measure's accuracy (SMLib's mass properties come within 2e-7 of + // a closed form). let (v, round) = (volume(&mut s, "Plate"), 15000.0 - 25.0 * PI * 2.5); - assert!(v >= round - 1e-6 && v - round < 0.02 * 25.0 * PI * 2.5, "{v}"); + assert!((v - round).abs() < 2e-7 * round, "{v} vs {round}"); } /// Shell, draft and offset face share the parser of Delete Face. @@ -207,8 +208,8 @@ fn offset_face_takes_the_face_by_name() { assert!((volume(&mut s, "Tray") - 100.0 * 60.0 * 35.0).abs() < 1e-6, "{}", volume(&mut s, "Tray")); } -/// A cylinder of radius 10 and height 20 has a side of two half cylinders, each of which -/// `model.faces` describes (its axis and radius); drafting them 5 degrees from the base plane makes +/// A cylinder of radius 10 and height 20 has one side face (SMLib's, closed on its seam), which +/// `model.faces` describes (its axis and radius); drafting it 5 degrees from the base plane makes /// a frustum of radius 10 at the base and 10 - 20 tan 5 degrees at the top. #[test] fn draft_takes_a_cylinders_side_by_name() { @@ -216,7 +217,7 @@ fn draft_takes_a_cylinders_side_by_name() { run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20, "body_name": "Pin"})); let all = faces(&mut s, "Pin"); let sides: Vec<&Value> = all.iter().filter(|f| f.get("cylinder").is_some()).collect(); - assert_eq!(sides.len(), 2, "two half cylinders: {all:?}"); + assert_eq!(sides.len(), 1, "one side: {all:?}"); for side in &sides { assert!((side["cylinder"]["radius"].as_f64().unwrap_or(f64::NAN) - 10.0).abs() < 1e-9, "{side}"); } diff --git a/crates/engine/src/naming_history_tests.rs b/crates/engine/src/naming_history_tests.rs index 4c6fcfb10..97560d42f 100644 --- a/crates/engine/src/naming_history_tests.rs +++ b/crates/engine/src/naming_history_tests.rs @@ -414,10 +414,10 @@ fn named_at(faces: &[(String, bool, [f64; 3])], at: [f64; 3]) -> String { } /// #1209: an arm with a boss at each end (each boss the radius of the arm's round end under it) -/// and a square cut through one. The second boss and the cut are prism booleans sewn slab by -/// slab, where the arm's round end and the boss over it are two pieces of one cylinder: every -/// face keeps exact history, so the cut's walls are its own four faces and the boss's outer -/// cylinder keeps its name, through the fillets on the bore's corners too. +/// and a square cut through one. The arm's round end and the boss over it lie on one cylinder, +/// which SMLib keeps one face, named for the arm's end it began as: every face keeps exact +/// history, so the cut's walls are its own four faces and the boss's outer cylinder keeps its +/// name, through the fillets on the bore's corners too. #[test] fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { let mut s = Session::default(); @@ -437,8 +437,10 @@ fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"distance": 16, "body_name": "Arm"})); run(&mut s, "solid.cylinder", json!({"diameter": 46.0, "height": 22, "base": [0, 0, 0], "operation": "join", "targets": ["Arm"]})); - let boss = named_at(&listed(&mut s, "Arm"), [19.98, -4.24, 19.0]); - assert!(boss.starts_with("F3:side"), "{boss}"); + // A point on the boss's outer wall, above the arm. + let wall = |s: &Session| solidcraft_doc::naming::face_names_at(&s.model.state(), &[Vec3::new(-23.0, 0.0, 19.0)]).pop().unwrap_or_default(); + let boss = wall(&s); + assert!(boss.starts_with("F2:side:a"), "{boss}"); run(&mut s, "solid.cylinder", json!({"diameter": 30.0, "height": 20, "base": [170.0, 0, 0], "operation": "join", "targets": ["Arm"]})); let joined = listed(&mut s, "Arm"); assert!(joined.iter().all(|(_, exact, _)| *exact), "{joined:?}"); @@ -453,47 +455,57 @@ fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { for (at, line) in [([0.0, -6.35, 11.0], "l1"), ([6.35, 0.0, 11.0], "l2"), ([0.0, 6.35, 11.0], "l3"), ([-6.35, 0.0, 11.0], "l4")] { assert_eq!(named_at(&cut, at), format!("F6:side:{line}")); } - assert_eq!(named_at(&cut, [19.98, -4.24, 19.0]), boss); + assert_eq!(wall(&s), boss); run(&mut s, "solid.fillet", json!({"edges": [[6.35, 6.35, 10], [-6.35, 6.35, 10], [-6.35, -6.35, 10], [6.35, -6.35, 10]], "radius": 1.5})); let filleted = listed(&mut s, "Arm"); let blends = filleted.iter().filter(|(n, _, _)| n.starts_with("F7:blend:")).count(); assert_eq!(blends, 4, "{filleted:?}"); - assert_eq!(named_at(&filleted, [19.98, -4.24, 19.0]), boss); + assert_eq!(wall(&s), boss); } -/// #3902: a torus with a closed, twisted square sweep cut inside it splits the sweep's walls into -/// pieces the kernel returns in a different order on each evaluation. The pieces are numbered by -/// where they lie, so every fresh evaluation gives each piece the same name. +/// A disc whose top a round groove along x splits into two pieces of one name, numbered by +/// place: `F1:top#1` on the -y side, `F1:top#2` on the +y side. +fn grooved_disc() -> Value { + json!([ + {"command": "solid.cylinder", "params": {"radius": 20, "height": 10, "body_name": "Disc"}}, + {"command": "solid.cylinder", "params": {"axis": [1, 0, 0], "base": [-25, 0, 10], "radius": 3, "height": 60, "operation": "cut"}} + ]) +} + +/// #3902: a torus with a closed, twisted square sweep cut inside it split the sweep's walls into +/// pieces truck returned in a different order on each evaluation (SMLib keeps those walls +/// whole), and a grooved disc's top is two pieces of one name. Pieces are numbered by where they +/// lie, so every fresh evaluation gives each face the same name. #[test] fn split_pieces_keep_their_numbers_across_evaluations() { - let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/closed_sweep_torus_cut.json")).unwrap(); - let mut s = Session::default(); - s.run_script(&script).unwrap(); - let body = s.model.state().bodies.first().map(|b| b.name.clone()).expect("a body"); - let named = |s: &mut Session| -> Vec<(String, [i64; 3])> { - let mut faces: Vec<(String, [i64; 3])> = listed(s, &body).into_iter().map(|(n, _, c)| (n, c.map(|x| x.round() as i64))).collect(); - faces.sort(); - faces - }; - let first = named(&mut s); - assert!(first.iter().any(|(n, _)| n.contains('#')), "no split pieces: {first:?}"); - for run in 0..10 { - let mut fresh = Session::new(solidcraft_doc::Document::clone(&s.doc)); - fresh.refresh(); - assert_eq!(named(&mut fresh), first, "evaluation {run}"); + let torus: Value = serde_json::from_str(include_str!("../../../examples/regressions/closed_sweep_torus_cut.json")).unwrap(); + for (script, pieces) in [(torus, false), (grooved_disc(), true)] { + let mut s = Session::default(); + s.run_script(&script).unwrap(); + let body = s.model.state().bodies.first().map(|b| b.name.clone()).expect("a body"); + let named = |s: &mut Session| -> Vec<(String, [i64; 3])> { + let mut faces: Vec<(String, [i64; 3])> = listed(s, &body).into_iter().map(|(n, _, c)| (n, c.map(|x| x.round() as i64))).collect(); + faces.sort(); + faces + }; + let first = named(&mut s); + assert_eq!(first.iter().any(|(n, _)| n.contains('#')), pieces, "split pieces: {first:?}"); + for run in 0..10 { + let mut fresh = Session::new(solidcraft_doc::Document::clone(&s.doc)); + fresh.refresh(); + assert_eq!(named(&mut fresh), first, "evaluation {run}"); + } } } /// #3902: a design saved before the pieces of a face were numbered by place opens with the /// numbers it was saved with, so a reference to `…#1` stays on the piece it was made on. The -/// block cut by the second block here has its side split in two, numbered the other way round -/// by place. +/// grooved disc's top is split in two, numbered the other way round by place. #[test] fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { - let script: Value = serde_json::from_str(include_str!("../../../tests/action_matrix/designs/multi-body-join-cut.json")).unwrap(); let mut s = Session::default(); - s.run_script(&script).unwrap(); - let by_place = listed(&mut s, "Block"); + s.run_script(&grooved_disc()).unwrap(); + let by_place = listed(&mut s, "Disc"); // As a build before the change saved it: its features carry no mark, and the file does not // list the change among those it has. let mut file: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); @@ -509,16 +521,16 @@ fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { assert!(old.features.iter().all(|f| f.kernel_piece_order), "the features of an older design keep the old numbering"); let mut reopened = Session::new(old); reopened.refresh(); - let kept = listed(&mut reopened, "Block"); + let kept = listed(&mut reopened, "Disc"); let at = |faces: &[(String, bool, [f64; 3])], name: &str| faces.iter().find(|(n, _, _)| n == name).map(|(_, _, c)| *c); // The pieces are numbered differently by place, and the older design keeps its own numbers. - let (old1, new1) = (at(&kept, "F2:side#1").unwrap(), at(&by_place, "F2:side#1").unwrap()); + let (old1, new1) = (at(&kept, "F1:top#1").unwrap(), at(&by_place, "F1:top#1").unwrap()); assert!((0..3).any(|k| (old1[k] - new1[k]).abs() > 1.0), "{kept:?} {by_place:?}"); let mut legacy = solidcraft_doc::Document::clone(&s.doc); legacy.features.iter_mut().for_each(|f| f.kernel_piece_order = true); let mut saved_with = Session::new(legacy); saved_with.refresh(); - assert_eq!(listed(&mut saved_with, "Block"), kept); + assert_eq!(listed(&mut saved_with, "Disc"), kept); } /// The volumes of the design's bodies, by name. diff --git a/crates/engine/src/schema/browser.rs b/crates/engine/src/schema/browser.rs new file mode 100644 index 000000000..03e0d1a96 --- /dev/null +++ b/crates/engine/src/schema/browser.rs @@ -0,0 +1,117 @@ +//! Contracts and result types for the commands in `cmd/browser.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::types::{FeatureCommon, LengthExpr, feature_common}; + +/// Repair a part the modelling kernel refuses, or an open part that should be a solid: faces +/// SMLib refuses on their own are rebuilt on their own surfaces (geometry unchanged), free edges +/// that pair up within `gap` are sewn (each sewn edge carries its own gap as its tolerance; the +/// body's and the other edges' stay), and with `patch_holes` the loops of free edges left (missing +/// faces) are patched and sewn in. One undoable feature; refused, with why, when nothing applies. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct RepairParams { + /// The part (body name). + pub body: String, + /// The widest gap between two free edges that is sewn, more than 0 and at most 1 mm. + /// Default: 0.2 mm. + #[serde(default)] + pub gap: Option, + /// Patch each loop of free edges no pair explains (a missing face) and sew the patch in: the + /// plane of the faces around it where they are all that plane, else a patch tangent to them + /// (G1). Default: false (the reply offers the patches). + #[serde(default)] + pub patch_holes: Option, + #[serde(flatten, deserialize_with = "feature_common")] + pub common: FeatureCommon, +} + +/// A face rebuilt on its own surface, or one SMLib still refuses. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairFace { + /// The face's index in the part's face order before the repair (from 0). + pub face: usize, + /// Its surface: plane, cylinder, cone, sphere, torus or freeform. + pub surface: String, + /// What SMLib said about it. + pub why: String, +} + +/// Two free edges sewn into one. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairSewn { + /// The faces on either side, by index before the repair. + pub faces: [usize; 2], + /// The widest distance between the two edges, mm. + pub gap: f64, + /// A point halfway along the gap, [x, y, z]. + pub at: [f64; 3], +} + +/// A loop of free edges no pair explains: a missing face. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairHole { + /// The faces around it, by index before the repair. + pub faces: Vec, + /// g0 (a patch in the plane of the faces around it) or g1 (tangent to curved neighbours). + pub continuity: String, + /// The patch was made and sewn in. + pub patched: bool, + /// Why it was not, when `patch_holes` asked for it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub why: Option, + /// The Patch that fills it: `{command: "surface.patch", params}`. + pub patch: Value, +} + +/// What the repair did, face by face. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairDone { + pub rebuilt: Vec, + /// Faces SMLib refuses that could not be rebuilt (the part may still be taken as a whole). + pub refused: Vec, + pub sewn: Vec, + pub holes: Vec, + /// Faces before and after. + pub faces: [usize; 2], + /// The largest edge tolerance before and after, mm. + pub largest_edge_tolerance: [f64; 2], + /// The part is a closed solid now. + pub closed: bool, + /// The modelling kernel takes the part now. + pub modelling: bool, + /// Its volume, mm³, when it is a closed solid. + pub volume: Option, +} + +/// What `body.repair` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RepairResult { + /// The new feature's id. + pub feature: u64, + /// The new feature's name. + pub name: String, + /// Every body after the feature. + pub bodies: Vec, + /// The bodies the feature made. + pub created_bodies: Vec, + /// Bodies that were there before and now have other geometry. + pub changed_bodies: Vec, + /// Bodies that are gone. + pub removed_bodies: Vec, + /// A warning from the evaluation (a hole left open), or `null`. + pub warning: Option, + /// How long the feature took to evaluate, in milliseconds. + pub ms: Option, + pub repair: RepairDone, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "browser_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/browser_tests.rs b/crates/engine/src/schema/browser_tests.rs new file mode 100644 index 000000000..677355417 --- /dev/null +++ b/crates/engine/src/schema/browser_tests.rs @@ -0,0 +1,28 @@ +use serde_json::{Value, json}; + +use super::{RepairParams, RepairResult}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["body", "body_name", "body_names", "gap", "name", "participants", "patch_holes"]); +} + +#[test] +fn replies_match_the_output_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(!required.contains(&"param_warnings")); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})).unwrap(); + s.execute("surface.unstitch", &json!({"body": "Box", "faces": [[5, 5, 10]]})).unwrap(); + s.param_check = ParamCheck::Warn; + let r = s.execute("body.repair", &json!({"body": "Box", "gap": "0.1 mm", "patch_holes": true, "name": "Mend"})).unwrap(); + assert!(r.get("param_warnings").is_none(), "{r}"); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + let r = s.execute("body.repair", &json!({"body": "Box", "colour": "red"})); + assert!(r.is_err(), "nothing left to repair"); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 1ca4710f6..db9bdbcc7 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -54,6 +54,7 @@ mod coverage_tests; mod tests; // The contracts, by command file. +pub mod browser; pub mod diagnostics; pub mod features; pub mod inspect; diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs index 8f193b312..f6b6f90ee 100644 --- a/crates/engine/src/schema/tests.rs +++ b/crates/engine/src/schema/tests.rs @@ -699,7 +699,8 @@ fn shared_types_keep_the_handlers_messages() { for (id, p, probe) in [ ("solid.shell", json!({"thickness": 1, "faces": 5}), json!({"faces": 5})), ("solid.shell", json!({"thickness": 1, "faces": null}), json!({"faces": null})), - ("solid.shell", json!({"thickness": 1, "faces": []}), json!({"faces": []})), + // `solid.shell` takes no faces (a closed hollow body); the draft refuses them. + ("solid.draft", json!({"angle": 1, "faces": []}), json!({"faces": []})), ("solid.shell", json!({"thickness": 1, "faces": [true]}), json!({"faces": [true]})), ("solid.shell", json!({"thickness": 1, "faces": [""]}), json!({"faces": [""]})), ("solid.fillet", json!({"radius": 1, "edges": {}}), json!({"edges": {}})), diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs index 2ef39ac6f..f77202a2a 100644 --- a/crates/engine/src/schema/types.rs +++ b/crates/engine/src/schema/types.rs @@ -730,8 +730,8 @@ macro_rules! pick_list { pick_list!( /// The `faces` of `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face` and - /// `face.delete`, as `features::face_points` reads them. (Extrude's `faces` is a - /// [`FacesParam`].) + /// `face.delete`, as `features::face_points` reads them; `solid.shell` also takes an empty + /// list (a closed hollow body). (Extrude's `faces` is a [`FacesParam`].) FaceRefs, FaceRef, "`faces` must be a list of points or face names", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b4970349b..4087cd8ff 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -627,7 +627,9 @@ fn extrude_of_adjacent_profiles_has_whole_edges() { assert_eq!(below.len(), 2, "{si}"); run(&mut s, "solid.extrude", json!({"sketch": "Holder", "profiles": below, "distance": 23, "body_name": "Holder"})); let topo = run(&mut s, "model.faces", json!({"body": "Holder"})); - assert_eq!(topo["faces"].as_array().unwrap().len(), 5, "a cut-off cylinder: {topo}"); + // The arc side (one face: SMLib keeps a cylinder's arc of more than half a turn whole), the + // chord's flat side and the two ends. + assert_eq!(topo["faces"].as_array().unwrap().len(), 4, "a cut-off cylinder: {topo}"); let lo = run(&mut s, "inspect.measure", json!({"bodies": ["Holder"]}))["bodies"][0]["bbox"]["min"][1].as_f64().unwrap(); run(&mut s, "solid.move", json!({"bodies": ["Holder"], "translate": [0, -5.0 - lo, 0]})); // The handle: r35 on the Y axis with a bevelled end. @@ -1920,13 +1922,15 @@ fn a_checkpoint_survives_file_new() { run(&mut s, "solid.box", json!({"length": 1.0, "width": 1.0, "height": 1.0})); let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap(); run(&mut s, "file.new", json!({"name": "Replacement"})); + // The volume as SMLib integrates it, to rounding (a unit box measures 1 + 2e-16). + let volume = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN); run(&mut s, "solid.box", json!({"length": 2.0, "width": 2.0, "height": 2.0})); - assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(8.0)); + assert!((volume(&mut s) - 8.0).abs() < 1e-12); run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id})); - assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(1.0)); + assert!((volume(&mut s) - 1.0).abs() < 1e-12); // The undo history is the restored design's own: one step back is the empty design. run(&mut s, "edit.undo", json!({})); - assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(0.0)); + assert!(volume(&mut s).abs() < 1e-12); } #[test] @@ -2768,17 +2772,20 @@ fn press_pull_on_curved_faces() { let v1 = volume(&mut s); assert!(rel(v1 - v0, PI * (25.0 - 16.0) * 20.0) < 1e-3, "{v0} {v1}"); // A shell's inner wall behind a fillet (`F3:inner:F2:blend:…`) only names the fillet: it is - // offset like any curved face, not taken for the shell's fillet. (The offset itself is - // refused: the wall is tangent to its neighbours.) + // offset like any curved face, not taken for the shell's fillet. Pulled 0.5 into the cavity + // (radius 3 to 2.5), the wall alone moves, stepping in from its tangent neighbours: the + // quarter ring between the radii, 18 high, is added. let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 20})); run(&mut s, "solid.fillet", json!({"edges": [[40, 40, 10]], "radius": 5})); run(&mut s, "solid.shell", json!({"faces": [[20, 20, 20]], "thickness": 2})); let on = Vec3::new(35.0, 35.0, 10.0) + Vec3::new(1.0, 1.0, 0.0).normalized().unwrap() * 3.0; - let err = - s.execute("solid.press_pull", &json!({"face": [on.x, on.y, on.z], "distance": 0.5})).map(|v| v.to_string()).unwrap_or_else(|e| e.to_string()); - assert!(!err.contains("not a fillet's or a chamfer's"), "{err}"); - assert!(err.contains("offset"), "{err}"); + let v0 = volume(&mut s); + let out = run(&mut s, "solid.press_pull", json!({"face": [on.x, on.y, on.z], "distance": 0.5})); + assert!(out["name"].as_str().is_some_and(|n| n.starts_with("OffsetFace")) && out.get("edited").is_none(), "{out}"); + let ring = PI / 4.0 * (3.0 * 3.0 - 2.5 * 2.5) * 18.0; + // Each volume to the measure's 2e-7. + assert!((volume(&mut s) - v0 - ring).abs() < 4e-7 * v0, "{} vs {ring}", volume(&mut s) - v0); } /// A cut in one component leaves other components' bodies alone unless they are named as @@ -3208,7 +3215,12 @@ fn shell_tangent_chain_that_opens_every_face_explains_how_to_keep_walls() { assert_eq!(s.doc.to_json(), before, "a refused shell must preserve the design"); } run(&mut s, "solid.shell", json!({"faces": [[20,0,30]], "thickness": 2, "tangent_chain": false})); - assert!((volume(&mut s) - 15_305.28).abs() < 0.1); + // The rounded box (its 37 x 27 x 57 core grown by the 1.5 ball) less the cavity, which the + // 2 mm walls leave sharp, open through the front: 36 x 56 x 28. To the measure's 2e-7. + let (a, b, c, r) = (37.0, 27.0, 57.0, 1.5); + let rounded = a * b * c + 2.0 * r * (a * b + b * c + a * c) + PI * r * r * (a + b + c) + 4.0 / 3.0 * PI * r * r * r; + let want = rounded - 36.0 * 56.0 * 28.0; + assert!((volume(&mut s) - want).abs() < 2e-7 * rounded, "{} vs {want}", volume(&mut s)); assert_eq!(s.model.state().bodies.len(), 1); } @@ -4432,31 +4444,21 @@ fn creating_a_component_recomputes_nothing() { run(&mut s, "sketch.circle.center", json!({"center": [25, 25], "radius": 2})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch": "Post sketch", "to": [25, 25, 10], "operation": "new", "body_name": "Post"})); - // A plate whose top face loses its certificate: a patterned cut, a pad joined flush with - // the top, then one more cut. Extruding that face makes a sketch on a legacy face plane. + // A sketch on a face without a construction certificate: a face extrude on a plate, saved + // as a design from before face attachments were certified (no anchor), and reopened. run(&mut s, "solid.box", json!({"length": 100, "width": 100, "height": 10, "corner": [200, 0, 0], "operation": "new", "body_name": "Plate"})); - run( - &mut s, - "solid.cylinder", - json!({"diameter": 4, "height": 12, "base": [210, 10, -1], "operation": "cut", "targets": ["Plate"], "name": "Pilot"}), - ); - run( - &mut s, - "solid.pattern.rectangular", - json!({"features": ["Pilot"], "dir1": [1, 0, 0], "count1": 4, "spacing1": 20, "dir2": [0, 1, 0], "count2": 4, "spacing2": 20}), - ); - run(&mut s, "sketch.create", json!({"plane": "XY", "offset": "5 mm", "name": "Pad sketch"})); - run(&mut s, "sketch.rectangle.two_point", json!({"p0": [260, 60], "p1": [295, 95]})); - run(&mut s, "sketch.finish", json!({})); - run(&mut s, "solid.extrude", json!({"sketch": "Pad sketch", "distance": 5, "operation": "join", "targets": ["Plate"]})); - run(&mut s, "solid.box", json!({"length": 5, "width": 100, "height": 12, "corner": [199, 0, -1], "operation": "cut", "targets": ["Plate"]})); run(&mut s, "solid.extrude", json!({"face": [240, 40, 10], "distance": 1, "operation": "join", "name": "Face layer"})); - let legacy_face = s - .doc - .features - .iter() - .any(|f| matches!(&f.kind, solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: None, .. }, .. })); - assert!(legacy_face, "the face extrude's sketch is on a legacy face plane"); + let mut legacy = (*s.doc).clone(); + let mut legacy_face = false; + for f in &mut legacy.features { + if let solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor, .. }, .. } = &mut f.kind { + *anchor = None; + legacy_face = true; + } + } + assert!(legacy_face, "the face extrude's sketch is on a face plane"); + let mut s = Session::new(solidcraft_doc::Document::from_json(&legacy.to_json()).unwrap()); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "the legacy design evaluates"); for name in ["First", "Second"] { run(&mut s, "component.create", json!({"name": name})); assert_eq!(s.model.last_recomputed, 0, "creating {name} recomputed a feature"); diff --git a/crates/engine/src/thread_tests.rs b/crates/engine/src/thread_tests.rs index b9c2a6b4b..7a9fea126 100644 --- a/crates/engine/src/thread_tests.rs +++ b/crates/engine/src/thread_tests.rs @@ -270,7 +270,8 @@ fn a_thread_without_a_coarse_pitch_suggests_explicit_pitches() { } for designation in ["MNaN", "Minf", "M-28", "M0", "M1e9", "M1e999", "M28x", "M28xNaN"] { let e = s.execute("solid.thread", &json!({"face": [14, 0, 5], "designation": designation})).unwrap_err().to_string(); - assert!(e.contains("unknown thread"), "{designation}: {e}"); + // Each thread form names itself in its refusal: `unknown metric thread`. + assert!(e.contains("unknown metric thread"), "{designation}: {e}"); assert_eq!(s.doc.to_json(), saved); } run(&mut s, "solid.thread", json!({"face": [14, 0, 5], "designation": "M28x2"})); diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index df07a28ee..ccc7ac690 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -1090,6 +1090,8 @@ mod tests { let mut cam = home_camera(&s).unwrap(); cam.fov = fov; let mut sc = scene(&s, &cam).unwrap(); + // The cap in the cap colour: a part's hatch colour is the one its name picks. + sc.part_hatch = None; assert!(!section_segments(&s.world_state().unwrap().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); diff --git a/crates/geom/src/ball.rs b/crates/geom/src/ball.rs new file mode 100644 index 000000000..46db2293b --- /dev/null +++ b/crates/geom/src/ball.rs @@ -0,0 +1,232 @@ +//! The smallest ball holding a set of points (Welzl's algorithm): a measure of a point set's size +//! that does not move with the points, whatever rigid motion carries them. + +use crate::Vec3; + +/// A ball: every point within `radius` of `center`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ball { + pub center: Vec3, + pub radius: f64, +} + +/// How much more than `radius` a point may lie from the centre and still count as inside: the +/// rounding of the centre's and radius' arithmetic, so a point the ball was made through is never +/// taken for one outside it. +const ROUNDING: f64 = 1e-12; + +impl Ball { + /// The smallest ball holding every finite point of `points` (points that are not finite are + /// skipped), or `None` when there are none. Welzl's algorithm in its incremental form, the + /// points taken in a fixed shuffled order: expected `O(n)`. The ball is unique, so the order + /// only changes the last bits of its centre and radius. + pub fn enclosing(points: &[Vec3]) -> Option { + let mut p: Vec = points.iter().copied().filter(|q| q.is_finite()).collect(); + shuffle(&mut p); + let mut ball = Ball { center: *p.first()?, radius: 0.0 }; + // Each loop keeps the smallest ball holding the points before it with the points of the + // loops outside it on its boundary (Welzl 1991): at most four are, in three dimensions. + for i in 1..p.len() { + if ball.holds(p[i]) { + continue; + } + ball = Ball { center: p[i], radius: 0.0 }; + for j in 0..i { + if ball.holds(p[j]) { + continue; + } + ball = through(&[p[i], p[j]]); + for k in 0..j { + if ball.holds(p[k]) { + continue; + } + ball = through(&[p[i], p[j], p[k]]); + for l in 0..k { + if !ball.holds(p[l]) { + ball = through(&[p[i], p[j], p[k], p[l]]); + } + } + } + } + } + Some(ball) + } + + pub fn diameter(&self) -> f64 { + 2.0 * self.radius + } + + /// Whether `p` lies in the ball, to the rounding of its arithmetic. + pub fn holds(&self, p: Vec3) -> bool { + p.dist(self.center) <= self.radius + ROUNDING * (self.radius + self.center.len()) + } +} + +/// The smallest ball with every one of `r` (two to four points) on its boundary; where they are +/// degenerate (three in a line, four in a plane, which exact arithmetic never asks for but +/// rounding can), the smallest ball through some of them that holds them all. +fn through(r: &[Vec3]) -> Ball { + let exact = match r { + [a, b] => Some((*a + *b) * 0.5), + [o, b, c] => circumcentre3(*o, *b, *c), + [o, b, c, d] => circumcentre4(*o, *b, *c, *d), + _ => None, + }; + match exact { + Some(center) => with_center(center, r), + None => smallest_holding(r), + } +} + +/// The ball about `center` reaching the farthest of `r`. +fn with_center(center: Vec3, r: &[Vec3]) -> Ball { + Ball { center, radius: r.iter().map(|q| q.dist(center)).fold(0.0, f64::max) } +} + +/// The centre of the circle through `o`, `b` and `c`, or `None` when they are (nearly) in a line. +fn circumcentre3(o: Vec3, b: Vec3, c: Vec3) -> Option { + let (a, b) = (b - o, c - o); + let n = a.cross(b); + let n2 = n.len2(); + if !(n2 > 1e-14 * a.len2() * b.len2()) { + return None; + } + Some(o + (b.cross(n) * a.len2() + n.cross(a) * b.len2()) / (2.0 * n2)) +} + +/// The centre of the sphere through `o`, `b`, `c` and `d`, or `None` when they are (nearly) in a +/// plane. +fn circumcentre4(o: Vec3, b: Vec3, c: Vec3, d: Vec3) -> Option { + let (a, b, c) = (b - o, c - o, d - o); + let det = a.dot(b.cross(c)); + if !(det.abs() > 1e-7 * a.len() * b.len() * c.len()) { + return None; + } + Some(o + (b.cross(c) * a.len2() + c.cross(a) * b.len2() + a.cross(b) * c.len2()) / (2.0 * det)) +} + +/// The smallest of the balls through two or three of `r` that holds all of them; a ball about +/// their mean where none does (never, for two to four points). +fn smallest_holding(r: &[Vec3]) -> Ball { + let mut best: Option = None; + let mut consider = |ball: Ball| { + if r.iter().all(|q| ball.holds(*q)) && best.is_none_or(|b| ball.radius < b.radius) { + best = Some(ball); + } + }; + for i in 0..r.len() { + for j in i + 1..r.len() { + consider(with_center((r[i] + r[j]) * 0.5, r)); + for k in j + 1..r.len() { + if let Some(c) = circumcentre3(r[i], r[j], r[k]) { + consider(with_center(c, r)); + } + } + } + } + best.unwrap_or_else(|| { + let mean = r.iter().fold(Vec3::ZERO, |s, q| s + *q) / (r.len().max(1) as f64); + with_center(mean, r) + }) +} + +/// A Fisher–Yates shuffle from a fixed seed (SplitMix64), so the same points give the same ball. +fn shuffle(p: &mut [Vec3]) { + let mut state: u64 = 0x9E37_79B9_7F4A_7C15; + for i in (1..p.len()).rev() { + state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + p.swap(i, (z % (i as u64 + 1)) as usize); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Points from a fixed generator in the cube [-1, 1]³. + fn cloud(n: usize, seed: u64) -> Vec { + let mut s = seed; + let mut next = || { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (s >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 + }; + (0..n).map(|_| Vec3::new(next(), next(), next())).collect() + } + + /// The smallest ball by brute force: of the balls through two, three or four of the points, + /// the smallest that holds them all. + fn brute(p: &[Vec3]) -> f64 { + let mut best = f64::INFINITY; + let n = p.len(); + let mut try_ball = |b: Ball| { + if p.iter().all(|q| q.dist(b.center) <= b.radius * (1.0 + 1e-9)) { + best = best.min(b.radius); + } + }; + for i in 0..n { + for j in i + 1..n { + try_ball(through(&[p[i], p[j]])); + for k in j + 1..n { + try_ball(through(&[p[i], p[j], p[k]])); + for l in k + 1..n { + try_ball(through(&[p[i], p[j], p[k], p[l]])); + } + } + } + } + best + } + + #[test] + fn the_smallest_ball_holds_every_point_and_matches_brute_force() { + for seed in 1..40 { + let p = cloud(3 + seed as usize % 9, seed); + let ball = Ball::enclosing(&p).unwrap(); + assert!(p.iter().all(|q| ball.holds(*q)), "seed {seed}: a point outside"); + let want = brute(&p); + assert!((ball.radius - want).abs() <= 1e-12 * want, "seed {seed}: {} against {want}", ball.radius); + } + } + + #[test] + fn known_balls() { + let cube: Vec = (0..8).map(|i| Vec3::new((i & 1) as f64, (i >> 1 & 1) as f64, (i >> 2 & 1) as f64)).collect(); + let b = Ball::enclosing(&cube).unwrap(); + assert!(b.center.dist(Vec3::new(0.5, 0.5, 0.5)) < 1e-15 && (b.radius - 3f64.sqrt() / 2.0).abs() < 1e-15); + let s = 3f64.sqrt(); + let triangle = [Vec3::new(1.0, 0.0, 0.0), Vec3::new(-0.5, s / 2.0, 0.0), Vec3::new(-0.5, -s / 2.0, 0.0)]; + assert!((Ball::enclosing(&triangle).unwrap().radius - 1.0).abs() < 1e-15); + // An obtuse triangle's ball is its longest side's. + let obtuse = [Vec3::new(-1.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 0.0)]; + assert!((Ball::enclosing(&obtuse).unwrap().radius - 1.0).abs() < 1e-15); + let tetra = [Vec3::new(1.0, 1.0, 1.0), Vec3::new(1.0, -1.0, -1.0), Vec3::new(-1.0, 1.0, -1.0), Vec3::new(-1.0, -1.0, 1.0)]; + assert!((Ball::enclosing(&tetra).unwrap().radius - s).abs() < 1e-15); + // Points in a line and in a plane, repeated points, one point, none. + let line: Vec = (0..10).map(|i| Vec3::new(i as f64, 2.0 * i as f64, 0.0)).collect(); + assert!((Ball::enclosing(&line).unwrap().diameter() - 9.0 * 5f64.sqrt()).abs() < 1e-12); + let square: Vec = (0..4).flat_map(|i| [Vec3::new((i & 1) as f64, (i >> 1) as f64, 0.0); 3]).collect(); + assert!((Ball::enclosing(&square).unwrap().diameter() - 2f64.sqrt()).abs() < 1e-15); + assert_eq!(Ball::enclosing(&[Vec3::X]), Some(Ball { center: Vec3::X, radius: 0.0 })); + assert_eq!(Ball::enclosing(&[]), None); + assert_eq!(Ball::enclosing(&[Vec3::new(f64::NAN, 0.0, 0.0)]), None); + } + + /// The ball's size is the set's own: a rigid motion leaves it, and points crowding one end + /// do not stretch it (twice the farthest point's distance from the centroid would be nearly + /// twice the diameter here). + #[test] + fn the_size_does_not_move_with_the_points_or_their_crowding() { + let p = cloud(200, 7); + let d = Ball::enclosing(&p).unwrap().diameter(); + let (c, s) = (0.7f64.cos(), 0.7f64.sin()); + let moved: Vec = p.iter().map(|q| Vec3::new(c * q.x - s * q.y + 30.0, s * q.x + c * q.y - 12.0, q.z + 5.0)).collect(); + assert!((Ball::enclosing(&moved).unwrap().diameter() - d).abs() <= 1e-12 * d); + let mut crowded = vec![Vec3::ZERO; 99]; + crowded.push(Vec3::new(1.0, 0.0, 0.0)); + assert!((Ball::enclosing(&crowded).unwrap().diameter() - 1.0).abs() < 1e-15); + } +} diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rs index 1a2b1b96e..619f8a4ec 100644 --- a/crates/geom/src/brep/form.rs +++ b/crates/geom/src/brep/form.rs @@ -91,6 +91,61 @@ fn params([a0, a1]: [f64; 2], (q0, n): (f64, usize)) -> [f64; 2] { [param(a0).clamp(q0, end), param(a1).clamp(q0, end)] } +/// Equal arcs from angle `a0` to `a1` (less than a turn), as few as keep each within a quarter: +/// their knot vector (0 at `a0`, one more at each arc's end) and control points (as +/// [`arcs`]). A form on them is not on the quarter grid: for a face whose angle range needs the +/// four quarters of a turn (or five) without being a turn, which on the grid would be a form that +/// closes on itself (or overlaps itself) around a face that does not. +fn arcs_between(a0: f64, a1: f64) -> Option<(Vec, Vec<([f64; 2], f64)>)> { + let span = a1 - a0; + if !(a0.is_finite() && span > 0.0 && span < TAU) { + return None; + } + let n = ((span / FRAC_PI_2) - 1e-9).ceil().max(1.0) as usize; + let phi = span / n as f64; + let w = (0.5 * phi).cos(); + let at = |a: f64| [a.cos(), a.sin()]; + let mut pts = Vec::with_capacity(2 * n + 1); + let mut knots = vec![0.0; 3]; + for k in 0..n { + let start = a0 + phi * k as f64; + if k == 0 { + pts.push((at(start), 1.0)); + } + let mid = at(start + 0.5 * phi); + pts.push(([mid[0] / w, mid[1] / w], w)); + pts.push((at(start + phi), 1.0)); + let end = (k + 1) as f64; + knots.extend(if k + 1 < n { vec![end; 2] } else { vec![end; 3] }); + } + Some((knots, pts)) +} + +/// The arcs of a face's angle range `a` and its domain on them: the quarter grid's +/// ([`face_quarters`]), or with `own` and a range short of a turn, arcs of its own from its start +/// ([`arcs_between`], the domain all of them). +fn face_arcs(a: [f64; 2], reach: f64, own: bool) -> Option<((Vec, Vec<([f64; 2], f64)>), [f64; 2])> { + if own && a[1] - a[0] < TAU * (1.0 - 1e-9) { + // Past each end by `reach` (while that stays short of a turn): the face's boundary, which + // lies off the surface by as much, then stays on the form. + let pad = reach.max(0.0).min(0.25 * (TAU * (1.0 - 1e-9) - (a[1] - a[0]))); + let (a0, a1) = (a[0] - pad, a[1] + pad); + let made = arcs_between(a0, a1)?; + let n = made.0.last().copied()?; + let phi = (a1 - a0) / n; + // The form parameter at angle `t`: its arc, plus the arc's own parameter there (as + // `quarter_u`, for an arc of `phi`). + let at = |t: f64| { + let k = ((t - a0) / phi).floor().clamp(0.0, n - 1.0); + let psi = (t - a0 - k * phi).clamp(0.0, phi); + k + 0.5 * (1.0 + (0.5 * psi - 0.25 * phi).tan() / (0.25 * phi).tan()) + }; + return Some((made, [at(a[0]), at(a[1])])); + } + let (grid, d) = face_quarters(a, reach)?; + Some((arcs(grid.0, grid.1), d)) +} + /// Quarter arcs from quarter `q0`, `n` of them: their knot vector (in form parameter) and their /// control points (as `(cos, sin)` factors on the unit circle's plane) with weights. fn arcs(q0: f64, n: usize) -> (Vec, Vec<([f64; 2], f64)>) { @@ -238,10 +293,29 @@ pub fn tube_turned(s: &Surface, angle: f64) -> Option { /// boundary's points ([`extent`]), which may run past a quarter's end by as much as its edges lie /// off the surface; the form then covers no quarter for that alone (a torus face of half a tube /// would otherwise go round the whole tube). -pub fn surface_within(s: &Surface, [u, v]: [[f64; 2]; 2], tolerance: f64) -> Option<(Surface, [[f64; 2]; 2])> { +pub fn surface_within(s: &Surface, domain: [[f64; 2]; 2], tolerance: f64) -> Option<(Surface, [[f64; 2]; 2])> { + surface_on(s, domain, tolerance, false) +} + +/// The NURBS form of a cylinder, cone, sphere or torus face over `domain` (as [`surface`]) whose +/// angles run on arcs of the face's own from where it starts, not on its frame's quarter grid, +/// wherever its range is short of a turn: the same surface, exactly, but a form that never +/// closes on itself around a face that does not (a torus face round 250° of its tube needs all +/// four quarters of the grid, a form SMLib does not take for a torus); each angle runs past the +/// face's ends by the angle `tolerance` (mm) makes, so a boundary that far off stays on the +/// form. Its circles' forms then no +/// longer share its parameter, so its pcurves are not lines: Repair Part rebuilds a refused face +/// on it and has SMLib make them. +pub fn surface_on_own_arcs(s: &Surface, domain: [[f64; 2]; 2], tolerance: f64) -> Option<(Surface, [[f64; 2]; 2])> { + match s { + Surface::Cylinder { .. } | Surface::Cone { .. } | Surface::Sphere { .. } | Surface::Torus { .. } => surface_on(s, domain, tolerance, true), + _ => None, + } +} + +fn surface_on(s: &Surface, [u, v]: [[f64; 2]; 2], tolerance: f64, own: bool) -> Option<(Surface, [[f64; 2]; 2])> { let (reach_u, reach_v) = reaches(s, v, tolerance); - let (grid, fu) = face_quarters(u, reach_u)?; - let (u_knots, ring) = arcs(grid.0, grid.1); + let ((u_knots, ring), fu) = face_arcs(u, reach_u, own)?; // The ring of arcs times a profile `(control, weight)` mapped to (radial, axial) about the // frame: a rational tensor product, its weights the products. let net = |f: &Frame, profile: &[([f64; 2], f64)], at: &dyn Fn([f64; 2]) -> (f64, f64)| -> Option>> { @@ -279,8 +353,7 @@ pub fn surface_within(s: &Surface, [u, v]: [[f64; 2]; 2], tolerance: f64) -> Opt Some((Surface::RationalSpline { u_knots, v_knots, homogeneous }, [fu, params(v, vgrid)])) } Surface::Torus { frame, major_radius, minor_radius, tube_start } => { - let (vgrid, fv) = face_quarters(v, reach_v)?; - let (v_knots, tube) = arcs(vgrid.0, vgrid.1); + let ((v_knots, tube), fv) = face_arcs(v, reach_v, own)?; // The tube's arcs turned on by its start (a rotation of the control points, exact). let (ts, tc) = tube_start.sin_cos(); let homogeneous = net(frame, &tube, &|[c, s]| (major_radius + minor_radius * (c * tc - s * ts), minor_radius * (s * tc + c * ts)))?; @@ -517,6 +590,11 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio // and a box over both is more than a turn wide. let (mut l_lo, mut l_hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); let mut prev: Option<[f64; 2]> = None; + // The loop's bounds in each direction, each with the number of poles the loop had passed + // through when it got there; and the first and last points off a pole. + let mut bounds: Vec<(usize, usize, f64)> = Vec::new(); + let (mut crossings, mut on_pole) = (0usize, false); + let mut first: Option<[f64; 2]> = None; for (c, [t0, t1], forward) in l { let curve = super::eval::CurveEval::new(c).ok()?; // The point at `t` on the label, a periodic parameter unwrapped next to `near`. @@ -531,28 +609,34 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio } Some(q) }; - let mut samples: Vec<(f64, [f64; 2], [bool; 2])> = Vec::with_capacity(EXTENT_POINTS + 1); + let mut samples: Vec<(f64, [f64; 2], [bool; 2], usize)> = Vec::with_capacity(EXTENT_POINTS + 1); for k in 0..=EXTENT_POINTS { let f = k as f64 / EXTENT_POINTS as f64; let t = if *forward { t0 * (1.0 - f) + t1 * f } else { t1 * (1.0 - f) + t0 * f }; let q = at(t, prev)?; // At a pole the collapsed parameter is anything: it bounds nothing. let pole = eval.pole(q); - for d in 0..2 { - if !pole.get(d).copied().unwrap_or(false) { - l_lo[d] = l_lo[d].min(q[d]); - l_hi[d] = l_hi[d].max(q[d]); + if pole.iter().any(|p| *p) { + on_pole = first.is_some(); + } else { + if on_pole { + crossings += 1; + on_pole = false; } - } - if !pole.iter().any(|p| *p) { + first = first.or(Some(q)); prev = Some(q); } - samples.push((t, q, pole)); + for (d, x) in q.iter().enumerate() { + if !pole.get(d).copied().unwrap_or(false) { + bounds.push((crossings, d, *x)); + } + } + samples.push((t, q, pole, crossings)); } // A sample is a point of the boundary, not its extreme: each sample higher (or lower) // than its neighbours brackets an extreme of the edge, which is found there. for k in 0..samples.len() { - let (_, q, pole) = samples[k]; + let (_, q, pole, passed) = samples[k]; let (a, b) = (samples[k.saturating_sub(1)].0, samples[(k + 1).min(samples.len() - 1)].0); for d in 0..2 { // Next to a pole the parameter it collapses is no function of the point: a @@ -573,12 +657,30 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio } let f = |t: f64| at(t, Some(q)).map_or(f64::NEG_INFINITY, |p| sign * p[d]); let x = sign * golden_max(&f, a.min(b), a.max(b)); - l_lo[d] = l_lo[d].min(x); - l_hi[d] = l_hi[d].max(x); + bounds.push((passed, d, x)); } } } } + // Through a pole the loop goes on from anywhere round the periodic direction it + // collapses, so continuing from the point before it is no measure of where: a loop + // through a pole closes in (u, v), the pole taking up its turn (a hemisphere bounded by its + // rim and its seam, down the seam to the pole and up it on the other side). Past the + // first pole, the loop is moved the whole periods that close it. + let last = prev; + for d in 0..2 { + let shift = match (period.get(d), first, last) { + (Some(Some(per)), Some(f), Some(e)) if crossings > 0 => -((e[d] - f[d]) / per).round() * per, + _ => 0.0, + }; + for &(passed, dd, x) in &bounds { + if dd == d { + let x = if passed > 0 { x + shift } else { x }; + l_lo[d] = l_lo[d].min(x); + l_hi[d] = l_hi[d].max(x); + } + } + } for d in 0..2 { if !(l_lo[d] <= l_hi[d]) { continue; diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs index 1ff217ded..208d0b441 100644 --- a/crates/geom/src/brep/tests.rs +++ b/crates/geom/src/brep/tests.rs @@ -850,6 +850,27 @@ fn a_hole_beside_the_seam_lies_in_its_face_turn() { assert!(v[0].abs() < 1e-9 && (v[1] - h).abs() < 1e-9, "{v:?}"); } +/// A hemisphere bounded by its rim and its seam, its loop starting a quarter turn along the rim +/// (the order a re-imported dimple's loop came in): along the rim to the seam, down the seam to +/// the pole, up it on the other side and round the rest of the rim. Through the pole the loop goes +/// on a turn away; continuing from the point before the pole put the seam's second use on the +/// first and the box a quarter turn off the seam (oracle 14: the re-imported face's form over +/// -270..90 degrees, its pcurves over 0..360, and its area a quarter short). +#[test] +fn a_loop_through_a_pole_closes_its_turn_from_the_seam() { + let r = 15.0f64; + let sphere = Surface::Sphere { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; + let rim = Curve::Circle { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; + let seam = Curve::Circle { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 0., -1.] }, radius: r }; + let outer = + vec![(&rim, [0., FRAC_PI_2], false), (&seam, [0., FRAC_PI_2], true), (&seam, [0., FRAC_PI_2], false), (&rim, [FRAC_PI_2, TAU], false)]; + let [u, v] = form::extent(&sphere, &[outer]).expect("an extent"); + assert!((u[1] - u[0] - TAU).abs() < 1e-9, "one turn: {u:?}"); + let from = u[0].rem_euclid(TAU); + assert!(from.min(TAU - from) < 1e-9, "from the seam: {u:?}"); + assert!((v[0] + FRAC_PI_2).abs() < 1e-9 && v[1].abs() < 1e-9, "{v:?}"); +} + /// A face's box reaches its boundary's extremes, not its samples' nearest ones: an ellipse cut /// from a cylinder of radius 20 by a plane at 45 degrees rises 20 above its centre, at an angle /// between the points the box is sampled at. Short of it, the face's NURBS form stopped below the @@ -909,3 +930,45 @@ fn analytic_partials_are_the_derivatives_of_the_order_below() { } } } + +#[test] +fn a_form_on_arcs_of_its_own_is_the_surface_and_does_not_close_around_an_open_face() { + // A torus face round 280° of its tube: on the quarter grid it needs all four quarters, a form + // that closes on itself; on arcs of its own it starts where the face does and stops past + // where it ends. + let torus = Surface::Torus { frame: a_frame(), major_radius: 5., minor_radius: 1.5, tube_start: 0. }; + let label = [[0.3, 1.2], [-2.9, 2.0]]; + let tube = |s: &Surface| match s { + Surface::RationalSpline { v_knots, .. } => (v_knots.first().copied().unwrap(), v_knots.last().copied().unwrap()), + _ => panic!("not a NURBS: {s:?}"), + }; + let (grid, _) = form::surface(&torus, label).unwrap(); + assert_eq!(tube(&grid), (-2.0, 2.0), "the grid's form is the whole tube"); + let tol = 1e-3; + let (own, domain) = form::surface_on_own_arcs(&torus, label, tol).unwrap(); + let (v0, v1) = tube(&own); + assert_eq!((v0, v1), (0.0, 4.0)); + let (label_at, own_at) = (eval::SurfaceEval::new(&torus).unwrap(), eval::SurfaceEval::new(&own).unwrap()); + let u = domain[0][0]; + assert!(own_at.point([u, v0]).unwrap().dist(own_at.point([u, v1]).unwrap()) > 0.1, "the form does not close"); + // Every point of the form is on the torus: (√(x² + y²) − R)² + z² = r² in its frame. + for i in 0..=8 { + for j in 0..=12 { + let uv = [domain[0][0] + (domain[0][1] - domain[0][0]) * i as f64 / 8., v0 + (v1 - v0) * j as f64 / 12.]; + let p = own_at.point(uv).unwrap() - crate::Vec3::new(1., 2., 3.); + let off = ((p.x.hypot(p.y) - 5.).powi(2) + p.z.powi(2)).sqrt() - 1.5; + assert!(off.abs() < 1e-12, "{uv:?}: {off}"); + } + } + // Its domain is the face's: the corners land where the label's do, the form past them by the + // angle the tolerance makes. + for (a, b) in [(0, 0), (0, 1), (1, 0), (1, 1)] { + let (p, q) = (label_at.point([label[0][a], label[1][b]]).unwrap(), own_at.point([domain[0][a], domain[1][b]]).unwrap()); + assert!(p.dist(q) < 1e-9, "corner {a}{b}: {p:?} vs {q:?}"); + } + assert!(domain[1][0] > v0 && domain[1][1] < v1, "{domain:?}"); + // A whole turn stays on the grid (periodic), and a plane has no form. + let (whole, _) = form::surface_on_own_arcs(&torus, [[0.3, 1.2], [-FRAC_PI_2, -FRAC_PI_2 + TAU]], tol).unwrap(); + assert_eq!(tube(&whole), (-1.0, 3.0)); + assert!(form::surface_on_own_arcs(&Surface::Plane { origin: [0.; 3], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }, label, tol).is_none()); +} diff --git a/crates/geom/src/fill.rs b/crates/geom/src/fill.rs index 5590ec400..71934863b 100644 --- a/crates/geom/src/fill.rs +++ b/crates/geom/src/fill.rs @@ -16,7 +16,7 @@ use crate::bspline::{Dir, HPoint, NurbsSurface, Side, SplineError, SplineResult, /// Most loop points a fill takes. pub const MAX_LOOP_POINTS: usize = 8192; /// Most spans of the height field in each direction. -pub const MAX_FILL_SPANS: usize = 32; +pub const MAX_FILL_SPANS: usize = 64; /// How full a patch's middle may be made (`crown`): 0 the least-bending fill, positive fuller, /// negative flatter, in fractions of the loop's size. Outside this range the value is refused. pub const MIN_CROWN: f64 = -0.9; @@ -89,7 +89,7 @@ pub struct LoopFill { /// is free to turn at the rim (it is not the surface that made the rim). It does not depend /// on the grid's directions. `λ = 10⁻⁷ ·` (fitted points) `/` (control points): just enough /// to fix the inside, small enough not to pull the surface off the loop. -/// - Grids of 4, 8, 16, 32 spans across the box's longer side are tried, with as many across +/// - Grids of 4, 8, 16, 32, 64 spans across the box's longer side are tried, with as many across /// the shorter side as keep the cells about square; a grid whose cells are under twice the /// fitted points' largest step in a direction (cells between points would be left to the /// energy alone) waits for denser sampling. The first grid within `tol` of every sampled diff --git a/crates/geom/src/fill_general.rs b/crates/geom/src/fill_general.rs index e6f5da582..a6ccab976 100644 --- a/crates/geom/src/fill_general.rs +++ b/crates/geom/src/fill_general.rs @@ -91,6 +91,10 @@ pub struct Across { pub normal: Vec3, /// G2: the neighbour's curvature vector along `leave` (unit speed). pub bend: Option, + /// G2 and up: the neighbour as a height over its tangent plane to the order asked + /// ([`crate::linkage::Jet`], on the frame `normal × leave`, `leave`), which the conditions of + /// [`crate::fill_iso`] read. `None` where only `bend` is known. + pub jet: Option, } /// One sample of the loop. @@ -226,7 +230,9 @@ pub fn fill_general( fn finite_station(s: &Station) -> bool { s.p.is_finite() && s.up.is_finite() - && s.across.is_none_or(|a| a.leave.is_finite() && a.normal.is_finite() && a.bend.is_none_or(|b| b.is_finite())) + && s.across.is_none_or(|a| { + a.leave.is_finite() && a.normal.is_finite() && a.bend.is_none_or(|b| b.is_finite()) && a.jet.is_none_or(|j| j.is_finite()) + }) } /// How close a grid came: what [`fill_general`] reports when none is close enough. @@ -1085,7 +1091,7 @@ fn crown(surface: NurbsSurface, net: &Net, st: &[Station], dev: &Developed, crow if crown == 0.0 { return Ok(surface); } - // The side the neighbours' normals face, by the patch's normals at the G1/G2 stations. + // The side the neighbours' normals face, by the patch's normals at the stations of G1 and up. let mut side = 0.0; for (s, q) in st.iter().zip(&dev.d) { if let (Some(a), Some((n, _, _))) = (s.across, net.frame(*q)) { @@ -1093,7 +1099,7 @@ fn crown(surface: NurbsSurface, net: &Net, st: &[Station], dev: &Developed, crow } } if side == 0.0 { - return Err(SplineError::Unsupported("crowning a patch with no g1 or g2 edge to say which side is out".into())); + return Err(SplineError::Unsupported("crowning a patch with no g1 or higher edge to say which side is out".into())); } let sign = side.signum(); let along = |g: [f64; 2]| net.frame(g).map(|(n, _, _)| n * sign); diff --git a/crates/geom/src/fill_general_tests.rs b/crates/geom/src/fill_general_tests.rs index 35ff6b6cd..41f2b4d43 100644 --- a/crates/geom/src/fill_general_tests.rs +++ b/crates/geom/src/fill_general_tests.rs @@ -30,7 +30,7 @@ fn tube_end(r: f64, g2: bool) -> impl FnMut(usize, &[f64]) -> Result impl FnMut(usize, &[f64]) -> Result, pub points: Vec, + /// One positive weight per point; `None` for a polynomial edge. + pub weights: Option>, } impl IsoEdge { @@ -101,6 +157,21 @@ impl IsoEdge { let [a, b] = self.domain(); 0.5 * (a + b) } + + /// The unit tangent at parameter `t` (the loop's way), `None` where the edge stops. + pub fn tangent(&self, t: f64) -> Option { + let space = Space::new(self.degree, self.knots.clone()).ok()?; + let h = self.homogeneous(); + let (a, da) = (space.eval(&h, t, 0).ok()?, space.eval(&h, t, 1).ok()?); + let p = a.project()?; + ((da.xyz() - p * da.w) * (1.0 / a.w)).normalized() + } + + /// The homogeneous control points. + fn homogeneous(&self) -> Vec { + let w = |i: usize| self.weights.as_ref().and_then(|w| w.get(i)).copied().unwrap_or(1.0); + self.points.iter().enumerate().map(|(i, p)| HPoint::weighted(*p, w(i))).collect() + } } /// What the fill is asked for besides its boundary. @@ -138,8 +209,8 @@ pub struct IsoPatch { #[derive(Clone, Debug, PartialEq)] pub struct IsoFill { pub patches: Vec, - /// Each spoke as a curve (degree, knots on `[0, 1]`, control points): from its edge's - /// midpoint to the centre. Empty for a fill of one patch. + /// Each spoke as a curve (degree, knots on `[0, 1]`, control points and, on a rational fill, + /// weights): from its edge's midpoint to the centre. Empty for a fill of one patch. pub spokes: Vec, pub achieved: Achieved, } @@ -151,28 +222,35 @@ pub struct Achieved { /// a spoke, between the two patches') at a station held to the tolerance, and at any station. pub normal_deviation: f64, pub normal_deviation_all: f64, - /// The largest difference (1/length) between the fill's normal curvature across a G2 edge - /// and the neighbour's. - pub curvature_mismatch: f64, + /// The largest angle (radians) by which the fill's normal at a station held to the tolerance + /// misses the neighbour's beyond the edge's own lean out of the neighbour's tangent plane + /// there (the fill holds the edge, so it can come no nearer): what the angle tolerance is + /// held to. + pub normal_excess: f64, + /// `jumps[k]`, k = 2 … 4: the largest jump, clear of the loop's corners, of the k-th + /// derivative of the linkage curves' height above the neighbour per unit length of their + /// foot (`(n·c⁽ᵏ⁾ − target) / |x₁|ᵏ`, 1/lengthᵏ⁻¹) across the edges asked for order k or more: + /// the normal curvature (k = 2), its rate of change (3) and that rate's (4). Zero below 2. + pub jumps: [f64; MAX_CONTINUITY + 1], /// The farthest point from the fill. pub point_deviation: f64, } -/// A curve on `[0, 1]`. +/// A curve on `[0, 1]`, on homogeneous control points. #[derive(Clone, Debug)] struct Curve { space: Space, - points: Vec, + points: Vec, } -/// The piece `[a, b]` of `edge`, on `[0, 1]` (run backwards when `reverse`). -fn on_unit(edge: &IsoEdge, [a, b]: [f64; 2], reverse: bool) -> SplineResult { +/// The piece `[a, b]` of `edge` (homogeneous points scaled by `scale`), on `[0, 1]` (run +/// backwards when `reverse`). +fn on_unit(edge: &IsoEdge, scale: f64, [a, b]: [f64; 2], reverse: bool) -> SplineResult { let p = edge.degree; - let h: Vec = edge.points.iter().map(|q| HPoint::weighted(*q, 1.0)).collect(); - let (knots, h) = segment(p, &edge.knots, &h, a, b)?; + let h: Vec = edge.homogeneous().into_iter().map(|q| q * scale).collect(); + let (knots, mut points) = segment(p, &edge.knots, &h, a, b)?; let map = |k: f64| if reverse { (b - k) / (b - a) } else { (k - a) / (b - a) }; let mut knots: Vec = knots.iter().map(|k| map(*k)).collect(); - let mut points: Vec = h.iter().map(|q| q.xyz()).collect(); if reverse { knots.reverse(); points.reverse(); @@ -188,8 +266,9 @@ fn on_unit(edge: &IsoEdge, [a, b]: [f64; 2], reverse: bool) -> SplineResult SplineResult { +/// The straight line from `a` to `b` on `[0, 1]`, homogeneous (a spoke's start, or a pole when +/// the points are one). +fn line(a: HPoint, b: HPoint) -> SplineResult { Ok(Curve { space: Space::polynomial(1, 0.0, 1.0)?, points: vec![a, b] }) } @@ -200,74 +279,205 @@ fn breaks(s: &Space) -> Vec { out } -/// One space holding every curve: every break of any (and `extra`), each repeated as often as the -/// highest degree; and each curve's control points there (each Bézier piece raised to that -/// degree). Exact. -fn compatible(curves: &[&Curve], extra: &[f64]) -> SplineResult<(Space, Vec>)> { - let q = curves.iter().map(|s| s.space.degree()).max().unwrap_or(1); - let mut all: Vec = curves.iter().flat_map(|s| breaks(&s.space)).chain(extra.iter().copied()).filter(|x| (0.0..=1.0).contains(x)).collect(); - all.sort_by(f64::total_cmp); - all.dedup(); - let mut knots = vec![0.0; q + 1]; - for &x in all.iter().filter(|x| **x > 0.0 && **x < 1.0) { - knots.extend(std::iter::repeat_n(x, q)); - } - knots.extend(std::iter::repeat_n(1.0, q + 1)); - let target = Space::new(q, knots)?; - let mut out = Vec::with_capacity(curves.len()); +/// Breaks of different sides closer than this (on `[0, 1]`) are one break: the rounding of +/// mapping each side's parameter onto the unit interval. +const BREAK_TOL: f64 = 1e-12; + +/// The knots of `s` with each one within [`BREAK_TOL`] of one of `breaks` moved onto it. +fn snapped(s: &Space, breaks: &[f64]) -> SplineResult { + let knots = s.knots().iter().map(|k| breaks.iter().copied().find(|b| (b - k).abs() <= BREAK_TOL).unwrap_or(*k)).collect(); + Space::new(s.degree(), knots) +} + +/// One space holding every curve, of degree `q` (at least each curve's), and each curve's +/// control points there. Each break of a curve keeps that curve's continuity there: a knot of +/// multiplicity `m` in a curve of degree `p` is one of multiplicity `m + q − p` in the space (as +/// raising the degree needs, NURBS Book §5.5), the most any curve asks (breaks of different +/// curves within [`BREAK_TOL`] made one); the breaks `extra` adds are simple knots. Exact: the +/// space contains every curve, which is carried into it by [`carried`]. +fn compatible(curves: &[&Curve], extra: &[f64], q: usize) -> SplineResult<(Space, Vec>)> { + let q = curves.iter().map(|s| s.space.degree()).max().unwrap_or(1).max(q); + let mut need: Vec<(f64, usize)> = Vec::new(); for c in curves { let p = c.space.degree(); - let h: Vec = c.points.iter().map(|x| HPoint::weighted(*x, 1.0)).collect(); - let mut points: Vec = Vec::new(); - for w in all.windows(2) { - let (a, b) = (w[0], w[1]); - let (_, piece) = segment(p, c.space.knots(), &h, a, b)?; - let piece: Vec = piece.iter().map(|x| x.xyz()).collect(); - let raised = embed(&Space::polynomial(p, a, b)?, &piece, &Space::polynomial(q, a, b)?)?; - points.extend(raised.into_iter().skip(usize::from(!points.is_empty()))); + for (x, m) in interior_knots(&c.space) { + let k = (m + q - p).min(q); + match need.iter_mut().find(|(y, _)| (*y - x).abs() <= BREAK_TOL) { + Some((_, have)) => *have = (*have).max(k), + None => need.push((x, k)), + } } - if points.len() != target.count() { - return invalid("the sides' pieces do not fill the common space"); - } - out.push(points); + } + need.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut knots = vec![0.0; q + 1]; + for &(x, k) in &need { + knots.extend(std::iter::repeat_n(x, k)); + } + knots.extend(std::iter::repeat_n(1.0, q + 1)); + let target = Space::new(q, knots)?.refined(extra)?; + let canonical: Vec = need.iter().map(|(x, _)| *x).collect(); + let mut out = Vec::with_capacity(curves.len()); + for c in curves { + out.push(carried(&snapped(&c.space, &canonical)?, &c.points, &target)?); } Ok((target, out)) } +/// The distinct interior knots of a space and how often each is repeated. +fn interior_knots(s: &Space) -> Vec<(f64, usize)> { + let [a, b] = s.domain(); + let mut out: Vec<(f64, usize)> = Vec::new(); + for &k in s.knots().iter().filter(|k| **k > a && **k < b) { + match out.last_mut() { + Some((x, m)) if *x == k => *m += 1, + _ => out.push((k, 1)), + } + } + out +} + +/// The control points in `to` of the curve with control points `ctrl` in `from`, which `to` +/// contains: the curve interpolated at `to`'s Greville abscissae (where the interpolation +/// problem is uniquely solvable, Schoenberg–Whitney), which is the curve itself since it lies in +/// the space; its end points are the curve's own. +fn carried(from: &Space, ctrl: &[HPoint], to: &Space) -> SplineResult> { + let conds: Vec = greville(to).into_iter().map(|t| Cond { t, der: 0 }).collect(); + let data = conds.iter().map(|c| from.eval(ctrl, c.t, 0)).collect::>>()?; + let mut points = Interpolant::new(to.clone(), conds)?.fit(&data)?; + if let (Some(f), Some(first)) = (points.first_mut(), ctrl.first()) { + *f = *first; + } + if let (Some(l), Some(last)) = (points.last_mut(), ctrl.last()) { + *l = *last; + } + Ok(points) +} + /// The Greville abscissae of a space (where its splines reproduce a linear function). fn greville(s: &Space) -> Vec { let (p, k) = (s.degree(), s.knots()); (0..s.count()).map(|i| (1..=p).map(|r| k.get(i + r).copied().unwrap_or(0.0)).sum::() / p as f64).collect() } -/// A tensor patch in the fill's space both ways, control point `(i, j)` (i along u) at -/// `i + c·j`, `c` the space's count. +/// A tensor patch in the fill's spaces along u and v, control point `(i, j)` (i along u) at +/// `i + c·j`, `c` the u space's count, with its fixed weights. #[derive(Clone, Debug)] struct Patch { - space: Space, + spaces: [Space; 2], net: Vec, + weights: Vec, + /// Whether any weight differs from one (else the polynomial basis is used as it is). + rational: bool, /// The patch collapses along `u = 0` (a three-sided patch). pole: bool, } impl Patch { - fn count(&self) -> usize { - self.space.count() + /// The control points along u and along v. + fn counts(&self) -> [usize; 2] { + [self.spaces[0].count(), self.spaces[1].count()] + } + + fn flat(&self, i: usize, j: usize) -> usize { + i + self.spaces[0].count() * j } fn at(&self, i: usize, j: usize) -> Vec3 { - self.net.get(i + self.count() * j).copied().unwrap_or(Vec3::ZERO) + self.net.get(self.flat(i, j)).copied().unwrap_or(Vec3::ZERO) + } + + fn weight(&self, i: usize, j: usize) -> f64 { + self.weights.get(self.flat(i, j)).copied().unwrap_or(1.0) } /// The coefficients of `∂^(du+dv) S / ∂u^du ∂v^dv` at (u, v) on each control point it - /// depends on: `(i, j, coefficient)`. + /// depends on: `(i, j, coefficient)`. On a rational patch these are the derivatives of the + /// rational basis `R_ij = w_ij N_i N_j / W`, by the Leibniz rule for `w_ij N_i N_j = R_ij W`: + /// `R^(a,b) = (f^(a,b) − Σ_{(k,l) ≠ (0,0)} C(a,k) C(b,l) W^(k,l) R^(a−k,b−l)) / W`. fn row(&self, u: f64, v: f64, du: usize, dv: usize) -> SplineResult> { - let (iu, bu) = self.space.basis(u, du)?; - let (iv, bv) = self.space.basis(v, dv)?; - let mut out = Vec::with_capacity(bu.len() * bv.len()); - for (b, nv) in bv.iter().enumerate() { - for (a, nu) in bu.iter().enumerate() { - out.push((iu + a, iv + b, nu * nv)); + self.row_sided(u, v, du, dv, [false; 2]) + } + + /// The basis of the space along `d` at `t`, from the left of a knot when `left`. + fn basis(&self, d: usize, t: f64, r: usize, left: bool) -> SplineResult<(usize, Vec)> { + let space = self.spaces.get(d).ok_or_else(|| SplineError::Invalid("a patch has two directions".into()))?; + if left { space.basis_left(t, r) } else { space.basis(t, r) } + } + + /// [`Patch::row`] with each direction's basis taken from the left of a knot where `left` + /// says so: the derivative of the piece ending there. + fn row_sided(&self, u: f64, v: f64, du: usize, dv: usize, left: [bool; 2]) -> SplineResult> { + if !self.rational { + let (iu, bu) = self.basis(0, u, du, left[0])?; + let (iv, bv) = self.basis(1, v, dv, left[1])?; + let mut out = Vec::with_capacity(bu.len() * bv.len()); + for (b, nv) in bv.iter().enumerate() { + for (a, nu) in bu.iter().enumerate() { + out.push((iu + a, iv + b, nu * nv)); + } + } + return Ok(out); + } + // The basis and its derivatives up to the orders asked, each way. + let ders = |d: usize, t: f64, top: usize| -> SplineResult<(usize, Vec>)> { + let mut first = 0; + let mut out = Vec::with_capacity(top + 1); + for r in 0..=top { + let (f, b) = self.basis(d, t, r, left.get(d).copied().unwrap_or(false))?; + first = f; + out.push(b); + } + Ok((first, out)) + }; + let (iu, bu) = ders(0, u, du)?; + let (iv, bv) = ders(1, v, dv)?; + let width = (bu.first().map_or(0, Vec::len), bv.first().map_or(0, Vec::len)); + let basis = |d: &[Vec], r: usize, a: usize| d.get(r).and_then(|x| x.get(a)).copied().unwrap_or(0.0); + // W^(k,l) at the point. + let mut wd = vec![vec![0.0; dv + 1]; du + 1]; + for b in 0..width.1 { + for a in 0..width.0 { + let w = self.weight(iu + a, iv + b); + for (k, row) in wd.iter_mut().enumerate() { + for (l, x) in row.iter_mut().enumerate() { + *x += w * basis(&bu, k, a) * basis(&bv, l, b); + } + } + } + } + let w0 = wd.first().and_then(|r| r.first()).copied().unwrap_or(0.0); + if !(w0 > 0.0) { + return invalid("a patch's weights vanish"); + } + let binom = |n: usize, k: usize| (0..k).fold(1.0, |c, i| c * (n - i) as f64 / (i + 1) as f64); + let mut out = Vec::with_capacity(width.0 * width.1); + let mut r = vec![vec![0.0; dv + 1]; du + 1]; + for b in 0..width.1 { + for a in 0..width.0 { + let w = self.weight(iu + a, iv + b); + for total in 0..=du + dv { + for k in 0..=du.min(total) { + let l = total - k; + if l > dv { + continue; + } + let mut x = w * basis(&bu, k, a) * basis(&bv, l, b); + for i in 0..=k { + for j in 0..=l { + if i == 0 && j == 0 { + continue; + } + let wij = wd.get(i).and_then(|x| x.get(j)).copied().unwrap_or(0.0); + let rr = r.get(k - i).and_then(|x| x.get(l - j)).copied().unwrap_or(0.0); + x -= binom(k, i) * binom(l, j) * wij * rr; + } + } + if let Some(slot) = r.get_mut(k).and_then(|x| x.get_mut(l)) { + *slot = x / w0; + } + } + } + out.push((iu + a, iv + b, r.get(du).and_then(|x| x.get(dv)).copied().unwrap_or(0.0))); } } Ok(out) @@ -283,10 +493,11 @@ impl Patch { } fn surface(&self) -> SplineResult { - let c = self.count(); - let ctrl: Vec = (0..c).flat_map(|j| (0..c).map(move |i| (i, j))).map(|(i, j)| HPoint::weighted(self.at(i, j), 1.0)).collect(); - let knots = self.space.knots().to_vec(); - NurbsSurface::from_homogeneous([self.space.degree(); 2], [knots.clone(), knots], ctrl) + let [cu, cv] = self.counts(); + let ctrl: Vec = + (0..cv).flat_map(|j| (0..cu).map(move |i| (i, j))).map(|(i, j)| HPoint::weighted(self.at(i, j), self.weight(i, j))).collect(); + let [su, sv] = &self.spaces; + NurbsSurface::from_homogeneous([su.degree(), sv.degree()], [su.knots().to_vec(), sv.knots().to_vec()], ctrl) } } @@ -327,59 +538,131 @@ struct Quilt { spokes: Vec<(usize, usize)>, } +/// The constants each edge's homogeneous points are scaled by so that the weights at every +/// corner of the loop agree (module docs); refused when no such constants exist. +fn corner_scales(edges: &[IsoEdge]) -> SplineResult> { + let ends = |e: &IsoEdge| { + let w = e.weights.as_ref(); + (w.and_then(|w| w.first()).copied().unwrap_or(1.0), w.and_then(|w| w.last()).copied().unwrap_or(1.0)) + }; + let mut scales = Vec::with_capacity(edges.len()); + let mut c = 1.0 / edges.first().map_or(1.0, |e| ends(e).0); + for (k, e) in edges.iter().enumerate() { + if k > 0 { + let (_, before) = edges.get(k - 1).map(ends).unwrap_or((1.0, 1.0)); + c *= before / ends(e).0; + } + scales.push(c); + } + let closing = edges.last().map_or(1.0, |e| ends(e).1) * scales.last().copied().unwrap_or(1.0); + if !(closing.is_finite() && (closing - 1.0).abs() <= WEIGHT_TOL) { + return Err(SplineError::Unsupported( + "a patch on rational edges whose weights at the loop's corners cannot be made to agree (their end-to-start ratios round the loop multiply to more or less than one)".into(), + )); + } + Ok(scales) +} + impl Quilt { - /// The fill's patches over the loop's sides in the space refined by `extra` breaks. - fn new(edges: &[IsoEdge], extra: &[f64]) -> SplineResult { + /// The fill's patches over the loop's sides at degree `degree` (at least) in spaces refined + /// by `extra` breaks (along u and v). One patch has a space each way, each holding the two + /// sides that run that way; about a centre, the space along each spoke is the two patches' + /// either side of it (one's along v, the other's along u), holding the spoke and the two edge + /// halves it meets those patches beside. + fn new(edges: &[IsoEdge], extra: &[Vec; 2], degree: usize) -> SplineResult { let n = edges.len(); - let corner = |k: usize| edges.get(k).and_then(|e| e.points.first()).copied().unwrap_or(Vec3::ZERO); + let scales = corner_scales(edges)?; + let scale = |k: usize| scales.get(k).copied().unwrap_or(1.0); + let corner = |k: usize| edges.get(k).and_then(|e| e.homogeneous().first().copied()).map_or(HPoint::ZERO, |h| h * scale(k)); if n <= 4 { // One patch: the edges are its sides (side 2 and 3 run back along their rows). - let mut sides: Vec = edges.iter().enumerate().map(|(k, e)| on_unit(e, e.domain(), k >= 2)).collect::>()?; + let mut sides: Vec = + edges.iter().enumerate().map(|(k, e)| on_unit(e, scale(k), e.domain(), k >= 2)).collect::>()?; if n == 3 { sides.push(line(corner(0), corner(0))?); } - let refs: Vec<&Curve> = sides.iter().collect(); - let (space, rows) = compatible(&refs, extra)?; - let (Some(c0), Some(c1), Some(c2), Some(c3)) = (rows.first(), rows.get(1), rows.get(2), rows.get(3)) else { return invalid("sides") }; - let patch = coons(&space, c0, c2, c3, c1, n == 3)?; - let c = space.count(); - let mut slots = vec![None; c * c]; - let mut unknowns = 0; - for j in 1..c - 1 { - for i in 1..c - 1 { - if let Some(s) = slots.get_mut(i + c * j) { - *s = Some(unknowns); - unknowns += 1; + let (Some(s0), Some(s1), Some(s2), Some(s3)) = (sides.first(), sides.get(1), sides.get(2), sides.get(3)) else { return invalid("sides") }; + let (su, along_u) = compatible(&[s0, s2], &extra[0], degree)?; + let (sv, along_v) = compatible(&[s3, s1], &extra[1], degree)?; + let (Some(c0), Some(c2), Some(c3), Some(c1)) = (along_u.first(), along_u.get(1), along_v.first(), along_v.get(1)) else { + return invalid("sides"); + }; + let patch = coons([su, sv], c0, c2, c3, c1, n == 3)?; + // The free points numbered with the shorter direction fastest, which keeps the + // normal equations' band narrow. + let [cu, cv] = patch.counts(); + let mut slots = vec![None; cu * cv]; + let (inner_u, inner_v) = (cu.saturating_sub(2), cv.saturating_sub(2)); + for j in 1..cv - 1 { + for i in 1..cu - 1 { + let id = if inner_u <= inner_v { (i - 1) + inner_u * (j - 1) } else { (j - 1) + inner_v * (i - 1) }; + if let Some(s) = slots.get_mut(i + cu * j) { + *s = Some(id); } } } + let unknowns = inner_u * inner_v; let pieces = edges.iter().enumerate().map(|(k, e)| (k, e.domain(), 0, k)).collect(); return Ok(Quilt { patches: vec![patch], slots: vec![slots], unknowns, pieces, spokes: Vec::new() }); } // N patches about the centre: halves of each edge, and straight spokes to start. - let middle: Vec = edges.iter().map(|e| eval_edge(e, e.middle())).collect::>()?; - let centre = middle.iter().fold(Vec3::ZERO, |s, p| s + *p) * (1.0 / n as f64); + let middle: Vec = edges.iter().enumerate().map(|(k, e)| Ok(eval_edge_h(e, e.middle())? * scale(k))).collect::>()?; + let centre = middle.iter().filter_map(|h| h.project()).fold(Vec3::ZERO, |s, p| s + p) * (1.0 / n as f64); let mut curves: Vec = Vec::with_capacity(3 * n); - for e in edges { + for (k, e) in edges.iter().enumerate() { let [a, b] = e.domain(); - curves.push(on_unit(e, [a, e.middle()], false)?); + curves.push(on_unit(e, scale(k), [a, e.middle()], false)?); // The second half runs up u = 0 of the next patch: from V (v = 0) back to M. - curves.push(on_unit(e, [e.middle(), b], true)?); + curves.push(on_unit(e, scale(k), [e.middle(), b], true)?); } for m in &middle { - curves.push(line(*m, centre)?); + curves.push(line(*m, HPoint::weighted(centre, 1.0))?); } - let refs: Vec<&Curve> = curves.iter().collect(); - let (space, rows) = compatible(&refs, extra)?; - let c = space.count(); - let row = |r: usize| rows.get(r).cloned().ok_or_else(|| SplineError::Invalid("rows".into())); + // Space k runs along spoke k: it is patch k's along v (its sides edge k − 1's second half + // and spoke k) and patch k + 1's along u (edge k + 1's first half and spoke k), so it + // holds those three curves' breaks only, not every edge's. + let mut spaces: Vec = Vec::with_capacity(n); + // Each curve carried into the space it runs in: [first half, second half] per edge, and + // each spoke. + let mut first_half: Vec>> = vec![None; n]; + let mut second_half: Vec>> = vec![None; n]; + let mut spoke_rows: Vec> = Vec::with_capacity(n); + for k in 0..n { + let (prev, next) = ((k + n - 1) % n, (k + 1) % n); + let refs = [ + curves.get(2 * prev + 1).ok_or_else(|| SplineError::Invalid("curves".into()))?, + curves.get(2 * next).ok_or_else(|| SplineError::Invalid("curves".into()))?, + curves.get(2 * n + k).ok_or_else(|| SplineError::Invalid("curves".into()))?, + ]; + let (space, mut rows) = compatible(&refs, &extra[0], degree)?; + let spoke = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?; + let first = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?; + let second = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?; + second_half[prev] = Some(second); + first_half[next] = Some(first); + spoke_rows.push(spoke); + spaces.push(space); + } + let got = |v: &[Option>], k: usize| v.get(k).cloned().flatten().ok_or_else(|| SplineError::Invalid("rows".into())); + let space = |k: usize| spaces.get(k).cloned().ok_or_else(|| SplineError::Invalid("spaces".into())); + let spoke_row = |k: usize| spoke_rows.get(k).cloned().ok_or_else(|| SplineError::Invalid("rows".into())); let mut patches = Vec::with_capacity(n); for k in 0..n { let prev = (k + n - 1) % n; - // v = 0: edge k's first half; u = 0: edge k − 1's second half, from V_k up to M_{k−1}; - // u = 1: spoke k; v = 1: spoke k − 1, from M_{k−1} to C. - patches.push(coons(&space, &row(2 * k)?, &row(2 * n + prev)?, &row(2 * prev + 1)?, &row(2 * n + k)?, false)?); + // Along u, space k − 1: v = 0 edge k's first half, v = 1 spoke k − 1 (from M_{k−1} to + // C); along v, space k: u = 0 edge k − 1's second half (from V_k up to M_{k−1}), + // u = 1 spoke k. + patches.push(coons( + [space(prev)?, space(k)?], + &got(&first_half, k)?, + &spoke_row(prev)?, + &got(&second_half, prev)?, + &spoke_row(k)?, + false, + )?); } + // The spokes are shared rows: their weights the same in both patches (the Coons blends + // agree on them), and so are their points once solved. // Unknowns: each spoke's points past its midpoint, the centre once, each patch's // interior. let mut unknowns = 0usize; @@ -388,20 +671,21 @@ impl Quilt { unknowns - 1 }; let centre_id = next(); - let spoke_ids: Vec> = (0..n).map(|_| (1..c - 1).map(|_| next()).collect()).collect(); + let spoke_ids: Vec> = spaces.iter().map(|sp| (1..sp.count().saturating_sub(1)).map(|_| next()).collect()).collect(); let mut slots = Vec::with_capacity(n); for k in 0..n { let prev = (k + n - 1) % n; - let mut s = vec![None; c * c]; - for j in 1..c { - for i in 1..c { - let id = match (i == c - 1, j == c - 1) { + let [cu, cv] = patches.get(k).map(Patch::counts).ok_or_else(|| SplineError::Invalid("patch".into()))?; + let mut s = vec![None; cu * cv]; + for j in 1..cv { + for i in 1..cu { + let id = match (i == cu - 1, j == cv - 1) { (true, true) => centre_id, (true, false) => *spoke_ids.get(k).and_then(|x| x.get(j - 1)).ok_or_else(|| SplineError::Invalid("spoke".into()))?, (false, true) => *spoke_ids.get(prev).and_then(|x| x.get(i - 1)).ok_or_else(|| SplineError::Invalid("spoke".into()))?, (false, false) => next(), }; - if let Some(slot) = s.get_mut(i + c * j) { + if let Some(slot) = s.get_mut(i + cu * j) { *slot = Some(id); } } @@ -418,6 +702,12 @@ impl Quilt { Ok(Quilt { patches, slots, unknowns, pieces, spokes }) } + /// Most free control points one solve takes, one patch or several about a centre. + fn most_unknowns(shared: bool) -> usize { + let _ = shared; + MAX_BANDED_POINTS + } + /// Write the unknowns' values into every patch that holds them. fn set(&mut self, values: &[Vec3]) { for (patch, slots) in self.patches.iter_mut().zip(&self.slots) { @@ -430,68 +720,248 @@ impl Quilt { } } -/// A point of an edge. -fn eval_edge(e: &IsoEdge, t: f64) -> SplineResult { - Space::new(e.degree, e.knots.clone())?.eval(&e.points, t, 0) +/// A homogeneous point of an edge. +fn eval_edge_h(e: &IsoEdge, t: f64) -> SplineResult { + Space::new(e.degree, e.knots.clone())?.eval(&e.homogeneous(), t, 0) } -/// The bilinearly blended Coons patch: `c0`, `c1` along u at v = 0 and 1, `d0`, `d1` along v at -/// u = 0 and 1, all running with their parameter. -fn coons(space: &Space, c0: &[Vec3], c1: &[Vec3], d0: &[Vec3], d1: &[Vec3], pole: bool) -> SplineResult { - let g = greville(space); - let c = space.count(); +/// The bilinearly blended Coons patch of homogeneous sides: `c0`, `c1` along u at v = 0 and 1, +/// `d0`, `d1` along v at u = 0 and 1, all running with their parameter. Points and weights are +/// blended alike, so the boundary rows are the sides' own and the weights inside are the blend +/// of theirs (refused where one is not positive). +fn coons(spaces: [Space; 2], c0: &[HPoint], c1: &[HPoint], d0: &[HPoint], d1: &[HPoint], pole: bool) -> SplineResult { + let (gu, gv) = (greville(&spaces[0]), greville(&spaces[1])); + let (cu, cv) = (gu.len(), gv.len()); let (Some(p00), Some(p10), Some(p01), Some(p11)) = (c0.first().copied(), c0.last().copied(), c1.first().copied(), c1.last().copied()) else { return invalid("a side has no points"); }; - let get = |a: &[Vec3], k: usize| a.get(k).copied().unwrap_or(Vec3::ZERO); - let mut net = Vec::with_capacity(c * c); - for (j, &y) in g.iter().enumerate() { - for (i, &x) in g.iter().enumerate() { + let get = |a: &[HPoint], k: usize| a.get(k).copied().unwrap_or(HPoint::ZERO); + let mut net = Vec::with_capacity(cu * cv); + let mut weights = Vec::with_capacity(cu * cv); + for (j, &y) in gv.iter().enumerate() { + for (i, &x) in gu.iter().enumerate() { let ruled_v = get(c0, i) * (1.0 - y) + get(c1, i) * y; let ruled_u = get(d0, j) * (1.0 - x) + get(d1, j) * x; let bilinear = (p00 * (1.0 - x) + p10 * x) * (1.0 - y) + (p01 * (1.0 - x) + p11 * x) * y; // The boundary rows exactly the sides' own points. - net.push(match (i, j) { + let h = match (i, j) { (_, 0) => get(c0, i), - (_, j) if j + 1 == c => get(c1, i), + (_, j) if j + 1 == cv => get(c1, i), (0, _) => get(d0, j), - (i, _) if i + 1 == c => get(d1, j), + (i, _) if i + 1 == cu => get(d1, j), _ => ruled_v + ruled_u - bilinear, - }); + }; + let p = h + .project() + .filter(|_| h.w > 0.0) + .ok_or_else(|| SplineError::Unsupported("a rational patch whose blended weights are not positive".into()))?; + net.push(p); + weights.push(h.w); } } - Ok(Patch { space: space.clone(), net, pole }) + let rational = weights.iter().any(|w| *w != 1.0); + Ok(Patch { spaces, net, weights, rational, pole }) } -/// One condition row: coefficients on patches' control points `(patch, i, j, coefficient)`, -/// dotted with `dir` when given, else on one coordinate `coord`; its value and weight. +/// One condition row: `Σ along·P = value` over its terms' control points, and its weight. +#[derive(Clone)] struct Row { - terms: Vec<(usize, usize, usize, f64)>, - dir: Option, - coord: usize, + terms: Vec, value: f64, weight: f64, } +/// A control point `(i, j)` of patch `patch` in a row, its coefficient a vector (dotted with +/// the point). +#[derive(Clone, Copy)] +struct Term { + patch: usize, + i: usize, + j: usize, + along: Vec3, +} + +/// The terms of a patch's derivative coefficients `(i, j, c)` taken along `dir`. +fn along(patch: usize, coefficients: &[(usize, usize, f64)], dir: Vec3) -> Vec { + coefficients.iter().map(|&(i, j, c)| Term { patch, i, j, along: dir * c }).collect() +} + +/// The three rows `Σ terms·P = value` on each coordinate. +fn on_each_axis(rows: &mut Vec, patch_terms: &[(usize, Vec<(usize, usize, f64)>)], value: Vec3, weight: f64) { + for (axis, v) in [(Vec3::X, value.x), (Vec3::Y, value.y), (Vec3::Z, value.z)] { + let terms = patch_terms.iter().flat_map(|(p, c)| along(*p, c, axis)).collect(); + rows.push(Row { terms, value: v, weight }); + } +} + /// A station of a loop edge: its patch, side and fraction there, its condition, whether it is -/// held to the angle tolerance, and the side's speed there. +/// held to the angle tolerance, whether it is clear of the loop's corners (its curvature and +/// curvature change are reported), and how fast the fill should leave there. struct Station { patch: usize, side: usize, t: f64, across: Across, + /// The continuity order asked here: the neighbour's, or less near a corner whose neighbours + /// do not agree to it ([`Asked`]): orders up to `full` at their full weight, those above it + /// up to `order` at `fade` of it. + order: usize, + full: usize, + fade: f64, + /// How far (radians) the edge itself leans out of the neighbour's tangent plane here: the + /// fill holds the edge, so its normal can come no nearer the neighbour's than that. + tilt: f64, held: bool, + clear: bool, speed: f64, } +impl Station { + /// The continuity order its conditions ask: 1 (G1) … 4 (G4). + fn order(&self) -> usize { + self.order + } +} + +/// What a station asks, by how near it is to corners whose neighbours agree to less (see +/// [`corner_orders`]): within [`CLASH_SHARE`] of such a corner the orders above the corner's +/// agreement (at least G1) are not asked, and over the next [`CLASH_SHARE`] they come back +/// smoothly (`fade` from 0 to 1, a smoothstep), so the fill is not strained where they start; +/// where the corner's tangent planes disagree the station is not held to the angle tolerance. +struct Asked { + asked: usize, + full: usize, + fade: f64, + held: bool, +} + +impl Asked { + /// For a station asking `asked`, at fraction `distance` of its side from each of the side's + /// two corners, whose neighbours agree to `agreement` (`None`: no cap). + fn near(asked: usize, ends: [(Option, f64); 2]) -> Asked { + let mut a = Asked { asked, full: asked, fade: 1.0, held: true }; + for (agreement, distance) in ends { + let Some(agreed) = agreement.filter(|g| *g < asked) else { continue }; + if distance >= 2.0 * CLASH_SHARE { + continue; + } + a.full = a.full.min(agreed.max(1)); + let x = ((distance - CLASH_SHARE) / CLASH_SHARE).clamp(0.0, 1.0); + a.fade = a.fade.min(x * x * (3.0 - 2.0 * x)); + if agreed == 0 && distance < CLASH_SHARE { + a.held = false; + } + } + a + } + + /// The highest order asked at all. + fn order(&self) -> usize { + if self.fade > 0.0 { self.asked } else { self.full } + } +} + +/// The derivatives `[c′, c″, …, c⁽ⁿ⁾]` (n = `order`) of the linkage curve `c` leaving a station +/// across its edge into the patch: the iso-parameter curve, σ growing into the patch. +fn linkage(patch: &Patch, s: &Station, order: usize) -> SplineResult> { + let (uv, (du, dv, sign)) = station_on(s.side, s.t); + (1..=order).map(|k| Ok(patch.eval(uv[0], uv[1], k * du, k * dv)? * sign.powi(k as i32))).collect() +} + +/// What orders 2 … n ask of `n·c⁽ᵏ⁾` at a station ([`crate::linkage::Jet::targets`]), read +/// from the linkage curve's last derivatives `c` (element k − 2 is order k's); empty for G1. +fn targets(s: &Station, c: &[Vec3]) -> Vec { + let Some(jet) = s.across.jet else { return Vec::new() }; + let (t, w) = (s.across.normal.cross(s.across.leave), s.across.leave); + let x: Vec<[f64; 2]> = c.iter().map(|d| [d.dot(t), d.dot(w)]).collect(); + let mut out = jet.targets(&x).unwrap_or_default(); + out.truncate(s.order().saturating_sub(1)); + out +} + +/// To what order the neighbours agree at each corner of the loop (`[k]`: where edge `k` +/// starts), from their conditions at its two edges' ends ([`corner_agreement`]); no cap +/// (`usize::MAX`) where either edge asks only G0. +fn corner_orders( + edges: &[IsoEdge], + across: &mut dyn FnMut(usize, &[f64]) -> Result>, String>, + size: f64, + angle_tol: f64, +) -> SplineResult> { + let n = edges.len(); + let mut out = vec![usize::MAX; n]; + for (k, slot) in out.iter_mut().enumerate() { + let prev = (k + n - 1) % n; + let (Some(ea), Some(eb)) = (edges.get(prev), edges.get(k)) else { continue }; + let (end, start) = (ea.domain()[1], eb.domain()[0]); + let before = across(prev, &[end]).map_err(SplineError::Invalid)?.into_iter().next().flatten(); + let after = across(k, &[start]).map_err(SplineError::Invalid)?.into_iter().next().flatten(); + if let (Some(x), Some(y), Some(d0), Some(d1)) = (before, after, ea.tangent(end), eb.tangent(start)) { + *slot = corner_agreement(&x, &y, [d0, d1], size, angle_tol); + } + } + Ok(out) +} + +/// To what order the neighbours `before` and `after` the loop's corner agree there (where no +/// surface can meet both with more): 0 when no surface can be within `angle_tol` of both +/// tangent planes there, or (with both neighbours' jets) their twists between the two edges +/// differ (at a corner the fill's normal is the loop's own, `d₀ × d₁` of the +/// edges' tangents `directions`, so each neighbour's must be within the tolerance of it; at a +/// corner where the loop runs straight on, the two must be within twice the tolerance of each +/// other); else the highest order k up to both jets' such that their forms `H_2 … H_k` agree +/// along the two tangents once carried over half the loop's `size` ([`turn`]), as the fill's +/// own jumps are held. A corner whose neighbours agree to the order asked caps nothing. +pub fn corner_agreement(before: &Across, after: &Across, directions: [Vec3; 2], size: f64, angle_tol: f64) -> usize { + let cos = before.normal.dot(after.normal); + let tangent = match directions[0].cross(directions[1]).normalized() { + Some(corner) if directions[0].dot(directions[1]) < (2.0 * angle_tol).cos() => { + [before.normal, after.normal].iter().all(|n| n.dot(corner).abs() >= angle_tol.cos()) + } + _ => cos.abs() >= (2.0 * angle_tol).cos(), + }; + if !tangent { + return 0; + } + let (Some(a), Some(b)) = (before.jet, after.jet) else { return 1 }; + // Heights along each one's own normal; along the other's they change sign with the order. + let sign = cos.signum(); + let form = |x: &Across, jet: &crate::linkage::Jet, m: usize, d: Vec3| { + let (t, w) = (x.normal.cross(x.leave), x.leave); + jet.form(m, [d.dot(t), d.dot(w)]) + }; + // G1 along both edges fixes the fill's twist `n·S_uv` at the corner twice, from each + // neighbour's second form between the two edges' directions, `H₂(d₀, d₁)` + // (`(H₂(d₀ + d₁) − H₂(d₀ − d₁)) / 4`): where those differ, not even G1 holds there. + let [d0, d1] = directions; + let twist = |x: &Across, jet: &crate::linkage::Jet| Some(0.25 * (form(x, jet, 2, d0 + d1)? - form(x, jet, 2, d0 - d1)?)); + match (twist(before, &a), twist(after, &b)) { + (Some(x), Some(y)) if turn((x - sign * y).abs(), 2, size) <= angle_tol => {} + _ => return 0, + } + let mut agreed = 1; + for m in 2..=a.order.min(b.order) { + let same = directions.iter().all(|d| match (form(before, &a, m, *d), form(after, &b, m, *d)) { + (Some(x), Some(y)) => turn((x - sign * y).abs(), m, size) <= angle_tol, + _ => false, + }); + if !same { + return agreed; + } + agreed = m; + } + agreed +} + /// Fill the loop `edges` (three to [`MAX_ISO_EDGES`], each ending where the next starts) with /// patches on them (module docs). `across(k, ts)` gives the neighbour's conditions at the -/// parameters `ts` of edge `k` (its own parameter; `None`: G0 there); `clash[k]`: the -/// neighbours' tangent planes disagree at the corner where edge `k` starts. +/// parameters `ts` of edge `k` (its own parameter; `None`: G0 there). Where the neighbours at a +/// corner agree to a lower order than asked ([`corner_orders`]), the stations within +/// [`CLASH_SHARE`] of it ask no more than that (at least G1), and where their tangent planes +/// disagree they are not held to the angle tolerance either: no surface can meet both better. pub fn iso_fill( edges: &[IsoEdge], across: &mut dyn FnMut(usize, &[f64]) -> Result>, String>, - clash: &[bool], spec: &IsoSpec, ) -> SplineResult { let n = edges.len(); @@ -517,6 +987,11 @@ pub fn iso_fill( if !(a < b) || e.points.iter().any(|q| !q.is_finite()) { return invalid(format!("edge {k} has an empty domain or a control point that is not finite")); } + if let Some(w) = &e.weights + && (w.len() != e.points.len() || w.iter().any(|x| !(x.is_finite() && *x > 0.0))) + { + return invalid(format!("edge {k}'s weights must be positive, one per control point")); + } } let mut all = edges.iter().flat_map(|e| e.points.iter().copied()); let first = all.next().ok_or_else(|| SplineError::Invalid("an edge has no control points".into()))?; @@ -529,33 +1004,110 @@ pub fn iso_fill( return invalid(format!("edge {k} does not end where edge {} starts", (k + 1) % n)); } } - let mut extra: Vec = Vec::new(); - let mut spans = 1usize; + // The highest continuity asked anywhere, from the conditions at each edge's middle (an + // edge's continuity is one along it). + let mut order = 0usize; + for k in 0..n { + let Some(e) = edges.get(k) else { continue }; + let found = across(k, &[e.middle()]).map_err(SplineError::Invalid)?; + for c in found.into_iter().flatten() { + order = order.max(c.jet.map_or(1, |j| j.order)); + } + } + if order > MAX_CONTINUITY { + return invalid(format!("a patch's continuity is at most G{MAX_CONTINUITY}")); + } + let degree = if order == 0 { 1 } else { (order + 1).min(MAX_SPLINE_DEGREE) }; + let corners = corner_orders(edges, &mut *across, size, spec.angle_tol)?; + let mut extra: [Vec; 2] = [Vec::new(), Vec::new()]; + let mut spans = [1usize; 2]; loop { - let quilt = Quilt::new(edges, &extra)?; - let stations = stations(edges, &quilt, &mut *across, clash)?; - let (quilt, report) = solve(quilt, &stations, spec)?; - let fits = report.normal_deviation <= spec.angle_tol && report.point_deviation <= spec.tol && !quilt.patches.iter().any(folds); - let space = quilt.patches.first().map(|p| p.space.clone()).ok_or_else(|| SplineError::Invalid("no patch".into()))?; - let finer = quilt.unknowns * 4 > MAX_UNKNOWN_POINTS; - if fits || spans * 2 > MAX_ISO_SPANS || finer { - if !fits { - return Err(SplineError::Unsupported(format!( - "a patch on these edges within the tolerances: normals within {:.4}° of the neighbours', points within {:.2e}", - report.normal_deviation.to_degrees(), - report.point_deviation - ))); - } + let quilt = Quilt::new(edges, &extra, degree)?; + let stations = stations(edges, &quilt, &mut *across, &corners)?; + let spaces = quilt.patches.first().map(|p| p.spaces.clone()).ok_or_else(|| SplineError::Invalid("no patch".into()))?; + let shared = !quilt.spokes.is_empty(); + // Rows enough for the conditions from opposite sides not to share control points, in + // every patch. + let fewest = |d: usize| quilt.patches.iter().filter_map(|p| p.spaces.get(d).map(Space::count)).min().unwrap_or(0); + let cramped = [fewest(0), fewest(1)].map(|c| c < 2 * (order + 1)); + if cramped.iter().any(|c| *c) && refinable(&spans, cramped, shared, quilt.unknowns) { + halve(&mut extra, &mut spans, &spaces, cramped, shared); + continue; + } + let (quilt, report, along) = solve(quilt, &stations, spec)?; + let folded = quilt.patches.iter().any(folds); + let mut wanted = along.missing(order, size, spec.angle_tol); + if folded || report.point_deviation > spec.tol { + wanted = [true; 2]; + } + // The tangent plane, the points and an unfolded fill are what a patch must have; the + // orders above G1 are held as tightly as the finest space allows, and reported. + let must = !folded && report.point_deviation <= spec.tol && along.angle.iter().all(|a| *a <= spec.angle_tol); + let refine = refinable(&spans, wanted, shared, quilt.unknowns); + if !wanted.iter().any(|w| *w) || (must && !refine) { let quilt = crowned(quilt, &stations, spec.crown, size)?; return finished(quilt, edges, report); } - // Halve every span. - spans *= 2; - let b = breaks(&space); - extra.extend(b.windows(2).map(|w| 0.5 * (w[0] + w[1]))); + if !refine { + let jumps = + report.jumps.get(2..=order).filter(|_| order >= 2).map(|j| format!(", jumps of orders 2 to {order} {j:?}")).unwrap_or_default(); + let folded = if folded { ", and it folds" } else { "" }; + return Err(SplineError::Unsupported(format!( + "a patch on these edges within the tolerances: normals within {:.4}° of the neighbours' beyond the edges' own lean{jumps}, points within {:.2e}{folded}", + report.normal_excess.to_degrees(), + report.point_deviation + ))); + } + halve(&mut extra, &mut spans, &spaces, wanted, shared); } } +/// Whether the spans may be halved in the `wanted` directions (both when the patches share one +/// space, about a centre): within [`MAX_ISO_SPANS`] each way, and the free points, doubling for +/// each direction, within what one solve takes ([`Quilt::most_unknowns`]). +fn refinable(spans: &[usize; 2], wanted: [bool; 2], shared: bool, unknowns: usize) -> bool { + let wanted = if shared { [true; 2] } else { wanted }; + let grows = wanted.iter().filter(|w| **w).count() as u32; + let spans_ok = spans.iter().zip(wanted).all(|(s, w)| !w || s * 2 <= MAX_ISO_SPANS); + spans_ok && unknowns.saturating_mul(2usize.pow(grows)) <= Quilt::most_unknowns(shared) +} + +/// Halve every span of the spaces in the `wanted` directions: the breaks that do it added to +/// `extra`. About a centre, every spoke's space takes the middles of a uniform grid as fine as +/// the refinement has reached. +fn halve(extra: &mut [Vec; 2], spans: &mut [usize; 2], spaces: &[Space; 2], wanted: [bool; 2], shared: bool) { + if shared { + // Each spoke's space has the breaks of its own sides: every one of them gets the same + // further breaks, the middles of the uniform grid at the level reached so far. + let n = spans[0]; + extra[0].extend((0..n).map(|i| (2 * i + 1) as f64 / (2 * n) as f64)); + spans[0] *= 2; + spans[1] *= 2; + return; + } + for (((e, n), s), w) in extra.iter_mut().zip(spans.iter_mut()).zip(spaces).zip(wanted) { + if w { + e.extend(breaks(s).windows(2).map(|w| 0.5 * (w[0] + w[1]))); + *n *= 2; + } + } +} + +/// Whether every jump of order 2 … `order` is within the angle tolerance once carried into the +/// fill: by Taylor's theorem a jump `j` of order k (1/lengthᵏ⁻¹) turns the normal by +/// `j·dᵏ⁻¹/(k − 1)!` at a distance `d` from the edge, and no point of the fill is farther from +/// the loop than half its `size`. So each order is held as tightly as the tangent plane is. +pub fn within_order(jumps: &[f64; MAX_CONTINUITY + 1], order: usize, size: f64, angle_tol: f64) -> bool { + (2..=order).all(|k| jumps.get(k).is_some_and(|j| turn(*j, k, size) <= angle_tol)) +} + +/// How far (radians) a jump `jump` of order `k` turns the normal over half of `size` +/// ([`within_order`]). +pub fn turn(jump: f64, k: usize, size: f64) -> f64 { + let factorial: f64 = (1..k).map(|i| i as f64).product(); + jump * (0.5 * size).powi(k as i32 - 1) / factorial +} + /// The patches, their sides and the spokes. fn finished(quilt: Quilt, edges: &[IsoEdge], achieved: Achieved) -> SplineResult { let n = edges.len(); @@ -584,25 +1136,35 @@ fn finished(quilt: Quilt, edges: &[IsoEdge], achieved: Achieved) -> SplineResult .iter() .filter_map(|&(left, _)| { let p = quilt.patches.get(left)?; - let c = p.count(); - Some(IsoEdge { degree: p.space.degree(), knots: p.space.knots().to_vec(), points: (0..c).map(|j| p.at(c - 1, j)).collect() }) + let [cu, cv] = p.counts(); + let weights = p.rational.then(|| (0..cv).map(|j| p.weight(cu - 1, j)).collect()); + let along = &p.spaces[1]; + Some(IsoEdge { degree: along.degree(), knots: along.knots().to_vec(), points: (0..cv).map(|j| p.at(cu - 1, j)).collect(), weights }) }) .collect(); Ok(IsoFill { patches, spokes, achieved }) } +/// Stations along a side: [`STATIONS_PER_SPAN`] a span and [`STATIONS_PER_POINT`] per control +/// point of a row (each order of continuity holds one row of them, so the stations must outnumber +/// a row's points well for the conditions to hold between them too), at least [`MIN_STATIONS`]. +fn station_count(space: &Space) -> usize { + (breaks(space).len().saturating_sub(1) * STATIONS_PER_SPAN).max(STATIONS_PER_POINT * space.count()).max(MIN_STATIONS) +} + /// The stations of every loop edge with a condition: enough of them for the space's spans. fn stations( edges: &[IsoEdge], quilt: &Quilt, across: &mut dyn FnMut(usize, &[f64]) -> Result>, String>, - clash: &[bool], + corners: &[usize], ) -> SplineResult> { let n = edges.len(); let mut out = Vec::new(); - let Some(space) = quilt.patches.first().map(|p| &p.space) else { return Ok(out) }; - let count = (breaks(space).len().saturating_sub(1) * STATIONS_PER_SPAN).max(MIN_STATIONS); for &(k, [a, b], patch, side) in &quilt.pieces { + // The space the side runs in: u for sides 0 and 2, v for 1 and 3. + let Some(space) = quilt.patches.get(patch).and_then(|p| p.spaces.get(side % 2)) else { continue }; + let count = station_count(space); let [ea, eb] = edges.get(k).map(IsoEdge::domain).unwrap_or([0.0, 1.0]); // Stations inside the piece (its corners are its neighbours' corners); every side runs // the loop's way round its patch, as the edge does. @@ -614,87 +1176,222 @@ fn stations( let Some(c) = c else { continue }; let t = (param - a) / (b - a); let f = (param - ea) / (eb - ea); - let near_start = clash.get(k).copied().unwrap_or(false) && f < CLASH_SHARE; - let near_end = clash.get((k + 1) % n).copied().unwrap_or(false) && f > 1.0 - CLASH_SHARE; - let (uv, (du, dv, _)) = station_on(side, t); - let speed = p.eval(uv[0], uv[1], dv, du).map(|d| d.len()).unwrap_or(0.0); - out.push(Station { patch, side, t, across: c, held: !(near_start || near_end), speed }); + let asked = c.jet.map_or(1, |j| j.order); + let ask = Asked::near(asked, [(corners.get(k).copied(), f), (corners.get((k + 1) % n).copied(), 1.0 - f)]); + let clear = f > CORNER_SHARE && f < 1.0 - CORNER_SHARE && ask.full == asked; + let (uv, (du, dv, sign)) = station_on(side, t); + // How fast the Coons start leaves into the leave direction: it blends the sides + // across, so it leaves as fast as the opposite sides lie apart; the side's own speed + // where it does not leave into the patch at all. + let along = p.eval(uv[0], uv[1], dv, du).map(|d| d.len()).unwrap_or(0.0); + let speed = p.eval(uv[0], uv[1], du, dv).map(|d| (d * sign).dot(c.leave)).ok().filter(|x| *x > 0.0).unwrap_or(along); + let tilt = edges.get(k).and_then(|e| e.tangent(param)).map_or(0.0, |d| d.dot(c.normal).abs().clamp(0.0, 1.0).asin()); + out.push(Station { patch, side, t, across: c, order: ask.order(), full: ask.full, fade: ask.fade, tilt, held: ask.held, clear, speed }); } } Ok(out) } /// The fill's free control points by least squares (module docs), and what they achieve. -fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult<(Quilt, Achieved)> { +fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult<(Quilt, Achieved, Along)> { if quilt.unknowns == 0 { - return Ok((quilt, Achieved::default())); + return Ok((quilt, Achieved::default(), Along::default())); } - if quilt.unknowns > MAX_UNKNOWN_POINTS { - return Err(SplineError::TooLarge(format!("{} free control points (at most {MAX_UNKNOWN_POINTS})", quilt.unknowns))); + let most = Quilt::most_unknowns(!quilt.spokes.is_empty()); + if quilt.unknowns > most { + return Err(SplineError::TooLarge(format!("{} free control points (at most {most})", quilt.unknowns))); } - let energy: Vec> = quilt.patches.iter().map(energy).collect::>()?; + let fairing = stations.iter().map(Station::order).max().unwrap_or(1).max(1) + 1; + let energy: Vec> = quilt.patches.iter().map(|p| energy(p, fairing)).collect::>()?; let mut located: Vec<(usize, [f64; 2])> = Vec::new(); let mut report = Achieved::default(); - let spoke_count = quilt.patches.first().map_or(0, |p| (breaks(&p.space).len().saturating_sub(1) * STATIONS_PER_SPAN).max(MIN_STATIONS)); - for round in 0..ROUNDS { - let mut rows: Vec = Vec::new(); + let mut along = Along::default(); + let spoke_count = quilt.patches.iter().map(|p| station_count(&p.spaces[0])).max().unwrap_or(0); + let top = stations.iter().map(Station::order).max().unwrap_or(1); + // The mean span of each space of a patch. + let span = |p: &Patch| p.spaces.clone().map(|s| 1.0 / breaks(&s).len().saturating_sub(1).max(1) as f64); + let rounds = if top >= 2 { ROUNDS_PER_ORDER * top } else { ROUNDS }; + let smooth = knot_line_rows(&quilt, spec.angle_tol)?; + for round in 0..rounds { + let mut rows: Vec = smooth.clone(); for s in stations { let Some(patch) = quilt.patches.get(s.patch) else { continue }; - let (uv, (du, dv, sign)) = station_on(s.side, s.t); - let first: Vec<(usize, usize, usize, f64)> = - patch.row(uv[0], uv[1], du, dv)?.into_iter().map(|(i, j, c)| (s.patch, i, j, c * sign)).collect(); - rows.push(Row { terms: first.clone(), dir: Some(s.across.normal), coord: 0, value: 0.0, weight: 1.0 }); - let w = s.across.leave * s.speed; - for (c, value) in [w.x, w.y, w.z].into_iter().enumerate() { - rows.push(Row { terms: first.clone(), dir: None, coord: c, value, weight: HERMITE_WEIGHT }); - } - if let Some(bend) = s.across.bend { - let along = (patch.eval(uv[0], uv[1], du, dv)? * sign).dot(s.across.leave); - let second = patch.row(uv[0], uv[1], 2 * du, 2 * dv)?.into_iter().map(|(i, j, c)| (s.patch, i, j, c)).collect(); - rows.push(Row { terms: second, dir: Some(s.across.normal), coord: 0, value: along * along * bend.dot(s.across.normal), weight: 1.0 }); - } + // The span across the side: of v for sides 0 and 2, of u for 1 and 3. + linkage_rows(&mut rows, patch, s, span(patch).get(1 - s.side % 2).copied().unwrap_or(1.0))?; } // Across each spoke the two patches' derivatives away from it are opposed. for &(left, right) in &quilt.spokes { let (Some(a), Some(b)) = (quilt.patches.get(left), quilt.patches.get(right)) else { continue }; for i in 0..spoke_count { let t = (i as f64 + 0.5) / spoke_count as f64; - let mut terms: Vec<(usize, usize, usize, f64)> = a.row(1.0, t, 1, 0)?.into_iter().map(|(i, j, c)| (left, i, j, c)).collect(); - terms.extend(b.row(t, 1.0, 0, 1)?.into_iter().map(|(i, j, c)| (right, i, j, c))); - for c in 0..3 { - rows.push(Row { terms: terms.clone(), dir: None, coord: c, value: 0.0, weight: 1.0 }); - } + on_each_axis(&mut rows, &[(left, a.row(1.0, t, 1, 0)?), (right, b.row(t, 1.0, 0, 1)?)], Vec3::ZERO, 1.0); } } for (p, (patch, uv)) in spec.points.iter().zip(&located) { let Some(on) = quilt.patches.get(*patch) else { continue }; - let terms: Vec<(usize, usize, usize, f64)> = on.row(uv[0], uv[1], 0, 0)?.into_iter().map(|(i, j, c)| (*patch, i, j, c)).collect(); - for (c, value) in [p.x, p.y, p.z].into_iter().enumerate() { - rows.push(Row { terms: terms.clone(), dir: None, coord: c, value, weight: 1.0 }); - } + on_each_axis(&mut rows, &[(*patch, on.row(uv[0], uv[1], 0, 0)?)], *p, 1.0); } let solved = least_squares(&quilt, &rows, &energy)?; quilt.set(&solved); located = spec.points.iter().map(|p| nearest(&quilt, *p)).collect(); - report = measure(&quilt, stations, spec.points, &located, spoke_count)?; - let relinearise = stations.iter().any(|s| s.across.bend.is_some()) || !spec.points.is_empty(); + (report, along) = measure(&quilt, stations, spec.points, &located, spoke_count)?; + let relinearise = top >= 2 || !spec.points.is_empty(); if !relinearise && round == 0 { break; } } - Ok((quilt, report)) + Ok((quilt, report, along)) } -/// A patch's thin-plate energy coefficients between its control points (flat indices), of the -/// terms `G⁽ʳ⁾ ⊗ G⁽ˢ⁾` with `(r, s)` = (2, 0), (1, 1) twice, (0, 2). -fn energy(patch: &Patch) -> SplineResult> { - let s = &patch.space; +/// Rows that keep a patch tangent continuous across its own C0 knot lines (a break where a +/// side is only C0 in its parameter, such as a circle's quarter joint once in homogeneous form): +/// along the line `u = x` (or `v = x`), at stations, the derivative across it from the right is +/// the one from the left times `r`, the ratio the two sides crossing the line have there (they +/// are tangent continuous, their speeds may differ), blended linearly between them; at the sides +/// the rows hold by construction. A line where a crossing side turns a corner is left alone: no +/// surface is tangent across it there. A three-sided patch's pole takes the other side's ratio. +fn knot_line_rows(quilt: &Quilt, angle_tol: f64) -> SplineResult> { + let mut rows = Vec::new(); + for (k, patch) in quilt.patches.iter().enumerate() { + for d in 0..2 { + let (Some(space), Some(other)) = (patch.spaces.get(d), patch.spaces.get(1 - d)) else { continue }; + let count = station_count(other); + for (x, m) in interior_knots(space) { + if m < space.degree() { + continue; + } + // The point (x, t) in the patch's (u, v), and its one-sided derivatives across. + let at = |t: f64| if d == 0 { [x, t] } else { [t, x] }; + let across = |t: f64, left: bool| -> SplineResult> { + let [u, v] = at(t); + let (du, dv) = if d == 0 { (1, 0) } else { (0, 1) }; + patch.row_sided(u, v, du, dv, if d == 0 { [left, false] } else { [false, left] }) + }; + let speed = |row: &[(usize, usize, f64)]| row.iter().fold(Vec3::ZERO, |s, (i, j, c)| s + patch.at(*i, *j) * *c); + let ratio = |t: f64| -> SplineResult> { + let (a, b) = (speed(&across(t, true)?), speed(&across(t, false)?)); + let (la, lb) = (a.len(), b.len()); + if !(la > 0.0 && lb > 0.0) { + return Ok(None); + } + Ok((a.dot(b) / (la * lb) >= angle_tol.cos()).then_some(lb / la)) + }; + let ends = [ratio(0.0)?, ratio(1.0)?]; + let (r0, r1) = match ends { + [Some(a), Some(b)] => (a, b), + [Some(a), None] | [None, Some(a)] if patch.pole && d == 1 => (a, a), + _ => continue, + }; + for i in 0..count { + let t = (i as f64 + 0.5) / count as f64; + let r = r0 * (1.0 - t) + r1 * t; + let mut terms = across(t, false)?; + terms.extend(across(t, true)?.into_iter().map(|(i, j, c)| (i, j, -r * c))); + on_each_axis(&mut rows, &[(k, terms)], Vec3::ZERO, 1.0); + } + } + } + } + Ok(rows) +} + +/// A station's rows (module docs), linearised about the patch as it stands: +/// - G1: `n·c′ = 0`, and the weak Hermite rows `w·c′ = s`, `t·c′ = 0` in the neighbour's tangent +/// plane only (`t = n × w`), so they never pull against the G1 row; +/// - orders k = 2 … n: `n·c⁽ᵏ⁾ = T_k(x₁ … x_{k−1})` ([`crate::linkage::Jet::linearised`]) by +/// Newton's method: `T_k` is replaced by its tangent at the last solution's `x⁰`, so the row is +/// `n·c⁽ᵏ⁾ − Σ_j ∇_j T_k · x_j = T_k(x⁰) − Σ_j ∇_j T_k · x_j⁰`, with `x_j = (t·c⁽ʲ⁾, w·c⁽ʲ⁾)` +/// and `c⁽ʲ⁾ = signʲ ∂ʲS` across. Each is weighed by `hᵏ⁻¹` against the G1 row (`h` the span), +/// so every order says how far it misses over one span and none swamps the others as the +/// spans shrink. +fn linkage_rows(rows: &mut Vec, patch: &Patch, s: &Station, span: f64) -> SplineResult<()> { + let (uv, (du, dv, sign)) = station_on(s.side, s.t); + let (n, w) = (s.across.normal, s.across.leave); + let t = n.cross(w); + let order = s.order(); + // The coefficients of c′ … c⁽ⁿ⁾ on the control points. + let derivative: Vec> = (1..=order) + .map(|k| { + let sign_k = sign.powi(k as i32); + Ok(patch.row(uv[0], uv[1], k * du, k * dv)?.into_iter().map(|(i, j, c)| (i, j, c * sign_k)).collect()) + }) + .collect::>()?; + let Some(first) = derivative.first() else { return Ok(()) }; + rows.push(Row { terms: along(s.patch, first, n), value: 0.0, weight: 1.0 }); + for (dir, value) in [(w, s.speed), (t, 0.0)] { + rows.push(Row { terms: along(s.patch, first, dir), value, weight: HERMITE_WEIGHT }); + } + let Some(jet) = s.across.jet else { return Ok(()) }; + let c = linkage(patch, s, jet.order)?; + let x0: Vec<[f64; 2]> = c.iter().map(|d| [d.dot(t), d.dot(w)]).collect(); + let Some(targets) = jet.linearised(&x0) else { return Ok(()) }; + for (k, target) in (2..=order).zip(targets) { + let Some(top) = derivative.get(k - 1) else { continue }; + let mut terms = along(s.patch, top, n); + let mut value = target.value; + for (j, (g, x)) in target.gradient.iter().zip(&x0).enumerate().take(k - 1) { + let Some(cj) = derivative.get(j) else { continue }; + terms.extend(along(s.patch, cj, (t * g[0] + w * g[1]) * -1.0)); + value -= g[0] * x[0] + g[1] * x[1]; + } + let fade = if k <= s.full { 1.0 } else { s.fade }; + rows.push(Row { terms, value, weight: fade * span.powi(k as i32 - 1) }); + } + Ok(()) +} + +/// A patch's fairing energy for a fill asked G^n, between its control points (flat indices): the +/// thin plate (order 2) plus, for n ≥ 2, the energy of order `m = n + 1`, each scaled to unit +/// trace ([`energy_of`]). The higher order leaves the change the conditions ask (of curvature, +/// of its rate…) spread over the fill rather than squeezed into the first span along its edges; +/// the thin plate, whose null space (the planes) the loop pins, keeps the system definite where +/// the higher order's (polynomials of degree below m) is not. +fn energy(patch: &Patch, m: usize) -> SplineResult> { + let thin = energy_of(patch, 2)?; + if m <= 2 { + return Ok(thin); + } + let high = energy_of(patch, m)?; + let trace = |e: &[(usize, usize, f64)]| e.iter().filter(|(a, b, _)| a == b).map(|(_, _, x)| *x).sum::(); + let (t2, tm) = (trace(&thin), trace(&high)); + if !(t2 > 0.0 && tm > 0.0) { + return Ok(thin); + } + Ok(thin.into_iter().map(|(a, b, x)| (a, b, x / t2)).chain(high.into_iter().map(|(a, b, x)| (a, b, x / tm))).collect()) +} + +/// A patch's fairing energy of order `m` between its control points (flat indices): +/// `∫∫ Σ_r C(m, r) |∂ᵘʳ ∂ᵥᵐ⁻ʳ S|²`, the terms `G⁽ʳ⁾ ⊗ G⁽ᵐ⁻ʳ⁾` of the spaces' Gram matrices (order 2 +/// is the thin plate `∫∫ |S_uu|² + 2|S_uv|² + |S_vv|²`). +fn energy_of(patch: &Patch, m: usize) -> SplineResult> { + let (gu, gv) = (gram(&patch.spaces[0], m)?, gram(&patch.spaces[1], m)?); + let at = |g: &[Vec>], r: usize, a: usize, b: usize| g.get(r).and_then(|x| x.get(a)).and_then(|x| x.get(b)).copied().unwrap_or(0.0); + let binom = |n: usize, k: usize| (0..k).fold(1.0, |c, i| c * (n - i) as f64 / (i + 1) as f64); + let [cu, cv] = patch.counts(); + let mut out = Vec::new(); + for j in 0..cv { + for l in 0..cv { + for i in 0..cu { + for k in 0..cu { + let e: f64 = (0..=m).map(|r| binom(m, r) * at(&gu, r, i, k) * at(&gv, m - r, j, l)).sum(); + if e != 0.0 { + out.push((i + cu * j, k + cu * l, e)); + } + } + } + } + } + Ok(out) +} + +/// The Gram matrices `∫ N_a⁽ʳ⁾ N_b⁽ʳ⁾` of a space's basis for r = 0 … m (Gauss–Legendre on +/// each span, exact for the degrees used). +fn gram(s: &Space, m: usize) -> SplineResult>>> { let n = s.count(); - let mut g: [Vec>; 3] = std::array::from_fn(|_| vec![vec![0.0; n]; n]); - let b = breaks(s); - for w in b.windows(2) { + let mut g: Vec>> = vec![vec![vec![0.0; n]; n]; m + 1]; + for w in breaks(s).windows(2) { let (lo, hi) = (w[0], w[1]); - for (x, wt) in GAUSS4 { + for (x, wt) in GAUSS6 { let t = 0.5 * (lo + hi) + 0.5 * (hi - lo) * x; let weight = 0.5 * (hi - lo) * wt; for (r, gr) in g.iter_mut().enumerate() { @@ -709,49 +1406,31 @@ fn energy(patch: &Patch) -> SplineResult> { } } } - let at = |r: usize, a: usize, b: usize| g.get(r).and_then(|x| x.get(a)).and_then(|x| x.get(b)).copied().unwrap_or(0.0); - let mut out = Vec::new(); - for j in 0..n { - for l in 0..n { - for i in 0..n { - for k in 0..n { - let e = at(2, i, k) * at(0, j, l) + 2.0 * at(1, i, k) * at(1, j, l) + at(0, i, k) * at(2, j, l); - if e != 0.0 { - out.push((i + n * j, k + n * l, e)); - } - } - } - } - } - Ok(out) + Ok(g) } /// The free points minimising the weighted rows' squares plus a vanishing multiple of the /// patches' energy, the loop's rows held: the normal equations, solved by Cholesky. fn least_squares(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)>]) -> SplineResult> { let dim = 3 * quilt.unknowns; - let mut a = vec![0.0; dim * dim]; - let mut b = vec![0.0; dim]; let slot = |p: usize, flat: usize| quilt.slots.get(p).and_then(|s| s.get(flat)).copied().flatten(); + let mut a = if quilt.spokes.is_empty() { Normal::new(dim, bandwidth(quilt, rows, energy)) } else { Normal::Blocks(BlockNormal::new(quilt)) }; + let mut b = vec![0.0; dim]; let value = |p: usize, flat: usize| quilt.patches.get(p).and_then(|x| x.net.get(flat)).copied().unwrap_or(Vec3::ZERO); let mut condition_trace = 0.0; for r in rows { let mut unknown: Vec<(usize, f64)> = Vec::new(); let mut known = 0.0; - for &(p, i, j, c) in &r.terms { - let flat = i + quilt.patches.get(p).map_or(0, Patch::count) * j; - let coords = match r.dir { - Some(d) => [d.x, d.y, d.z], - None => std::array::from_fn(|k| if k == r.coord { 1.0 } else { 0.0 }), - }; - let v = value(p, flat); - for (k, f) in coords.iter().enumerate() { - if *f == 0.0 { + for t in &r.terms { + let flat = quilt.patches.get(t.patch).map_or(0, |p| p.flat(t.i, t.j)); + let v = value(t.patch, flat); + for (k, (f, x)) in [t.along.x, t.along.y, t.along.z].into_iter().zip([v.x, v.y, v.z]).enumerate() { + if f == 0.0 { continue; } - match slot(p, flat) { - Some(x) => unknown.push((3 * x + k, c * f)), - None => known += c * f * [v.x, v.y, v.z][k], + match slot(t.patch, flat) { + Some(id) => unknown.push((3 * id + k, f)), + None => known += f * x, } } } @@ -759,9 +1438,7 @@ fn least_squares(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)> let w2 = r.weight * r.weight; for &(x, cx) in &unknown { for &(y, cy) in &unknown { - if let Some(cell) = a.get_mut(x * dim + y) { - *cell += w2 * cx * cy; - } + a.add(x, y, w2 * cx * cy); } if let Some(cell) = b.get_mut(x) { *cell += w2 * cx * rhs; @@ -779,9 +1456,7 @@ fn least_squares(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)> match slot(p, g) { Some(y) => { for k in 0..3 { - if let Some(cell) = a.get_mut((3 * x + k) * dim + 3 * y + k) { - *cell += lambda * e; - } + a.add(3 * x + k, 3 * y + k, lambda * e); } } None => { @@ -795,12 +1470,247 @@ fn least_squares(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)> } } } - let x = cholesky(a, b, dim)?; + let x = a.solve(b)?; Ok((0..quilt.unknowns) .map(|i| Vec3::new(x.get(3 * i).copied().unwrap_or(0.0), x.get(3 * i + 1).copied().unwrap_or(0.0), x.get(3 * i + 2).copied().unwrap_or(0.0))) .collect()) } +/// The widest coupling between two unknowns (coordinates) in any row or energy term: the +/// normal equations' half bandwidth. +fn bandwidth(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)>]) -> usize { + let slot = |p: usize, i: usize, j: usize| quilt.patches.get(p).and_then(|x| quilt.slots.get(p)?.get(x.flat(i, j)).copied().flatten()); + let mut bw = 0usize; + for r in rows { + let ids = r.terms.iter().filter_map(|t| slot(t.patch, t.i, t.j)); + let (lo, hi) = ids.fold((usize::MAX, 0usize), |(lo, hi), x| (lo.min(x), hi.max(x))); + if lo <= hi { + bw = bw.max(3 * (hi - lo) + 2); + } + } + for (p, entries) in energy.iter().enumerate() { + let Some(slots) = quilt.slots.get(p) else { continue }; + for &(f, g, _) in entries { + if let (Some(Some(x)), Some(Some(y))) = (slots.get(f), slots.get(g)) { + bw = bw.max(3 * x.abs_diff(*y) + 2); + } + } + } + bw +} + +/// The normal equations' matrix: banded where the band is narrow against the size, else dense. +enum Normal { + Band(crate::fill::Band), + Dense(Vec, usize), + Blocks(BlockNormal), +} + +impl Normal { + fn new(n: usize, bw: usize) -> Normal { + if 4 * bw < n { Normal::Band(crate::fill::Band::new(n, bw)) } else { Normal::Dense(vec![0.0; n * n], n) } + } + + /// Add `v` at `(r, s)` (callers add both halves of a symmetric matrix). + fn add(&mut self, r: usize, s: usize, v: f64) { + match self { + Normal::Band(b) => b.add(r, s, v), + Normal::Dense(a, n) => { + if let Some(x) = a.get_mut(r * *n + s) { + *x += v; + } + } + Normal::Blocks(m) => m.add(r, s, v), + } + } + + fn solve(self, b: Vec) -> SplineResult> { + match self { + Normal::Band(m) => m.factor_rows()?.substitute(b), + Normal::Dense(a, n) => cholesky(a, b, n), + Normal::Blocks(m) => m.solve(b), + } + } +} + +/// The normal equations of patches about a centre, solved by blocks: each patch's interior +/// unknowns (coordinates of control points only that patch holds, coupled to no other patch's) +/// form a banded block, eliminated exactly onto the shared unknowns (the spokes', the centre's, +/// and any a row couples across patches) by their Schur complement, which is solved dense; the +/// interiors then follow by back substitution. Entries are kept sparse until the blocks are +/// known (callers add both halves of the symmetric matrix). +struct BlockNormal { + /// Each coordinate's patch when only one patch holds its point, else `None`. + owner: Vec>, + entries: std::collections::HashMap<(usize, usize), f64>, +} + +impl BlockNormal { + fn new(quilt: &Quilt) -> BlockNormal { + let mut holders: Vec> = vec![Vec::new(); quilt.unknowns]; + for (p, slots) in quilt.slots.iter().enumerate() { + for id in slots.iter().flatten() { + if let Some(h) = holders.get_mut(*id) + && !h.contains(&p) + { + h.push(p); + } + } + } + let owner = holders.iter().flat_map(|h| { + let o = if let [p] = h.as_slice() { Some(*p) } else { None }; + [o; 3] + }); + BlockNormal { owner: owner.collect(), entries: std::collections::HashMap::new() } + } + + fn add(&mut self, r: usize, s: usize, v: f64) { + if v != 0.0 { + *self.entries.entry((r, s)).or_insert(0.0) += v; + } + } + + fn solve(mut self, b: Vec) -> SplineResult> { + let n = b.len(); + // A coordinate coupled to another patch's interior is shared too. + let coupled: Vec = self + .entries + .keys() + .filter(|(r, c)| matches!((self.owner.get(*r).copied().flatten(), self.owner.get(*c).copied().flatten()), (Some(a), Some(b)) if a != b)) + .flat_map(|(r, c)| [*r, *c]) + .collect(); + for x in coupled { + if let Some(o) = self.owner.get_mut(x) { + *o = None; + } + } + let shared: Vec = (0..n).filter(|x| self.owner.get(*x).copied().flatten().is_none()).collect(); + if shared.len() > MAX_SHARED_UNKNOWNS { + return Err(SplineError::TooLarge(format!( + "{} unknowns shared by the patches about the centre (at most {MAX_SHARED_UNKNOWNS})", + shared.len() + ))); + } + let mut place = vec![usize::MAX; n]; + for (i, x) in shared.iter().enumerate() { + if let Some(slot) = place.get_mut(*x) { + *slot = i; + } + } + let patches = self.owner.iter().flatten().copied().max().map_or(0, |m| m + 1); + let mut interior: Vec> = vec![Vec::new(); patches]; + for (x, o) in self.owner.iter().enumerate() { + if let Some(p) = o + && let Some(list) = interior.get_mut(*p) + { + if let Some(slot) = place.get_mut(x) { + *slot = list.len(); + } + list.push(x); + } + } + let m = shared.len(); + // The shared block, and per patch its block, its coupling to the shared unknowns. + let mut s_mat = vec![0.0; m * m]; + let mut blocks: Vec> = vec![std::collections::HashMap::new(); patches]; + let mut couple: Vec> = vec![std::collections::HashMap::new(); patches]; + for ((r, c), v) in std::mem::take(&mut self.entries) { + let (or, oc) = (self.owner.get(r).copied().flatten(), self.owner.get(c).copied().flatten()); + let (pr, pc) = (place.get(r).copied().unwrap_or(0), place.get(c).copied().unwrap_or(0)); + match (or, oc) { + (None, None) => { + if let Some(x) = s_mat.get_mut(pr * m + pc) { + *x += v; + } + } + (Some(p), Some(_)) => { + if let Some(blk) = blocks.get_mut(p) { + *blk.entry((pr, pc)).or_insert(0.0) += v; + } + } + // Interior row, shared column (the transposed entry is its mirror). + (Some(p), None) => { + if let Some(cp) = couple.get_mut(p) { + *cp.entry((pr, pc)).or_insert(0.0) += v; + } + } + (None, Some(_)) => {} + } + } + let mut rhs: Vec = shared.iter().map(|x| b.get(*x).copied().unwrap_or(0.0)).collect(); + let mut solved_parts: Vec<(crate::fill::Band, Vec, Vec<(usize, Vec)>)> = Vec::with_capacity(patches); + for p in 0..patches { + let ids = interior.get(p).map(Vec::as_slice).unwrap_or(&[]); + let k = ids.len(); + let blk = blocks.get(p).cloned().unwrap_or_default(); + let bw = blk.keys().map(|(r, c)| r.abs_diff(*c)).max().unwrap_or(0); + let mut band = crate::fill::Band::new(k.max(1), bw); + for (&(r, c), &v) in &blk { + band.add(r, c, v); + } + if k == 0 { + solved_parts.push((band, Vec::new(), Vec::new())); + continue; + } + let band = band.factor_rows()?; + // g = A_kk⁻¹ b_k; per shared column j coupled to this patch, z_j = A_kk⁻¹ A_k,j. + let bk: Vec = ids.iter().map(|x| b.get(*x).copied().unwrap_or(0.0)).collect(); + let g = band.substitute(bk)?; + let mut columns: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (&(r, j), &v) in couple.get(p).into_iter().flatten() { + if let Some(cell) = columns.entry(j).or_insert_with(|| vec![0.0; k]).get_mut(r) { + *cell += v; + } + } + let mut z: Vec<(usize, Vec)> = Vec::with_capacity(columns.len()); + for (j, col) in columns { + z.push((j, band.substitute(col)?)); + } + // S −= A_Bk·Z, rhs −= A_Bk·g, A_Bk the transpose of the coupling. + let coupling = couple.get(p).cloned().unwrap_or_default(); + let mut by_column: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (&(r, j), &v) in &coupling { + by_column.entry(j).or_default().push((r, v)); + } + for (i, entries) in &by_column { + let dot = |w: &[f64]| entries.iter().map(|(r, v)| v * w.get(*r).copied().unwrap_or(0.0)).sum::(); + if let Some(x) = rhs.get_mut(*i) { + *x -= dot(&g); + } + for (j, zj) in &z { + if let Some(x) = s_mat.get_mut(i * m + j) { + *x -= dot(zj); + } + } + } + solved_parts.push((band, g, z)); + } + let xs = if m > 0 { cholesky(s_mat, rhs, m)? } else { Vec::new() }; + let mut x = vec![0.0; n]; + for (i, id) in shared.iter().enumerate() { + if let Some(slot) = x.get_mut(*id) { + *slot = xs.get(i).copied().unwrap_or(0.0); + } + } + for (p, (_, g, z)) in solved_parts.iter().enumerate() { + let ids = interior.get(p).map(Vec::as_slice).unwrap_or(&[]); + for (r, id) in ids.iter().enumerate() { + let mut v = g.get(r).copied().unwrap_or(0.0); + for (j, zj) in z { + v -= zj.get(r).copied().unwrap_or(0.0) * xs.get(*j).copied().unwrap_or(0.0); + } + if let Some(slot) = x.get_mut(*id) { + *slot = v; + } + } + } + if x.iter().any(|v| !v.is_finite()) { + return invalid("the patches' equations have no finite solution"); + } + Ok(x) + } +} + /// Solve the symmetric positive definite `a·x = b` (dense, `n × n`). fn cholesky(mut a: Vec, mut b: Vec, n: usize) -> SplineResult> { let at = |a: &[f64], r: usize, c: usize| a.get(r * n + c).copied().unwrap_or(0.0); @@ -851,25 +1761,45 @@ fn cholesky(mut a: Vec, mut b: Vec, n: usize) -> SplineResult } /// What the fill achieves at the stations, across the spokes and at the points. -fn measure(quilt: &Quilt, stations: &[Station], points: &[Vec3], located: &[(usize, [f64; 2])], spoke_count: usize) -> SplineResult { +fn measure( + quilt: &Quilt, + stations: &[Station], + points: &[Vec3], + located: &[(usize, [f64; 2])], + spoke_count: usize, +) -> SplineResult<(Achieved, Along)> { let mut r = Achieved::default(); - let mut angle = |a: f64, held: bool| { - r.normal_deviation_all = r.normal_deviation_all.max(a); - if held { - r.normal_deviation = r.normal_deviation.max(a); - } - }; - let mut mismatch = 0.0f64; + let mut along = Along::default(); + let mut jumps = [0.0f64; MAX_CONTINUITY + 1]; for s in stations { let Some(patch) = quilt.patches.get(s.patch) else { continue }; - let (uv, (du, dv, sign)) = station_on(s.side, s.t); + let (uv, _) = station_on(s.side, s.t); let Some(normal) = patch.normal(uv[0], uv[1]) else { continue }; - angle(normal.dot(s.across.normal).abs().clamp(0.0, 1.0).acos(), s.held); - if let Some(bend) = s.across.bend { - let first = patch.eval(uv[0], uv[1], du, dv)? * sign; - let second = patch.eval(uv[0], uv[1], 2 * du, 2 * dv)?; - let mine = second.dot(s.across.normal) / first.len2().max(1e-300); - mismatch = mismatch.max((mine - bend.dot(s.across.normal)).abs()); + let a = normal.dot(s.across.normal).abs().clamp(0.0, 1.0).acos(); + r.normal_deviation_all = r.normal_deviation_all.max(a); + let d = s.side % 2; + if s.held { + r.normal_deviation = r.normal_deviation.max(a); + r.normal_excess = r.normal_excess.max(a - s.tilt); + if let Some(x) = along.angle.get_mut(d) { + *x = x.max(a - s.tilt); + } + } + if s.order() < 2 || !s.clear { + continue; + } + // The linkage curve's height above the neighbour, per unit length along its foot. + let c = linkage(patch, s, s.across.jet.map_or(1, |j| j.order))?; + let n = s.across.normal; + let Some(first) = c.first() else { continue }; + let foot = (*first - n * first.dot(n)).len().max(1e-300); + for (k, want) in (2..).zip(targets(s, &c)) { + let (Some(ck), Some(jump)) = (c.get(k - 1), jumps.get_mut(k)) else { continue }; + let here = ((n.dot(*ck) - want) / foot.powi(k as i32)).abs(); + *jump = jump.max(here); + if let Some(x) = along.jumps.get_mut(d).and_then(|j| j.get_mut(k)) { + *x = x.max(here); + } } } // Across the spokes, clear of the centre. @@ -878,17 +1808,39 @@ fn measure(quilt: &Quilt, stations: &[Station], points: &[Vec3], located: &[(usi for i in 0..spoke_count { let t = (i as f64 + 0.5) / spoke_count as f64; if let (Some(na), Some(nb)) = (a.normal(1.0, t), b.normal(t, 1.0)) { - angle(na.dot(nb).clamp(-1.0, 1.0).acos(), t < 1.0 - CLASH_SHARE); + let a = na.dot(nb).clamp(-1.0, 1.0).acos(); + r.normal_deviation_all = r.normal_deviation_all.max(a); + if t < 1.0 - CLASH_SHARE { + r.normal_deviation = r.normal_deviation.max(a); + r.normal_excess = r.normal_excess.max(a); + along.angle = along.angle.map(|x| x.max(a)); + } } } } - r.curvature_mismatch = mismatch; + r.jumps = jumps; for (p, (patch, uv)) in points.iter().zip(located) { if let Some(on) = quilt.patches.get(*patch) { r.point_deviation = r.point_deviation.max(on.eval(uv[0], uv[1], 0, 0)?.dist(*p)); } } - Ok(r) + Ok((r, along)) +} + +/// What a fit achieves at the stations of the sides running along u (`[0]`) and along v (`[1]`): +/// where it falls short, the spans that way are halved. +#[derive(Clone, Copy, Debug, Default)] +struct Along { + angle: [f64; 2], + jumps: [[f64; MAX_CONTINUITY + 1]; 2], +} + +impl Along { + /// The directions whose sides miss the angle tolerance, or an order's ([`within_order`]). + fn missing(&self, order: usize, size: f64, angle_tol: f64) -> [bool; 2] { + [0, 1] + .map(|d| self.angle.get(d).is_some_and(|a| *a > angle_tol) || self.jumps.get(d).is_some_and(|j| !within_order(j, order, size, angle_tol))) + } } /// The patch and parameters of the fill's point nearest `p`: the nearest of a grid of samples @@ -926,19 +1878,37 @@ fn nearest(quilt: &Quilt, p: Vec3) -> (usize, [f64; 2]) { (k, [u, v]) } -/// Whether a patch folds back on itself: its normal turns against the middle's somewhere on a -/// grid (clear of a three-sided patch's pole at u = 0, where the normal is undefined). +/// Whether a patch folds back on itself: on a grid of its parameters, its normal reverses between +/// neighbouring points (the surface turns back over itself), or vanishes inside it. A patch may +/// turn its normal through more than a right angle overall (a dome meeting a tube's wall, a +/// window round more than half a cylinder): only a reversal between neighbours is a fold. The +/// normal may vanish at a corner (where two sides run on straight, as on a closed loop's pieces) +/// and on a three-sided patch's pole at u = 0. fn folds(patch: &Patch) -> bool { - let Some(mid) = patch.normal(0.5, 0.5) else { return true }; - for i in 0..=FOLD_SAMPLES { - if patch.pole && i == 0 { - continue; + let n = FOLD_SAMPLES; + if patch.normal(0.5, 0.5).is_none() { + return true; + } + let at = |i: usize, j: usize| patch.normal(i as f64 / n as f64, j as f64 / n as f64); + let mut grid: Vec> = Vec::with_capacity((n + 1) * (n + 1)); + for i in 0..=n { + for j in 0..=n { + let normal = at(i, j); + let excused = (patch.pole && i == 0) || ((i == 0 || i == n) && (j == 0 || j == n)); + if normal.is_none() && !excused { + return true; + } + grid.push(normal); } - for j in 0..=FOLD_SAMPLES { - let (u, v) = (i as f64 / FOLD_SAMPLES as f64, j as f64 / FOLD_SAMPLES as f64); - match patch.normal(u, v) { - Some(n) if n.dot(mid) > 0.0 => {} - _ => return true, + } + let get = |i: usize, j: usize| grid.get(i * (n + 1) + j).copied().flatten(); + for i in 0..=n { + for j in 0..=n { + let Some(a) = get(i, j) else { continue }; + for (k, l) in [(i + 1, j), (i, j + 1)] { + if k <= n && l <= n && get(k, l).is_some_and(|b| a.dot(b) <= 0.0) { + return true; + } } } } @@ -946,26 +1916,25 @@ fn folds(patch: &Patch) -> bool { } /// The fill with its middle filled out by `crown` times the loop's `size` along the normals, on -/// control points clear of the rows the conditions hold (one row from a G0 edge, two from G1, -/// three from G2), so the loop and the conditions across it do not move. One patch rises by -/// `16·u(1−u)·v(1−v)`; patches about a centre by `u(2−u)·v(2−v)`, nought on the loop and one at -/// the centre, the same on a spoke from either side. +/// control points clear of the rows the conditions hold (n + 1 rows from a G^n edge), so the loop and the conditions across it do not move. One patch +/// rises by `16·u(1−u)·v(1−v)`; patches about a centre by `u(2−u)·v(2−v)`, nought on the loop and +/// one at the centre, the same on a spoke from either side. fn crowned(mut quilt: Quilt, stations: &[Station], crown: f64, size: f64) -> SplineResult { if crown == 0.0 { return Ok(quilt); } - let held = 1 + stations.iter().map(|s| if s.across.bend.is_some() { 2 } else { 1 }).max().unwrap_or(0); + let held = 1 + stations.iter().map(Station::order).max().unwrap_or(0); let about_centre = !quilt.spokes.is_empty(); let bump = |x: f64, y: f64| if about_centre { x * (2.0 - x) * y * (2.0 - y) } else { 16.0 * x * (1.0 - x) * y * (1.0 - y) }; let mut moved = std::collections::HashMap::new(); for (k, patch) in quilt.patches.iter().enumerate() { - let c = patch.count(); - let g = greville(&patch.space); - let far = if about_centre { c } else { c.saturating_sub(held) }; - for j in held..far { - for i in held..far { - let Some(Some(id)) = quilt.slots.get(k).and_then(|s| s.get(i + c * j)) else { continue }; - let (x, y) = (g.get(i).copied().unwrap_or(0.5), g.get(j).copied().unwrap_or(0.5)); + let [cu, cv] = patch.counts(); + let (gu, gv) = (greville(&patch.spaces[0]), greville(&patch.spaces[1])); + let far = |c: usize| if about_centre { c } else { c.saturating_sub(held) }; + for j in held..far(cv) { + for i in held..far(cu) { + let Some(Some(id)) = quilt.slots.get(k).and_then(|s| s.get(patch.flat(i, j))) else { continue }; + let (x, y) = (gu.get(i).copied().unwrap_or(0.5), gv.get(j).copied().unwrap_or(0.5)); let Some(n) = patch.normal(x, y) else { continue }; moved.entry(*id).or_insert_with(|| patch.at(i, j) + n * (crown * size * bump(x, y))); } @@ -983,3 +1952,7 @@ fn crowned(mut quilt: Quilt, stations: &[Station], crown: f64, size: f64) -> Spl } Ok(quilt) } + +#[cfg(test)] +#[path = "fill_iso_tests.rs"] +mod tests; diff --git a/crates/geom/src/fill_iso_tests.rs b/crates/geom/src/fill_iso_tests.rs new file mode 100644 index 000000000..04ac77f6e --- /dev/null +++ b/crates/geom/src/fill_iso_tests.rs @@ -0,0 +1,219 @@ +use super::*; +use crate::brep::eval::SurfaceEval; +use crate::brep::{Curve, Frame, Surface}; +use crate::linkage::surface_jet; + +const R: f64 = 10.0; +/// The window's half-widths in longitude and latitude. +const ALPHA: f64 = 0.5; +const BETA: f64 = 0.35; + +fn spec() -> IsoSpec<'static> { + IsoSpec { tol: 1e-6, angle_tol: 0.05f64.to_radians(), crown: 0.0, points: &[] } +} + +/// The arc of the circle about `frame`'s z of radius `r` from angle `a0` to `a1`, on its NURBS +/// form (rational quadratic quarter arcs, as SMLib holds circles); run backwards when `reverse`. +fn arc(frame: Frame, r: f64, [a0, a1]: [f64; 2], reverse: bool) -> IsoEdge { + let (form, [t0, t1]) = crate::brep::form::curve(&Curve::Circle { frame, radius: r }, [a0, a1]).unwrap(); + let Curve::RationalSpline { knots, homogeneous } = form else { panic!("a circle's form is rational") }; + let h: Vec = homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(); + let p = knots.len() - h.len() - 1; + let (mut knots, mut h) = segment(p, &knots, &h, t0, t1).unwrap(); + if reverse { + knots = knots.iter().rev().map(|k| t0 + t1 - k).collect(); + h.reverse(); + } + IsoEdge { degree: p, knots, points: h.iter().map(|q| q.project().unwrap()).collect(), weights: Some(h.iter().map(|q| q.w).collect()) } +} + +fn frame(origin: Vec3, x: Vec3, y: Vec3) -> Frame { + Frame { origin: [origin.x, origin.y, origin.z], x_axis: [x.x, x.y, x.z], y_axis: [y.x, y.y, y.z] } +} + +/// A window in a sphere of radius `R` about the origin: longitudes `±ALPHA`, latitudes `±BETA`; +/// the bottom latitude east, the east meridian up, the top latitude west, the west meridian down. +fn window() -> Vec { + let radial = |u: f64| Vec3::new(u.cos(), u.sin(), 0.0); + let latitude = |v: f64| frame(Vec3::Z * (R * v.sin()), Vec3::X, Vec3::Y); + let meridian = |u: f64| frame(Vec3::ZERO, radial(u), Vec3::Z); + vec![ + arc(latitude(-BETA), R * BETA.cos(), [-ALPHA, ALPHA], false), + arc(meridian(ALPHA), R, [-BETA, BETA], false), + arc(latitude(BETA), R * BETA.cos(), [-ALPHA, ALPHA], true), + arc(meridian(-ALPHA), R, [-BETA, BETA], true), + ] +} + +/// The sphere round the window, met with continuity `order` (1 … 4): its outward normal, the way +/// it leaves into the window, and its jet. +fn sphere_beside(edges: &[IsoEdge], order: usize) -> impl FnMut(usize, &[f64]) -> Result>, String> + '_ { + let sphere = SurfaceEval::new(&Surface::Sphere { frame: frame(Vec3::ZERO, Vec3::X, Vec3::Y), radius: R }).unwrap(); + move |k, ts| { + let e = &edges[k]; + ts.iter() + .map(|t| { + let p = eval_edge_h(e, *t).unwrap().project().unwrap(); + let uv = [p.y.atan2(p.x), (p.z / R).clamp(-1.0, 1.0).asin()]; + let (_, su, sv) = sphere.derivs(uv[0], uv[1]).unwrap(); + let normal = su.cross(sv).normalized().unwrap(); + let leave = match k { + 0 => sv.normalized().unwrap(), + 1 => su.normalized().unwrap() * -1.0, + 2 => sv.normalized().unwrap() * -1.0, + _ => su.normalized().unwrap(), + }; + let jet = (order >= 2).then(|| surface_jet(&sphere, uv, normal, leave, order).unwrap()); + Ok(Some(Across { leave, normal, bend: None, jet })) + }) + .collect() + } +} + +/// How far the fill strays from the sphere, over a grid of each patch. +fn off_sphere(fill: &IsoFill) -> f64 { + let mut worst = 0.0f64; + for p in &fill.patches { + for i in 0..=16 { + for j in 0..=16 { + let q = p.surface.eval(i as f64 / 16.0, j as f64 / 16.0).unwrap(); + worst = worst.max((q.len() - R).abs()); + } + } + } + worst +} + +/// The fill's one patch as a surface record, to be evaluated independently of the fill. +fn record(fill: &IsoFill) -> SurfaceEval { + let s = &fill.patches[0].surface; + let [nu, nv] = s.count(); + let homogeneous = (0..nu).map(|i| (0..nv).map(|j| s.point(i, j)).map(|h| [h.x, h.y, h.z, h.w]).collect()).collect(); + let [u_knots, v_knots] = s.knots().clone(); + SurfaceEval::new(&Surface::RationalSpline { u_knots, v_knots, homogeneous }).unwrap() +} + +/// The largest jump of order `k` (2 … 4) across the window's edges, clear of the corners: the +/// fill's linkage curves (its exact partials across each edge) against the sphere's jet of order +/// `k`, per unit length of their foot, as `crate::linkage` defines it. +fn jump(fill: &IsoFill, edges: &[IsoEdge], k: usize) -> f64 { + let surface = record(fill); + let mut beside = sphere_beside(edges, k); + let mut worst = 0.0f64; + for (side, edge) in edges.iter().enumerate() { + let [a, b] = edge.domain(); + for i in 1..40 { + let f = i as f64 / 40.0; + if !(CORNER_SHARE..=1.0 - CORNER_SHARE).contains(&f) { + continue; + } + let across = beside(side, &[a + (b - a) * f]).unwrap()[0].unwrap(); + let (uv, (du, dv, sign)) = station_on(side, f); + let d = surface.partials(uv[0], uv[1]).unwrap(); + let c: Vec = (1..=k).map(|m| d[m * du][m * dv] * sign.powi(m as i32)).collect(); + let (n, t, w) = (across.normal, across.normal.cross(across.leave), across.leave); + let x: Vec<[f64; 2]> = c.iter().map(|d| [d.dot(t), d.dot(w)]).collect(); + let want = across.jet.unwrap().targets(&x).unwrap()[k - 2]; + let foot = (c[0] - n * c[0].dot(n)).len(); + worst = worst.max(((n.dot(c[k - 1]) - want) / foot.powi(k as i32)).abs()); + } + } + worst +} + +/// A window in a sphere, bounded by four circular arcs (rational edges), filled G1 … G4. Each +/// fill of order n holds its jumps of orders 2 … n, by its own report and by an independent +/// reading of its record; the jump of order n + 1 it leaves to its energy is many times larger. +/// (The sphere itself is not in the fill's space, whose weights are a Coons blend and the +/// sphere's a product, so the orders a fill is not asked for do leave jumps.) +#[test] +fn a_sphere_window_on_rational_arcs_holds_each_order_asked_and_not_the_next() { + let edges = window(); + for order in 1..=4 { + let fill = iso_fill(&edges, &mut sphere_beside(&edges, order), &spec()).unwrap(); + let a = fill.achieved; + let measured: Vec = (2..=4).map(|k| jump(&fill, &edges, k)).collect(); + eprintln!( + "G{order}: degree {}, {} control points a side, normals within {:.2e}°, reported jumps {:?}, read off the record (G2, G3, G4) {measured:?}, off the sphere {:.2e}", + fill.patches[0].surface.degree()[0], + fill.patches[0].surface.count()[0], + a.normal_deviation.to_degrees(), + a.jumps, + off_sphere(&fill) + ); + assert!(a.normal_deviation <= spec().angle_tol); + // Each order held within the angle tolerance over the window's size, by the fill's own + // report and by the independent reading of its record (at other stations, so within + // twice that). + let size = { + let mut all = edges.iter().flat_map(|e| e.points.iter().copied()); + let first = all.next().unwrap(); + let (lo, hi) = all.fold((first, first), |(lo, hi), p| (lo.min(p), hi.max(p))); + lo.dist(hi) + }; + for k in 2..=order { + let (reported, read) = (turn(a.jumps[k], k, size), turn(measured[k - 2], k, size)); + assert!(reported <= spec().angle_tol, "G{order}: order {k} reported {reported:e}"); + assert!(read <= 2.0 * spec().angle_tol, "G{order}: order {k} read {read:e}"); + } + if (2..4).contains(&order) { + let (held, next) = (measured[order - 2], measured[order - 1]); + assert!(next > 10.0 * held.max(1e-12), "G{order} leaves order {} to the energy: {next:e} vs {held:e}", order + 1); + } + // Not the sphere (nothing asks for it), but a cap over the window, not a dent. + assert!(off_sphere(&fill) < 0.05 * R, "G{order} near the sphere: {}", off_sphere(&fill)); + } +} + +#[test] +fn hostile_edges_are_refused() { + let edges = window(); + let ok = |e: &[IsoEdge]| iso_fill(e, &mut sphere_beside(e, 2), &spec()); + let mut bad = edges.clone(); + bad[1].weights = Some(vec![-1.0; bad[1].points.len()]); + assert!(ok(&bad).is_err(), "a negative weight"); + let mut bad = edges.clone(); + bad[1].weights = Some(vec![1.0]); + assert!(ok(&bad).is_err(), "a weight count that does not match"); + let mut bad = edges.clone(); + if let Some(w) = bad[0].weights.as_mut() { + w[0] = f64::NAN; + } + assert!(ok(&bad).is_err(), "a weight that is not a number"); + // One edge's start weight doubled alone (its curve changes, and its corner disagrees). + let mut bad = edges.clone(); + if let Some(w) = bad[0].weights.as_mut() { + w[0] *= 2.0; + } + assert!(matches!(ok(&bad), Err(SplineError::Unsupported(_))), "corner weights that cannot agree"); + // A jet above G4. + let mut beside = sphere_beside(&edges, 4); + let mut too_high = |k: usize, ts: &[f64]| -> Result>, String> { + let mut got = beside(k, ts)?; + for a in got.iter_mut().flatten() { + if let Some(j) = a.jet.as_mut() { + j.order = 5; + } + } + Ok(got) + }; + assert!(iso_fill(&edges, &mut too_high, &spec()).is_err()); +} + +/// The rational basis's derivatives (the Leibniz rule on `w N N = R W`) against central +/// differences of the derivative one order lower, on the sphere window's patch. +#[test] +fn a_rational_patch_s_derivatives_are_its_differences() { + let edges = window(); + let q = Quilt::new(&edges, &[Vec::new(), Vec::new()], 3).unwrap(); + let p = &q.patches[0]; + assert!(p.rational); + let (u, v, h) = (0.3, 0.6, 1e-5); + for (du, dv) in [(1, 0), (0, 1), (2, 0), (0, 2), (1, 1), (3, 0), (0, 3)] { + let exact = p.eval(u, v, du, dv).unwrap(); + let (lu, lv) = if du > 0 { (du - 1, dv) } else { (du, dv - 1) }; + let (a, b) = if du > 0 { ((u + h, v), (u - h, v)) } else { ((u, v + h), (u, v - h)) }; + let differences = (p.eval(a.0, a.1, lu, lv).unwrap() - p.eval(b.0, b.1, lu, lv).unwrap()) * (0.5 / h); + assert!(exact.dist(differences) < 1e-5 * exact.len().max(1.0), "∂({du}, {dv}): {exact:?} vs {differences:?}"); + } +} diff --git a/crates/geom/src/fill_matched_tests.rs b/crates/geom/src/fill_matched_tests.rs index 527631802..ab942bc7d 100644 --- a/crates/geom/src/fill_matched_tests.rs +++ b/crates/geom/src/fill_matched_tests.rs @@ -36,7 +36,13 @@ fn setback_hole(r: f64, s: f64, g2: bool) -> impl FnMut(usize, &[f64]) -> Result _ => return Err(format!("no side {k}")), }; let up = Vec3::new(1.0, 1.0, 1.0).normalized().unwrap_or(Vec3::Z); - Ok(Station { p, up, across: Some(Across { leave, normal, bend: g2.then_some(Vec3::ZERO) }), corner: *t == 0.0, clash: false }) + Ok(Station { + p, + up, + across: Some(Across { leave, normal, bend: g2.then_some(Vec3::ZERO), jet: None }), + corner: *t == 0.0, + clash: false, + }) }) .collect() } @@ -110,7 +116,7 @@ fn a_hole_in_a_cylinder_is_filled_with_the_cylinder_to_the_second_order() { // over the radius, bending away from the normal. let across = leave - Vec3::X * leave.x; let bend = normal * (-across.len2() / r); - Ok(Station { p, up: normal, across: Some(Across { leave, normal, bend: Some(bend) }), corner: false, clash: false }) + Ok(Station { p, up: normal, across: Some(Across { leave, normal, bend: Some(bend), jet: None }), corner: false, clash: false }) }) .collect() }; @@ -131,7 +137,7 @@ fn hostile_matched_fills_are_refused() { .map(|t| { let a = t * std::f64::consts::TAU / 3.0; let p = Vec3::new(a.cos(), a.sin(), 0.0); - Station { p, up: Vec3::Z, across: Some(Across { leave: Vec3::Z, normal: p, bend: None }), corner: false, clash: false } + Station { p, up: Vec3::Z, across: Some(Across { leave: Vec3::Z, normal: p, bend: None, jet: None }), corner: false, clash: false } }) .collect()) }; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index c1b3bc7c3..622be959b 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,6 +11,7 @@ mod aabb2; mod arcfit; +mod ball; pub mod blend; pub mod brep; pub mod bspline; @@ -24,6 +25,7 @@ pub mod fill_general; pub mod fill_iso; pub mod fill_matched; mod grid; +pub mod linkage; mod mesh; pub mod mesh_distance; pub mod network; @@ -39,6 +41,7 @@ mod vec; pub use aabb2::Aabb2; pub use arcfit::MAX_FIT_PIECES; +pub use ball::Ball; pub use blend::hermite_bezier; pub use bvh::{Bvh, MeshIndex}; pub use chain::{Chain, Closed, Ends, Open, Path, Planar, Ring}; diff --git a/crates/geom/src/linkage.rs b/crates/geom/src/linkage.rs new file mode 100644 index 000000000..daa753ae6 --- /dev/null +++ b/crates/geom/src/linkage.rs @@ -0,0 +1,334 @@ +//! Geometric continuity of order `n` (G0 … G4) between two surfaces that share a curve, in the +//! linkage-curve formulation, as the fill imposes it and as a seam is measured. +//! +//! **The criterion.** Two surfaces meeting along a curve are G^n there exactly when the +//! *linkage curves* crossing it — a curve on one surface continued by a curve on the other — are +//! G^n curves (Pegna & Wolter, "Geometrical criteria to guarantee curvature continuity of blend +//! surfaces", J. Mech. Des. 114, 1992, for n = 2; Hermann, Lukács & Wolter, "Geometrical +//! criteria on the higher order smoothness of composite surfaces", CAGD 16, 1999, for any n). +//! In a form that needs no reparameterisation: write the neighbour, near a point `p` of the +//! curve, as a height `H` over its tangent plane along its unit normal `n`, +//! `q = p + x + H(x)·n` for `x` in the tangent plane, so that `H(0) = 0` and `∇H(0) = 0`. A +//! curve `c(σ)` from `p` lies on a surface meeting the neighbour with G^n exactly when its height +//! above the neighbour, `n·(c(σ) − p) − H(x(σ))` with `x(σ)` the part of `c(σ) − p` in the +//! tangent plane, vanishes to order `n` in σ. With `H(x) = Σ_{m ≥ 2} H_m(x) / m!` (`H_m` the +//! m-th derivative of `H` at `p`, a form of degree m) and `x(σ) = Σ_j x_j σʲ / j!` +//! (`x_j` the tangent-plane part of `c⁽ʲ⁾`), the condition of order `k` is +//! +//! `n·c⁽ᵏ⁾ = k! · [σᵏ] Σ_{m=2}^{k} H_m(x(σ)) / m!`, +//! +//! whose right-hand side reads `c′ … c⁽ᵏ⁻¹⁾` only: order 1 is `n·c′ = 0` (the tangent plane), +//! order 2 `n·c″ = H₂(x₁)` (the normal curvature in the curve's direction), order 3 +//! `n·c‴ = 3·H₂(x₁, x₂) + H₃(x₁)` (the rate of change of that curvature), and order 4 its rate of +//! change in turn. For a unit `a`, `H₂(a)` is the curvature of the normal section along `a` and +//! `H₃(a)`, `H₄(a)` are its first and second derivatives by arc length. +//! +//! **The jet.** [`surface_jet`] reads `H₂ … H_n` off a surface record's exact partial +//! derivatives: along a tangent vector `a`, the curve on the surface whose foot in the tangent +//! plane runs straight along `a` at unit rate has `n·γ⁽ᵐ⁾(0) = H_m(a)`; its parameter series +//! `(u(τ), v(τ))` is found order by order (the part of each coefficient of `S(u(τ), v(τ))` in the +//! tangent plane is `a`, then zero), and `H_m` as a binary form from its values along +//! `t + λ·w` at `m + 1` values of λ (a polynomial of degree m in λ, so exactly). +//! +//! Input is hostile: orders are capped at [`MAX_CONTINUITY`], and every evaluation is checked. + +use crate::Vec3; +use crate::brep::eval::SurfaceEval; +use crate::tess::partials::{MAX_PARTIAL_ORDER, Partials}; + +/// The highest continuity order handled: G4, the highest order of the surfaces' exact partials. +pub const MAX_CONTINUITY: usize = MAX_PARTIAL_ORDER; + +/// A surface near a point as a height over its tangent plane, to order `order` (2 … 4): the +/// forms `H_m` for `m = 2 ..= order` on the frame `t = n × w`, `w` (both unit, in the tangent +/// plane; `w` the direction the surface leaves the shared curve in). `forms[m − 2][j]` is the +/// coefficient of `x_t^(m−j)·x_w^j` in `H_m(x)`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Jet { + pub order: usize, + pub forms: [[f64; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1], +} + +impl Jet { + /// `H_m(a)` for a tangent vector given by its components `(a_t, a_w)`. + pub fn form(&self, m: usize, a: [f64; 2]) -> Option { + let coefficients = self.forms.get(m.checked_sub(2)?).filter(|_| (2..=self.order).contains(&m))?; + Some((0..=m).map(|j| coefficients.get(j).copied().unwrap_or(0.0) * a[0].powi((m - j) as i32) * a[1].powi(j as i32)).sum()) + } + + /// Whether every coefficient is finite. + pub fn is_finite(&self) -> bool { + self.forms.iter().flatten().all(|x| x.is_finite()) + } + + /// What orders `2 ..= self.order` ask of `n·c⁽ᵏ⁾` (module docs), for a curve whose first + /// derivatives have the tangent-plane components `x[j − 1] = (x_j·t, x_j·w)`: element + /// `k − 2` is order k's (it reads `x[0 .. k − 1]`). `None` when too few derivatives are given. + pub fn targets(&self, x: &[[f64; 2]]) -> Option> { + Some(self.linearised(x)?.into_iter().map(|t| t.value).collect()) + } + + /// [`Jet::targets`] with their exact gradients: element `k − 2` is order k's target and its + /// derivative with respect to each component of each `x_j` (`gradient[j − 1]`), so that the + /// condition `n·c⁽ᵏ⁾ = target(x)` can be linearised about a curve (Newton's method). + pub fn linearised(&self, x: &[[f64; 2]]) -> Option> { + let top = self.order; + if x.len() + 1 < top || top > MAX_CONTINUITY { + return None; + } + // x(σ) as truncated Taylor series in each component (no constant term), each coefficient + // a dual number seeded with its own component. + let mut series = [vec![Dual::ZERO; top + 1], vec![Dual::ZERO; top + 1]]; + for (j, xj) in x.iter().enumerate().take(top.saturating_sub(1)) { + for (c, (s, value)) in series.iter_mut().zip(xj).enumerate() { + if let Some(slot) = s.get_mut(j + 1) { + *slot = Dual::seed(*value, 2 * j + c).scale(1.0 / factorial(j + 1)); + } + } + } + let mut height = vec![Dual::ZERO; top + 1]; + for m in 2..=top { + let coefficients = self.forms.get(m - 2)?; + for (j, c) in coefficients.iter().enumerate().take(m + 1) { + let monomial = mul(&power(&series[0], m - j, top), &power(&series[1], j, top), top); + for (h, x) in height.iter_mut().zip(&monomial) { + *h = *h + x.scale(c / factorial(m)); + } + } + } + Some( + (2..=top) + .map(|k| { + let d = height.get(k).copied().unwrap_or(Dual::ZERO).scale(factorial(k)); + let mut gradient = [[0.0; 2]; MAX_CONTINUITY - 1]; + for (j, g) in gradient.iter_mut().enumerate() { + *g = [d.grad[2 * j], d.grad[2 * j + 1]]; + } + Target { value: d.value, gradient } + }) + .collect(), + ) + } +} + +/// One order's target and its gradient (see [`Jet::linearised`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Target { + pub value: f64, + /// `gradient[j − 1]`: the derivative with respect to `(x_j·t, x_j·w)`. + pub gradient: [[f64; 2]; MAX_CONTINUITY - 1], +} + +/// Gradients carried: two components of each of `x₁ … x₃`. +const SEEDS: usize = 2 * (MAX_CONTINUITY - 1); + +/// A number with its gradient with respect to the [`SEEDS`] components (forward differentiation: +/// the targets are polynomials in them, so the gradient is exact). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Dual { + value: f64, + grad: [f64; SEEDS], +} + +impl Dual { + const ZERO: Dual = Dual { value: 0.0, grad: [0.0; SEEDS] }; + const ONE: Dual = Dual { value: 1.0, grad: [0.0; SEEDS] }; + + fn seed(value: f64, at: usize) -> Dual { + let mut grad = [0.0; SEEDS]; + if let Some(g) = grad.get_mut(at) { + *g = 1.0; + } + Dual { value, grad } + } + + fn scale(self, k: f64) -> Dual { + Dual { value: self.value * k, grad: self.grad.map(|g| g * k) } + } +} + +impl std::ops::Add for Dual { + type Output = Dual; + fn add(self, o: Dual) -> Dual { + let mut grad = self.grad; + for (g, h) in grad.iter_mut().zip(o.grad) { + *g += h; + } + Dual { value: self.value + o.value, grad } + } +} + +impl std::ops::Mul for Dual { + type Output = Dual; + fn mul(self, o: Dual) -> Dual { + let mut grad = [0.0; SEEDS]; + for ((g, a), b) in grad.iter_mut().zip(self.grad).zip(o.grad) { + *g = a * o.value + self.value * b; + } + Dual { value: self.value * o.value, grad } + } +} + +/// `k!` as a float (small k). +fn factorial(k: usize) -> f64 { + (1..=k).map(|i| i as f64).product() +} + +/// The numbers the series below are over: plain floats and [`Dual`]s. +trait Coefficient: Copy + std::ops::Add + std::ops::Mul { + const ZERO: Self; + const ONE: Self; +} + +impl Coefficient for f64 { + const ZERO: f64 = 0.0; + const ONE: f64 = 1.0; +} + +impl Coefficient for Dual { + const ZERO: Dual = Dual::ZERO; + const ONE: Dual = Dual::ONE; +} + +/// The product of two truncated series (coefficients of `σ⁰ … σ^top`). +fn mul(a: &[T], b: &[T], top: usize) -> Vec { + let mut out = vec![T::ZERO; top + 1]; + for (i, x) in a.iter().enumerate().take(top + 1) { + for (j, y) in b.iter().enumerate().take(top + 1 - i) { + if let Some(slot) = out.get_mut(i + j) { + *slot = *slot + *x * *y; + } + } + } + out +} + +/// A truncated series to the power `e`. +fn power(a: &[T], e: usize, top: usize) -> Vec { + let mut one = vec![T::ZERO; top + 1]; + if let Some(c) = one.first_mut() { + *c = T::ONE; + } + (0..e).fold(one, |acc, _| mul(&acc, a, top)) +} + +/// The surface `s` near `uv` as a height along its unit normal `n` (either sign) over its tangent +/// plane, to order `order` (2 ..= [`MAX_CONTINUITY`]), on the frame `t = n × w`, `w` (`w` a unit +/// tangent vector): see [`Jet`] and the module docs. `None` where the surface has no tangent +/// plane (a pole) or cannot be evaluated. +pub fn surface_jet(s: &SurfaceEval, uv: [f64; 2], n: Vec3, w: Vec3, order: usize) -> Option { + if !(2..=MAX_CONTINUITY).contains(&order) { + return None; + } + let d = s.partials(uv[0], uv[1])?; + let t = n.cross(w); + let mut forms = [[0.0; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1]; + // H_m(t + λ w) is a polynomial of degree m in λ: its coefficients are the form's. + const NODES: [f64; MAX_CONTINUITY + 1] = [0.0, 1.0, -1.0, 2.0, -2.0]; + let along: Vec> = NODES.iter().map(|l| heights(&d, n, t + w * *l, order)).collect::>()?; + for m in 2..=order { + let values: Vec = along.iter().take(m + 1).map(|h| h.get(m).copied().unwrap_or(f64::NAN)).collect(); + let coefficients = polynomial_through(NODES.get(..=m)?, &values)?; + let slot = forms.get_mut(m - 2)?; + for (x, c) in slot.iter_mut().zip(coefficients) { + *x = c; + } + } + let jet = Jet { order, forms }; + jet.is_finite().then_some(jet) +} + +/// `H_m(a)` for `m = 0 ..= order` from the partials `d` (`d[i][j] = S^(i,j)`): the curve on +/// the surface whose foot runs straight along `a` (module docs), its parameter series solved +/// order by order. `None` where the tangent plane degenerates. +fn heights(d: &Partials, n: Vec3, a: Vec3, order: usize) -> Option> { + let at = |i: usize, j: usize| d.get(i).and_then(|r| r.get(j)).copied(); + let (su, sv) = (at(1, 0)?, at(0, 1)?); + let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv)); + let det = e * g - f * f; + // A pole: one parameter direction collapses against the other (or the two run together). + if !(e.min(g) > 1e-20 * e.max(g) && det > 1e-12 * e * g) { + return None; + } + // The rates (du, dv) whose image S_u du + S_v dv has tangent-plane part `b`. + let rates = |b: Vec3| { + let (bu, bv) = (b.dot(su), b.dot(sv)); + ((g * bu - f * bv) / det, (e * bv - f * bu) / det) + }; + let tangential = |x: Vec3| x - n * x.dot(n); + let mut du = vec![0.0; order + 1]; + let mut dv = vec![0.0; order + 1]; + for k in 1..=order { + // The coefficient of τᵏ with this order's rates still nought, then the rates that make + // its tangent-plane part `a` (k = 1) or zero. + let have = composed(d, &du, &dv, order)?.get(k).copied()?; + let want = if k == 1 { tangential(a) } else { Vec3::ZERO }; + let (x, y) = rates(want - tangential(have)); + *du.get_mut(k)? = x; + *dv.get_mut(k)? = y; + } + let c = composed(d, &du, &dv, order)?; + Some(c.iter().enumerate().map(|(k, x)| factorial(k) * n.dot(*x)).collect()) +} + +/// The Taylor coefficients of `S(u₀ + δu(τ), v₀ + δv(τ)) − S(u₀, v₀)` to order `order`, for the +/// series `δu`, `δv` (no constant term) and the partials `d`. +fn composed(d: &Partials, du: &[f64], dv: &[f64], order: usize) -> Option> { + let mut out = vec![Vec3::ZERO; order + 1]; + for (i, row) in d.iter().enumerate() { + for (j, partial) in row.iter().enumerate() { + if i + j == 0 || i + j > order { + continue; + } + let term = mul(&power(du, i, order), &power(dv, j, order), order); + let scale = 1.0 / (factorial(i) * factorial(j)); + for (o, x) in out.iter_mut().zip(&term) { + *o += *partial * (x * scale); + } + } + } + out.iter().all(|p| p.is_finite()).then_some(out) +} + +/// The coefficients `c₀ … c_m` of the polynomial of degree `m = nodes.len() − 1` through +/// `(nodes[i], values[i])` (Newton's divided differences, expanded). +fn polynomial_through(nodes: &[f64], values: &[f64]) -> Option> { + let m = nodes.len(); + if values.len() != m || m == 0 { + return None; + } + let mut dd = values.to_vec(); + for level in 1..m { + for i in (level..m).rev() { + let span = nodes.get(i)? - nodes.get(i - level)?; + if span == 0.0 { + return None; + } + *dd.get_mut(i)? = (dd.get(i)? - dd.get(i - 1)?) / span; + } + } + // Horner on the Newton form: p(λ) = dd₀ + (λ − x₀)(dd₁ + (λ − x₁)(…)). + let mut c = vec![0.0; m]; + for i in (0..m).rev() { + // c ← c·(λ − x_i) + dd_i. + let x = *nodes.get(i)?; + let mut next = vec![0.0; m]; + for (k, ck) in c.iter().enumerate() { + if let Some(slot) = next.get_mut(k + 1) { + *slot += ck; + } + if let Some(slot) = next.get_mut(k) { + *slot -= ck * x; + } + } + if let Some(slot) = next.get_mut(0) { + *slot += dd.get(i)?; + } + c = next; + } + c.iter().all(|x| x.is_finite()).then_some(c) +} + +#[cfg(test)] +#[path = "linkage_tests.rs"] +mod tests; diff --git a/crates/geom/src/linkage_tests.rs b/crates/geom/src/linkage_tests.rs new file mode 100644 index 000000000..d559fbb85 --- /dev/null +++ b/crates/geom/src/linkage_tests.rs @@ -0,0 +1,95 @@ +use super::*; +use crate::brep::{Frame, Surface}; + +fn frame() -> Frame { + Frame { origin: [1.0, -2.0, 0.5], x_axis: [1.0, 0.0, 0.0], y_axis: [0.0, 1.0, 0.0] } +} + +/// A sphere of radius `r` as a height over its tangent plane along the outward normal: +/// `H(x) = √(r² − |x|²) − r`, so `H₂(a) = −|a|²/r`, `H₃ = 0`, `H₄(a) = −3|a|⁴/r³`. +#[test] +fn a_sphere_is_a_height_whose_forms_are_its_radius_s() { + let r = 7.0; + let s = SurfaceEval::new(&Surface::Sphere { frame: frame(), radius: r }).unwrap(); + for uv in [[0.3, 0.2], [2.0, -0.9], [4.5, 1.1]] { + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + let n = su.cross(sv).normalized().unwrap(); + let w = (su + sv * 0.5).normalized().unwrap(); + let jet = surface_jet(&s, uv, n, w, 4).unwrap(); + for (a, len2) in [([1.0, 0.0], 1.0), ([0.0, 1.0], 1.0), ([1.0, 1.0], 2.0), ([0.6, -0.8], 1.0)] { + assert!((jet.form(2, a).unwrap() + len2 / r).abs() < 1e-12, "H2 at {uv:?} along {a:?}"); + assert!(jet.form(3, a).unwrap().abs() < 1e-11, "H3 at {uv:?} along {a:?}"); + assert!((jet.form(4, a).unwrap() + 3.0 * len2 * len2 / r.powi(3)).abs() < 1e-11, "H4 at {uv:?} along {a:?}"); + } + } +} + +/// A cylinder bends across its axis only: the height depends on the component round it, as the +/// circle's `√(r² − x²) − r` does; along its axis it is straight. +#[test] +fn a_cylinder_bends_round_its_axis_and_not_along_it() { + let r = 4.0; + let s = SurfaceEval::new(&Surface::Cylinder { frame: frame(), radius: r }).unwrap(); + let uv = [0.7, 3.0]; + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + let n = su.cross(sv).normalized().unwrap(); + // w along the axis: t = n × w runs round the cylinder. + let jet = surface_jet(&s, uv, n, sv.normalized().unwrap(), 4).unwrap(); + let around = [1.0, 0.0]; + assert!((jet.form(2, around).unwrap().abs() - 1.0 / r).abs() < 1e-12); + assert!((jet.form(4, around).unwrap().abs() - 3.0 / r.powi(3)).abs() < 1e-11); + for m in 2..=4 { + assert!(jet.form(m, [0.0, 1.0]).unwrap().abs() < 1e-12, "straight along the axis: H{m}"); + } +} + +/// The same cylinder on its NURBS form (rational quadratic arcs, as SMLib holds it) has the same +/// jet: the height is the surface's, whatever its parameterisation. +#[test] +fn a_cylinder_and_its_nurbs_form_have_one_jet() { + let label = Surface::Cylinder { frame: frame(), radius: 4.0 }; + let (form, _) = crate::brep::form::surface(&label, [[0.0, 2.0], [-1.0, 5.0]]).unwrap(); + let (a, b) = (SurfaceEval::new(&label).unwrap(), SurfaceEval::new(&form).unwrap()); + let p = a.point([0.9, 2.0]).unwrap(); + let uv = b.project(p, None, 1e-9).unwrap(); + let (_, su, sv) = a.derivs(0.9, 2.0).unwrap(); + let n = su.cross(sv).normalized().unwrap(); + let w = (su.normalized().unwrap() * 0.6 + sv * 0.8).normalized().unwrap(); + let (ja, jb) = (surface_jet(&a, [0.9, 2.0], n, w, 4).unwrap(), surface_jet(&b, uv, n, w, 4).unwrap()); + for m in 2..=4 { + for x in [[1.0, 0.0], [0.0, 1.0], [0.3, 0.7]] { + let (fa, fb) = (ja.form(m, x).unwrap(), jb.form(m, x).unwrap()); + assert!((fa - fb).abs() < 1e-9 * fa.abs().max(1.0), "H{m}({x:?}): {fa} vs {fb}"); + } + } +} + +/// The targets are the linkage conditions: order 2 the form in the curve's direction, order 3 +/// `3·H₂(x₁, x₂) + H₃(x₁)`. +#[test] +fn the_targets_are_the_height_s_taylor_terms_along_the_curve() { + let mut forms = [[0.0; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1]; + forms[0] = [2.0, 0.5, -1.0, 0.0, 0.0]; + forms[1] = [0.3, -0.2, 0.1, 0.7, 0.0]; + let jet = Jet { order: 3, forms }; + let (x1, x2) = ([0.8, 0.4], [0.1, -0.5]); + let got = jet.targets(&[x1, x2]).unwrap(); + let h2 = |a: [f64; 2], b: [f64; 2]| 2.0 * a[0] * b[0] + 0.25 * (a[0] * b[1] + a[1] * b[0]) - a[1] * b[1]; + assert!((got[0] - h2(x1, x1)).abs() < 1e-14); + assert!((got[1] - (3.0 * h2(x1, x2) + jet.form(3, x1).unwrap())).abs() < 1e-14); + assert!(jet.targets(&[x1]).is_none(), "order 3 reads c″"); +} + +#[test] +fn hostile_orders_and_degenerate_points_are_refused() { + let s = SurfaceEval::new(&Surface::Sphere { frame: frame(), radius: 2.0 }).unwrap(); + let (n, w) = (Vec3::Z, Vec3::X); + assert!(surface_jet(&s, [0.0, 0.0], Vec3::X, Vec3::Y, 5).is_none()); + assert!(surface_jet(&s, [0.0, 0.0], Vec3::X, Vec3::Y, 1).is_none()); + // At the pole the latitude's parameterisation has no tangent plane. + assert!(surface_jet(&s, [0.0, std::f64::consts::FRAC_PI_2], n, w, 2).is_none()); + assert!(surface_jet(&s, [f64::NAN, 0.0], n, w, 2).is_none()); + let jet = Jet { order: 2, forms: [[f64::NAN; MAX_CONTINUITY + 1]; MAX_CONTINUITY - 1] }; + assert!(!jet.is_finite()); + assert!(jet.form(3, [1.0, 0.0]).is_none(), "beyond its order"); +} diff --git a/crates/geom/src/profile.rs b/crates/geom/src/profile.rs index f51cfcbd2..49220d182 100644 --- a/crates/geom/src/profile.rs +++ b/crates/geom/src/profile.rs @@ -384,8 +384,23 @@ impl Seg2 { _ => {} } let n = 64; - let mut t = - (0..=n).map(|i| i as f64 / n as f64).min_by(|x, y| self.point_at(*x).dist(p).total_cmp(&self.point_at(*y).dist(p))).unwrap_or(0.0); + let t = (0..=n).map(|i| i as f64 / n as f64).min_by(|x, y| self.point_at(*x).dist(p).total_cmp(&self.point_at(*y).dist(p))).unwrap_or(0.0); + let t = self.newton_closest(p, t); + // A closed segment (a full circle) starts where it ends: a point just before its start is + // nearest just before its end, which Newton from the start (held there by the clamp) + // never reaches. Try from the other end too. + let (a, b) = (self.point_at(0.0), self.point_at(1.0)); + if (t == 0.0 || t == 1.0) && a.dist(b) <= 1e-12 * (1.0 + a.len()) { + let other = self.newton_closest(p, 1.0 - t); + if self.point_at(other).dist(p) < self.point_at(t).dist(p) { + return other; + } + } + t + } + + /// Newton's method for the parameter of the point nearest `p`, from `t`, within [0, 1]. + fn newton_closest(&self, p: Vec2, mut t: f64) -> f64 { for _ in 0..30 { let (q, d) = (self.point_at(t), self.derivative(t)); let (d2, h) = ((self.derivative((t + 1e-6).min(1.0)) - self.derivative((t - 1e-6).max(0.0))) / 2e-6, q - p); @@ -403,6 +418,7 @@ impl Seg2 { } t } + /// The two halves of the segment (same kind, exact). pub fn split_half(&self) -> (Seg2, Seg2) { match *self { @@ -965,6 +981,16 @@ mod tests { assert!(s.point_at(s.closest_param(on_curve)).dist(on_curve) < 1e-9); } } + // A full circle's points just before its start, either way round: nearest just before + // its end, not at its start (Newton from the start stays held there). + for sweep in [TAU, -TAU] { + let circle = Seg2::Arc { center: Vec2::new(1.0, 2.0), radius: 5.0, start: 0.6131, sweep }; + for delta in [1e-4, 0.01, 0.04] { + let before = 0.6131 - delta * sweep.signum(); + let p = Vec2::new(1.0, 2.0) + Vec2::from_angle(before) * 4.99; + assert!((circle.point_at(circle.closest_param(p)).dist(p) - 0.01).abs() < 1e-9, "sweep {sweep}, {delta}"); + } + } } /// The sweep visits only the edges crossing each slab; it must give the triangles that diff --git a/crates/geom/src/spline_space.rs b/crates/geom/src/spline_space.rs index 6456ee8c2..82ac3efea 100644 --- a/crates/geom/src/spline_space.rs +++ b/crates/geom/src/spline_space.rs @@ -76,6 +76,30 @@ impl Linear for Vec3 { } } +/// Homogeneous points as they are: a rational spline's control values `(x·w, y·w, z·w, w)` +/// combine linearly, so carrying one into a larger space (degree elevation, knot insertion) is +/// exact on them. +impl Linear for HPoint { + fn zero() -> Self { + HPoint::ZERO + } + fn plus(self, o: Self) -> Self { + self + o + } + fn times(self, s: f64) -> Self { + self * s + } + fn to_h(self) -> HPoint { + self + } + fn from_h(h: HPoint) -> Self { + h + } + fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite() + } +} + /// A clamped B-spline space: a degree and a knot vector whose first and last `degree + 1` knots /// are the domain's ends, interior knots repeated at most `degree` times (the space's splines /// are continuous). @@ -168,6 +192,27 @@ impl Space { Ok((first, values.collect())) } + /// [`Space::basis`] from the left of `t`: at an interior knot, the derivatives of the + /// polynomial piece that ends there (elsewhere the same as from the right). + pub fn basis_left(&self, t: f64, der: usize) -> SplineResult<(usize, Vec)> { + let [a, b] = self.domain(); + if !t.is_finite() { + return invalid("a parameter is not a finite number"); + } + let t = t.clamp(a, b); + if t <= a { + return self.basis(t, der); + } + let p = self.degree; + // The span [k_s, k_{s+1}) with k_s < t ≤ k_{s+1}. + let below = self.knots.partition_point(|&x| x < t); + let span = below.checked_sub(1).filter(|s| *s >= p).ok_or_else(|| SplineError::Invalid(format!("{t} is outside the domain")))?; + let first = span - p; + let values = + (first..=span).map(|i| self.knots.get(i..i + p + 2).map_or(0.0, |k| local_basis(k, t, Side::Left, der).get(der).copied().unwrap_or(0.0))); + Ok((first, values.collect())) + } + /// The `der`-th derivative at `t` of the spline with control values `ctrl`. pub fn eval(&self, ctrl: &[T], t: f64, der: usize) -> SplineResult { if ctrl.len() != self.count() { diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rs index 4c618b2fc..309c02e9d 100644 --- a/crates/gpu/tests/capture.rs +++ b/crates/gpu/tests/capture.rs @@ -160,6 +160,8 @@ fn pictures_show_the_section_and_its_cap() { let mut cam = view::home_camera(&s).unwrap(); cam.fov = fov; let mut sc = view::scene(&s, &cam).unwrap(); + // The cap in the cap colour: a part's hatch colour is the one its name picks (#8529). + sc.part_hatch = None; // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); sc.lines.push(SceneLine { diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 245f197a5..12c6e83d2 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -838,8 +838,12 @@ mod tests { assert!(o.contains("o Body1") && o.contains("\nf ")); } - /// OBJ shares a face's vertices (a cube: 8 positions, 6 normals, not 36 of each) and keeps - /// the body name as written, spaces included. + /// OBJ shares the vertices faces meet at and keeps the body name as written, spaces included. + /// The 10 × 20 × 30 box meshes as the planner's grids, no side longer than a fifth of its + /// extent (the 37.4 mm diagonal): its edges in 2, 3 and 5 pieces, so its faces are grids of + /// 2 × 3, 2 × 5 and 3 × 5 cells, 2 · (6 + 10 + 15) · 2 = 124 triangles. Welded, their + /// corners are the 3 · 4 · 6 = 72 nodes of the box's lattice less the 1 · 2 · 4 inside it: 64 + /// positions (unwelded, 372), and one normal per face. #[test] fn obj_export_is_welded_and_keeps_names() { let (_, m) = model(); @@ -850,10 +854,10 @@ mod tests { let o = String::from_utf8(export(&st, &[], Format::Obj, "t").unwrap()).unwrap(); let count = |p: &str| o.lines().filter(|l| l.starts_with(p)).count(); assert!(o.contains("\no Red Block\n"), "{o}"); - assert_eq!((count("v "), count("vn "), count("f ")), (8, 6, 12), "{o}"); + assert_eq!((count("v "), count("vn "), count("f ")), (64, 6, 124), "{o}"); let ids: Vec = o.lines().filter(|l| l.starts_with("f ")).flat_map(|l| l.split([' ', '/']).skip(1)).filter_map(|x| x.parse().ok()).collect(); - assert!(ids.iter().all(|i| (1..=8).contains(i) || (1..=6).contains(i))); + assert!(ids.iter().all(|i| (1..=64).contains(i))); } /// The design properties land in each format's own metadata (#1015): STEP and IGES headers, diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 915658809..5098f69f9 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -617,6 +617,13 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl crate::blend_smlib::chamfer_sides(body, edges, d1, side, flip) } +/// The edge each pick takes, as a blend takes it (an index in the body's edge order, the order +/// of its mesh's edges): the nearest, and at a vertex where a seam or a smooth join meets a sharp +/// edge (a cylinder's seam at its rim), the sharp edge. Picks that find no edge are refused. +pub fn blend_edges(body: &Body, picks: &[Vec3]) -> Result> { + crate::blend_smlib::picked_edges(body, picks).map(|(edges, _)| edges) +} + /// The picked edges' tangent chains, for a blend that is to run along them: `picks` (each the /// nearest edge of `body` to it), then a point on every other edge that continues one of them /// tangentially (within 0.5° at a shared vertex), until no more do. Each pick takes its edge as a @@ -627,20 +634,58 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl /// a round cannot pass from one side of the faces to the other, so it ends at that vertex. /// Picks that find no edge are refused. pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { - /// Edges meeting at an angle below this continue one another. - const TANGENT_DEGREES: f64 = 0.5; if picks.is_empty() || picks.len() > 1000 || picks.iter().any(|p| !p.is_finite()) { return Err(KernelError::Invalid("select 1…1000 edges by finite points".into())); } let rec = Faces::of(body)?; let (seeds, hidden) = crate::blend_smlib::picked_edges(body, picks)?; - let mut chain: Vec = Vec::new(); + let mut picked: Vec = Vec::new(); for e in seeds { - if !chain.contains(&e) { - chain.push(e); + if !picked.contains(&e) { + picked.push(e); } } - let picked = chain.len(); + let chain = chain_of(&rec, &picked, &hidden); + let mut out = picks.to_vec(); + for e in chain.into_iter().skip(picked.len()) { + out.push(edge_middle(&rec, e).ok_or_else(|| KernelError::Failed("a point on a chain edge".into()))?); + } + Ok(out) +} + +/// Edges meeting at an angle below this continue one another; faces meeting at an angle below +/// it meet tangentially. +const TANGENT_DEGREES: f64 = 0.5; + +/// The point halfway along edge `e`. +fn edge_middle(rec: &Faces, e: usize) -> Option { + let edge = rec.rec.edges.get(e)?; + CurveEval::new(edge.parameters()).ok().and_then(|c| c.point(0.5 * (edge.interval[0] + edge.interval[1]))) +} + +/// How far from a face's surface a point may lie for its normal there. +fn normal_reach(rec: &Faces) -> f64 { + rec.rec.tolerance.max(1e-7) * 10.0 +} + +/// Whether edge `e`'s two faces meet tangentially (within [`TANGENT_DEGREES`]) at its start: a +/// smooth edge, with no corner to blend. +fn smooth_join(rec: &Faces, e: usize) -> bool { + let cos = TANGENT_DEGREES.to_radians().cos(); + let accept = normal_reach(rec); + let faces: Vec = rec.faces_of(e).into_iter().collect(); + let (Some(&a), Some(&b), Some((p, _))) = (faces.first(), faces.get(1), rec.ends(e)) else { return false }; + match (rec.normal_at(a as usize, p, accept), rec.normal_at(b as usize, p, accept)) { + (Some(na), Some(nb)) => faces.len() == 2 && na.dot(nb) > cos, + _ => false, + } +} + +/// `seeds` (edges in the record's order, each once), then every other edge that continues one +/// of them tangentially, as [`tangent_chain`] follows them; `hidden` marks the edges a pick +/// passes over. +fn chain_of(rec: &Faces, seeds: &[usize], hidden: &[bool]) -> Vec { + let mut chain = seeds.to_vec(); // The unit direction edge `e` leaves its end `v` in. let leaving = |e: usize, v: u32| -> Option { let [a, b] = rec.rec.edges.get(e)?.vertices; @@ -650,16 +695,7 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { if a == v { rec.tangent(e, false) } else { rec.tangent(e, true).map(|t| t * -1.0) } }; let cos = TANGENT_DEGREES.to_radians().cos(); - let accept = rec.rec.tolerance.max(1e-7) * 10.0; - // Whether edge `e`'s two faces meet tangentially at its start. - let smooth = |e: usize| -> bool { - let faces: Vec = rec.faces_of(e).into_iter().collect(); - let (Some(&a), Some(&b), Some((p, _))) = (faces.first(), faces.get(1), rec.ends(e)) else { return false }; - match (rec.normal_at(a as usize, p, accept), rec.normal_at(b as usize, p, accept)) { - (Some(na), Some(nb)) => faces.len() == 2 && na.dot(nb) > cos, - _ => false, - } - }; + let accept = normal_reach(rec); // Whether edge `e` is convex at its end `v` (its faces meet at less than 180° inside the // body): the direction into its second face, square to it, points against its first face's // outward normal. A face lies to the left of its loop seen from its surface's natural normal. @@ -686,7 +722,7 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { let Some(d) = leaving(e, v) else { continue }; for (f, other) in rec.rec.edges.iter().enumerate() { let passed_over = hidden.get(f).copied().unwrap_or(false); - if passed_over || chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) || smooth(f) { + if passed_over || chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) || smooth_join(rec, f) { continue; } let turns_over = matches!((convex(e, v), convex(f, v)), (Some(a), Some(b)) if a != b); @@ -696,16 +732,47 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { } } } - let mut out = picks.to_vec(); - for e in chain.into_iter().skip(picked) { - let edge = rec.rec.edges.get(e).ok_or_else(|| KernelError::Failed("a chain edge".into()))?; - let mid = CurveEval::new(edge.parameters()) - .ok() - .and_then(|c| c.point(0.5 * (edge.interval[0] + edge.interval[1]))) - .ok_or_else(|| KernelError::Failed("a point on a chain edge".into()))?; - out.push(mid); + chain +} + +/// Before blending exactly `edges` (the record's edges `picks` took, in order): refuses an edge +/// whose faces meet tangentially (a smooth edge, nothing to round), and names the first edge a +/// picked one runs on into tangentially without being blended with it, if any (tangent +/// propagation off). SMLib blends the picked edges alone where it can end a blend there (a round +/// ending on the round it runs into); where it can't, [`with_continuation`] says why. +pub(crate) fn unfinished_chain(body: &Body, picks: &[Vec3], edges: &[usize], hidden: &[bool]) -> Result> { + let rec = Faces::of(body)?; + let at = |i: usize| picks.get(i).map(|p| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)).unwrap_or_default(); + for (i, &e) in edges.iter().enumerate() { + if smooth_join(&rec, e) { + return Err(KernelError::Invalid(format!("the edge at {} is smooth: its faces meet tangentially, so there is nothing to round", at(i)))); + } + } + let mut seeds: Vec = Vec::new(); + for &e in edges { + if !seeds.contains(&e) { + seeds.push(e); + } + } + Ok(chain_of(&rec, &seeds, hidden).get(seeds.len()).and_then(|&next| edge_middle(&rec, next))) +} + +/// A blend's failure where a picked edge continues tangentially into `next`, an edge left out +/// ([`unfinished_chain`]): SMLib rounds a tangent chain as one sequence and could not end the +/// blend there, so the reason and the way out are named. +pub(crate) fn with_continuation(e: KernelError, next: Option) -> KernelError { + let Some(p) = next else { return e }; + let why = format!( + " (a picked edge continues tangentially into the edge at ({:.3}, {:.3}, {:.3}), which is not blended with it, and the blend \ + cannot end there: with tangent propagation on, tangent_chain: true, its tangent chain is blended as one)", + p.x, p.y, p.z + ); + match e { + KernelError::Invalid(m) => KernelError::Invalid(m + &why), + KernelError::Failed(m) => KernelError::Failed(m + &why), + KernelError::TooLarge(m) => KernelError::TooLarge(m + &why), + e => e, } - Ok(out) } #[cfg(test)] diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs index 05049a7f2..c99932a86 100644 --- a/crates/kernel/src/blend_corner.rs +++ b/crates/kernel/src/blend_corner.rs @@ -177,13 +177,15 @@ mod tests { // using the reported picks, with and without the open cavity visible in the screenshot. let picks = [Vec3::new(-5.0, 87.2, 12.5), Vec3::new(-4.283446394180081, 86.48344639418008, -1.5001085324947512)]; for base in [b.clone(), crate::shell(&b, &[Vec3::new(15.0, 47.2, 25.0)], 1.0).unwrap()] { + // Each fillet with its tangent chain, as the Fillet feature asks for it by default + // (tangent propagation). let mut rounded = base; for edge in bottom { - rounded = fillet(&rounded, &[edge], 2.0).unwrap(); + rounded = fillet(&rounded, &crate::tangent_chain(&rounded, &[edge]).unwrap(), 2.0).unwrap(); } - let reference = fillet(&rounded, &picks[..1], 2.0).unwrap(); + let reference = fillet(&rounded, &crate::tangent_chain(&rounded, &picks[..1]).unwrap(), 2.0).unwrap(); for selection in [picks, [picks[1], picks[0]]] { - let result = fillet(&rounded, &selection, 2.0).unwrap(); + let result = fillet(&rounded, &crate::tangent_chain(&rounded, &selection).unwrap(), 2.0).unwrap(); assert_eq!(result.face_count(), reference.face_count()); assert_eq!(result.unmeshed_faces(), 0); assert!(result.validity().is_empty(), "{:?}", result.validity()); diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs index 7d60d42e3..f7747e37f 100644 --- a/crates/kernel/src/blend_smlib.rs +++ b/crates/kernel/src/blend_smlib.rs @@ -191,6 +191,7 @@ mod imp { body.require_brep(what)?; sizes_ok(what, sizes)?; let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; let kind = match kind { Kind::Round => Blend::Round, Kind::Curvature => Blend::Curvature, @@ -198,7 +199,7 @@ mod imp { Kind::Chamfer => Blend::Chamfer, }; let tol = pick_tolerance(body); - run(body, what, &picked.edges, |b| b.blend(kind, &picked.points, sizes, tol)) + run(body, what, &picked.edges, |b| b.blend(kind, &picked.points, sizes, tol)).map_err(|e| crate::blend::with_continuation(e, next)) } /// Rounds with corner setbacks: each corner point picks the body's nearest vertex (within @@ -214,12 +215,14 @@ mod imp { return Err(KernelError::Invalid(format!("{what}: each corner is a finite point with a positive, finite setback"))); } let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; let corners = corner_vertices(body, setbacks.iter().map(|(p, _)| *p))?; let distances: Vec = setbacks.iter().map(|(_, d)| *d).collect(); let tol = pick_tolerance(body); let at: Vec = setbacks.iter().map(|(p, _)| *p).collect(); run_with(body, what, &picked.edges, &at, |b| b.blend_setback(Blend::Round, &picked.points, sizes, &corners, &distances, tol).map(|r| (r, ()))) .map(|(out, (), _)| out) + .map_err(|e| crate::blend::with_continuation(e, next)) } /// [`blend_setback`] with the set-back corners left open (`super::OpenCorners`). @@ -234,12 +237,14 @@ mod imp { return Err(KernelError::Invalid(format!("{what}: each corner is a finite point with a positive, finite setback"))); } let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; let corners = corner_vertices(body, setbacks.iter().map(|(p, _)| *p))?; let distances: Vec = setbacks.iter().map(|(_, d)| *d).collect(); let at: Vec = setbacks.iter().map(|(p, _)| *p).collect(); let tol = pick_tolerance(body); let (sheet, holes, order) = - run_with(body, what, &picked.edges, &at, |b| b.blend_setback_open(Blend::Round, &picked.points, sizes, &corners, &distances, tol))?; + run_with(body, what, &picked.edges, &at, |b| b.blend_setback_open(Blend::Round, &picked.points, sizes, &corners, &distances, tol)) + .map_err(|e| crate::blend::with_continuation(e, next))?; // SMLib's indices in the sheet's own orders. let place = |list: &[usize], i: usize| if list.is_empty() { Some(i) } else { list.get(i).copied() }; let renumber = |hole: &solidcraft_smlib::Hole| -> Result> { @@ -281,6 +286,7 @@ mod imp { body.require_brep("chamfer")?; sizes_ok("chamfer", &vec![d1; edges.len()])?; let picked = resolve(body, edges)?; + let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; let second = match side { crate::ChamferSide::Distance(d) => ChamferSecond::Distance(d), crate::ChamferSide::Angle(a) => ChamferSecond::Angle(a), @@ -288,6 +294,7 @@ mod imp { let up = if flip { [0.0, 0.0, -1.0] } else { [0.0, 0.0, 1.0] }; let tol = pick_tolerance(body); run(body, "chamfer", &picked.edges, |b| b.chamfer_sides(&picked.points, tol, d1, second, up)) + .map_err(|e| crate::blend::with_continuation(e, next)) } pub(super) fn variable(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result { @@ -296,11 +303,13 @@ mod imp { return Err(KernelError::Invalid("the start point must be finite".into())); } let picked = resolve(body, &[edge_at])?; + let next = crate::blend::unfinished_chain(body, &[edge_at], &picked.edges, &picked.hidden)?; let [at] = picked.points[..] else { return Err(KernelError::Invalid("one edge".into())) }; let tol = pick_tolerance(body); run(body, "variable fillet", &picked.edges, |b| { b.fillet_variable(at, tol, [start.x, start.y, start.z], spline.degree, &spline.knots, &spline.radii) }) + .map_err(|e| crate::blend::with_continuation(e, next)) } /// `op` on `body` in SMLib, tagged as operand 0, checked, decoded, with its history. @@ -334,6 +343,10 @@ mod imp { None => failed(what, "operation", SmError::CornerRefused { corner }), }, SmError::NoEffect => KernelError::Failed(format!("SMLib made no change: the {what} reported success but built no face")), + SmError::CornerUnsupported => KernelError::Invalid(format!( + "not supported yet: the {what} meets a corner of this kind, which SMLib's blends do not handle yet (where its edges \ + run on tangentially into each other, or meet in a way no blend corner builds)" + )), SmError::NoRoom => KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow")), e => failed(what, "operation", e), })?; @@ -594,4 +607,37 @@ mod tests { assert!(imp::blend(&b, "fillet", Kind::Round, &[Vec3::new(f64::NAN, 20.0, 20.0)], &[1.0]).is_err()); assert!(imp::blend(&b, "fillet", Kind::Round, &[], &[]).is_err()); } + + /// A smooth edge (a round's seam with the face it runs into) has nothing to round: refused + /// before SMLib, saying so. An edge that runs on tangentially into one left out is SMLib's to + /// end: where it cannot (the end face's top edge into the round's end arc) the refusal says + /// why, and rounded with its tangent chain the edge builds; where it can (a vertical edge run + /// on up a top round's end arc into the corner, ladder 07-fillets/018) it builds. + #[test] + fn smooth_edges_and_unfinished_tangent_chains_are_refused_saying_why() { + let b = cube(); + let rounded = fillet(&b, &[Vec3::new(10.0, 20.0, 20.0)], 3.0).unwrap(); + // the seam where the r3 round meets the top, 3 in from the old edge + let seam = imp::blend(&rounded, "fillet", Kind::Round, &[Vec3::new(10.0, 17.0, 20.0)], &[1.0]).unwrap_err().to_string(); + assert!(seam.contains("is smooth: its faces meet tangentially, so there is nothing to round"), "{seam}"); + // the end face's top edge runs on tangentially into the round's end arc + let top = Vec3::new(0.0, 8.0, 20.0); + let alone = imp::blend(&rounded, "fillet", Kind::Round, &[top], &[1.0]).unwrap_err().to_string(); + assert!(alone.contains("continues tangentially"), "{alone}"); + let chain = crate::tangent_chain(&rounded, &[top]).unwrap(); + assert!(chain.len() > 1, "{chain:?}"); + let whole = fillet(&rounded, &chain, 1.0).unwrap(); + assert!(volume(&whole) < volume(&rounded)); + + // r5 and r3 on two top edges at a corner, then r2 on the vertical edge under them: it + // runs on up the r5 round's end arc, and SMLib ends it there + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let b = fillet(&b, &[Vec3::new(30.0, 40.0, 20.0)], 5.0).unwrap(); + let b = fillet(&b, &[Vec3::new(60.0, 20.0, 20.0)], 3.0).unwrap(); + let vertical = Vec3::new(60.0, 40.0, 8.0); + let chain = crate::tangent_chain(&b, &[vertical]).unwrap(); + assert!(chain.len() > 1, "{chain:?}"); + let run_on = fillet(&b, &[vertical], 2.0).unwrap(); + assert!(volume(&run_on) < volume(&b)); + } } diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index c75b3ad73..2c233bfe0 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -344,9 +344,25 @@ fn coarse_tolerance(span: f64) -> f64 { (span * 0.01).clamp(1e-3, 1.0) } -/// Box diagonal of a record's vertices (0 when it has none or no finite extent). +/// Box diagonal of a record's vertices and points along its edges (0 when it has none or no +/// finite extent). The edges count: SMLib closes a sphere, a cylinder or a torus along seams, so +/// its vertices alone can be two poles or a single point (a torus came out 1 mm across, and its +/// display mesh at a hundredth of that took 214 720 triangles). Points on the edges, not their +/// control hulls: a rational edge's control points can lie far off it. fn span_of(record: &Brep) -> f64 { - let bounds: Aabb3 = record.vertices.iter().map(|v| v3(v.point)).collect(); + let mut bounds: Aabb3 = record.vertices.iter().map(|v| v3(v.point)).collect(); + for e in &record.edges { + if let Ok(c) = brep::eval::CurveEval::new(e.parameters()) { + let [t0, t1] = e.interval; + for i in 1..4 { + if let Some(p) = c.point(t0 + (t1 - t0) * f64::from(i) / 4.0) + && p.is_finite() + { + bounds.add(p); + } + } + } + } let d = if bounds.is_empty() { 0.0 } else { bounds.diagonal() }; if d.is_finite() && d > 0.0 { d } else { 0.0 } } @@ -426,7 +442,7 @@ impl Refusal { } impl SurfaceKind { - fn of(surface: &solidcraft_geom::brep::Surface) -> SurfaceKind { + pub(crate) fn of(surface: &solidcraft_geom::brep::Surface) -> SurfaceKind { use solidcraft_geom::brep::Surface as S; match surface { S::Plane { .. } | S::PlaneThrough { .. } => SurfaceKind::Plane, @@ -1182,6 +1198,13 @@ impl Body { .collect()) } + /// How far [`Body::planar_edges`] lets a piece it reads as a line or an arc lie from the + /// edge's curve (a NURBS within this of a circle is that arc), so how far a piece's ends may + /// lie from the edge's vertices. + pub fn planar_edges_tolerance(&self) -> f64 { + (self.size() * 1e-7).max(1e-9) * 10.0 + } + /// Edges `indices` (record edge indices) in `plane`'s coordinates, exactly: lines, circular /// arcs, and free-form curves as the Bézier spans they are, for a sketch to project them. /// `None` for an edge that doesn't lie in a plane parallel to `plane`, isn't read exactly or @@ -1190,7 +1213,7 @@ impl Body { if self.is_mesh() { return vec![None; indices.len()]; } - let tol = (self.size() * 1e-7).max(1e-9) * 10.0; + let tol = self.planar_edges_tolerance(); indices .iter() .map(|i| { diff --git a/crates/kernel/src/boolean_history_tests.rs b/crates/kernel/src/boolean_history_tests.rs index 2e0956236..852564a14 100644 --- a/crates/kernel/src/boolean_history_tests.rs +++ b/crates/kernel/src/boolean_history_tests.rs @@ -188,15 +188,16 @@ fn faces_of(h: &History) -> Vec<(Change, Vec)> { } /// A boolean with a sphere (no prism, no coincident faces): a box with a corner taken -/// off by a sphere. The three faces at the corner get a notch, the sphere's patches inside the -/// box bound it, meeting the box's faces along new edges. +/// off by a sphere. The three faces at the corner get a notch, the sphere's one face (SMLib's +/// sphere is one periodic face) bounds it inside the box, meeting each notched face along a new +/// edge. #[test] fn box_minus_sphere() { let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); let b = crate::sphere(Vec3::new(10.0, 10.0, 10.0), 4.0).unwrap(); let r = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&a, &b], 0.02); - assert_eq!(changes(h), [3, 6, 0, 0, 0], "{}", show(h)); + assert_eq!(changes(h), [3, 4, 0, 0, 0], "{}", show(h)); let from_b: BTreeSet = h .faces .iter() @@ -206,9 +207,9 @@ fn box_minus_sphere() { _ => None, }) .collect(); - assert_eq!(from_b.len(), 3); - // Each notched box face meets two of the sphere's patches. - assert_eq!(meets(h).len(), 6, "{}", show(h)); + assert_eq!(from_b.len(), 1); + // Each notched box face meets the sphere. + assert_eq!(meets(h).len(), 3, "{}", show(h)); assert!(meets(h).iter().all(|(x, y)| matches!((x, y), (FaceOrigin::Face { operand: 0, .. }, FaceOrigin::Face { operand: 1, .. })))); } @@ -231,9 +232,10 @@ fn box_union_box_prism() { }) .collect(); origins.sort(); - // All of a's faces, and b's but the end inside a. + // All of a's faces, and b's but the end inside a (its face at x = 5). let mut want: Vec = (0..6).map(|i| face(0, i)).chain((0..6).map(|i| face(1, i))).collect(); - let inside = face(1, 4); + let inside = + face(1, b.faces(1e-3).unwrap().iter().position(|f| (f.centroid.x - 5.0).abs() < 1e-6 && f.plane_normal.is_some_and(|n| n.x < -0.9)).unwrap()); want.retain(|o| *o != inside); assert_eq!(origins, want, "{}", show(h)); // b's four sides meet a's face at x = 10. @@ -243,22 +245,22 @@ fn box_union_box_prism() { assert!(h.edges.iter().all(|e| e.origins.len() == 1)); } -/// A through hole: the box's sides are kept, top and bottom get the hole, the cylinder's two -/// half walls line it, meeting top and bottom along its rims, and meet each other along the -/// cylinder's own seams. +/// A through hole: the box's sides are kept, top and bottom get the hole, the cylinder's wall +/// (one periodic face) lines it, meeting top and bottom along its rims, and closes on itself +/// along the cylinder's own seam. #[test] fn box_minus_cylinder_prism() { let a = boxed(0.0, 0.0, 0.0, 10.0, 10.0, 10.0); let b = crate::cylinder(Vec3::new(5.0, 5.0, -1.0), Vec3::Z, 2.0, 12.0).unwrap(); let r = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&a, &b], 0.01); - assert_eq!(changes(h), [4, 4, 0, 0, 0], "{}", show(h)); - let walls = from(h, face(1, 1)).len() + from(h, face(1, 2)).len(); - assert_eq!(walls, 2, "{}", show(h)); - // Rims: each wall meets top and bottom. - assert_eq!(meets(h).len(), 4, "{}", show(h)); + assert_eq!(changes(h), [4, 3, 0, 0, 0], "{}", show(h)); + let side = (0..b.face_count()).find(|i| b.planar_face(*i).is_none()).unwrap(); + assert_eq!(from(h, face(1, side)).len(), 1, "{}", show(h)); + // Rims: the wall meets top and bottom. + assert_eq!(meets(h).len(), 2, "{}", show(h)); let seams = h.edges.iter().filter(|e| matches!(e.origins.as_slice(), [EdgeOrigin::Edge { operand: 1, .. }])).count(); - assert_eq!(seams, 2); + assert_eq!(seams, 1); // Every other edge is one of the box's twelve. let boxed_edges: BTreeSet<_> = h.edges.iter().flat_map(|e| &e.origins).filter(|o| matches!(o, EdgeOrigin::Edge { operand: 0, .. })).collect(); assert_eq!(boxed_edges.len(), 12); @@ -320,9 +322,9 @@ fn a_cut_of_two_pieces_composes_the_pieces() { let b = crate::sphere(Vec3::new(15.0, 5.0, 10.0), 7.0).unwrap(); let r = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&a, &b], 0.02); - // Both pieces are bitten: the sphere's patches inside each line its bite. - let bites: BTreeSet<_> = h.faces.iter().flat_map(|f| &f.origins).filter(|o| matches!(o, FaceOrigin::Face { operand: 1, .. })).collect(); - assert!(bites.len() >= 2, "{}", show(h)); + // Both pieces are bitten: a piece of the sphere's face lines each bite. + let bites = h.faces.iter().filter(|f| matches!(f.origins.as_slice(), [FaceOrigin::Face { operand: 1, .. }])).count(); + assert!(bites >= 2, "{}", show(h)); let targets: BTreeSet<_> = h.faces.iter().flat_map(|f| &f.origins).filter(|o| matches!(o, FaceOrigin::Face { operand: 0, .. })).collect(); assert_eq!(targets.len(), 12); } @@ -341,10 +343,10 @@ fn faceted_tool() { assert_eq!(h.faces.iter().filter(|f| matches!(f.origins.first(), Some(FaceOrigin::Face { operand: 1, .. }))).count(), 3); } -/// A partial-depth cut of stepped prisms: walls over one segment through successive slabs are -/// sewn as one face (coalesced), which comes from the operand walls under it in every slab. +/// A partial-depth cut of a prism by a narrower one: the stock's walls run whole from 0 to 20, +/// one face each past the cutter's floor, untouched (Kept). #[test] -fn coalesced_stepped_walls() { +fn stepped_cut_keeps_the_stock_walls_whole() { use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; for curved in [true, false] { let (outer, inner) = if curved { @@ -357,20 +359,19 @@ fn coalesced_stepped_walls() { let cutter = crate::extrude(&Plane::XY, &[Region2 { outer: inner, holes: vec![] }], 2.0, 22.0).unwrap().pop().unwrap(); let r = boolean(&stock, &cutter, BoolOp::Cut).unwrap().unwrap(); let h = verified(&r, &[&stock, &cutter], 0.01); - // The stock's walls run whole from 0 to 20, one face each, past the cutter's floor. - let walls: Vec = (0..r.face_count()).filter(|i| r.face_was_coalesced(*i)).collect(); - assert_eq!(walls.len(), if curved { 2 } else { 4 }, "{}", show(h)); + let walls: Vec = + stock.faces(1e-3).unwrap().iter().enumerate().filter(|(_, f)| f.plane_normal.is_none_or(|n| n.z.abs() < 0.5)).map(|(i, _)| i).collect(); + assert_eq!(walls.len(), if curved { 1 } else { 4 }); for i in walls { - assert!(matches!(h.faces[i].origins.as_slice(), [FaceOrigin::Face { operand: 0, .. }]), "{}", show(h)); - assert_eq!(h.faces[i].change, Change::Modified, "{}", show(h)); + let pieces = from(h, face(0, i)); + assert_eq!(pieces.len(), 1, "{}", show(h)); + assert_eq!(h.faces[pieces[0]].change, Change::Kept, "{}", show(h)); } } } -/// A step cut into a box: the stepped prism path sews the box's face 3 in pieces at the -/// slab stations, and the joining of generated walls on their common supports makes it one face -/// again; the joined body keeps the sewn body's history composed through the join. A certified -/// box (whose planar regularization would join the same pieces) gets the same history. +/// A step cut into a box: the box's top (z = 7.5) loses the step's corner, one face still +/// (Modified). A certified box gets the same history as a plain one. #[test] fn regularized_step_cut() { let (pa, pb) = (boxed(0.0, 0.0, 0.0, 30.0, 35.0, 7.5), boxed(0.0, 30.0, 2.5, 22.5, 50.0, 25.0)); @@ -379,9 +380,10 @@ fn regularized_step_cut() { let h = verified(&r, &[&a, &b], 0.01); let plain = boolean(&pa, &pb, BoolOp::Cut).unwrap().unwrap(); let ph = verified(&plain, &[&pa, &pb], 0.01); - let joined = from(ph, face(0, 3)); + let top = pa.faces(1e-3).unwrap().iter().position(|f| (f.centroid.z - 7.5).abs() < 1e-9).unwrap(); + let joined = from(ph, face(0, top)); assert_eq!(joined.len(), 1, "{}", show(ph)); - assert_eq!(faces_of(ph)[joined[0]], (Change::Modified, vec![face(0, 3)])); + assert_eq!(faces_of(ph)[joined[0]], (Change::Modified, vec![face(0, top)])); assert_eq!(faces_of(h), faces_of(ph), "{}", show(h)); } diff --git a/crates/kernel/src/bridge.rs b/crates/kernel/src/bridge.rs index f76860cb3..9af6ee4ff 100644 --- a/crates/kernel/src/bridge.rs +++ b/crates/kernel/src/bridge.rs @@ -490,8 +490,9 @@ impl Support { let d3 = (f0 * -5.0 + f1 * 18.0 + f2 * -24.0 + f3 * 14.0 + f4 * -3.0) * (1.0 / (2.0 * h * h * h)); (d1, d2, d3) } else { - let d1 = (f0 * -1.0 + f1 * 8.0 + f3 * -8.0 + f4) * (1.0 / (12.0 * h)); - let d2 = (f0 + f1 * -16.0 + f2 * 30.0 + f3 * -16.0 + f4) * (1.0 / (12.0 * h * h)); + // Five-point central differences at the middle sample f2. + let d1 = (f0 + f1 * -8.0 + f3 * 8.0 + f4 * -1.0) * (1.0 / (12.0 * h)); + let d2 = (f0 * -1.0 + f1 * 16.0 + f2 * -30.0 + f3 * 16.0 + f4 * -1.0) * (1.0 / (12.0 * h * h)); let d3 = (f0 * -1.0 + f1 * 2.0 + f3 * -2.0 + f4) * (1.0 / (2.0 * h * h * h)); (d1, d2, d3) }; diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index be6512194..7b65f1d86 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -799,24 +799,61 @@ pub fn extrude_tapered_between( smlib_tapered(plane, region, from, to, foot, dir_sign.signum(), taper, corner) } -/// [`extrude_tapered_between`] through SMLib's draft extrusion: one loop (SMLib's takes no -/// holes), its section at `from` the profile offset by the taper, after any straight foot. +/// [`extrude_tapered_between`] through SMLib's draft extrusion, its section at `from` the +/// profile offset by the taper, after any straight foot. SMLib's draft extrusion takes one loop: +/// a region with holes is its outer loop drafted, less each hole drafted the other way (every +/// wall leaning by the taper on the material's side), refused only where the taper would make a +/// hole meet the outer wall or another hole within the extrusion. #[allow(clippy::too_many_arguments)] fn smlib_tapered(plane: &Plane, region: &Region2, from: f64, to: f64, foot: f64, sign: f64, taper: f64, corner: DraftCorner) -> Result { - if !region.holes.is_empty() { - return Err(crate::smlib_sweeps::refuse("draft extrusion of a profile with holes (SMLib's takes one loop)")); - } - let outer = oriented(region)?.map_loops(|l| l.merged_lines(continues_straight)).outer; - let bottom = if from == 0.0 || taper == 0.0 { - outer - } else { - let moved = offset_loop(&outer.lp, from * taper.tan())?; - let segs: Option> = moved.into_iter().collect(); + let joined = oriented(region)?.map_loops(|l| l.merged_lines(continues_straight)); + // A loop's section `at` along the extrusion: counter-clockwise, grown by `taper` (a hole's + // the other way, as the wall of the material round it leans). + let section = |l: &NumberedLoop, at: f64, taper: f64| -> Result { + let ccw = l.oriented(false); + if at == 0.0 || taper == 0.0 { + return Ok(ccw); + } + let segs: Option> = offset_loop(&ccw.lp, at * taper.tan())?.into_iter().collect(); let segs = segs.ok_or_else(|| crate::smlib_sweeps::refuse("draft extrusion that starts before its profile where the taper closes a side"))?; - NumberedLoop { lp: Loop2 { segs }, from: outer.from } + Ok(NumberedLoop { lp: Loop2 { segs }, from: ccw.from }) }; + let outer = section(&joined.outer, from, taper)?; let draft = (taper != 0.0).then_some(crate::smlib_sweeps::Draft { taper, foot, corner }); - crate::smlib_sweeps::extrude(plane, &crate::smlib_sweeps::pieces([&bottom]), Some(region), from * sign, to - from, sign, draft) + if joined.holes.is_empty() { + return crate::smlib_sweeps::extrude(plane, &crate::smlib_sweeps::pieces([&outer]), Some(region), from * sign, to - from, sign, draft); + } + let Some(draft) = draft else { + return Err(KernelError::Invalid("a tapered extrusion needs a taper".into())); + }; + let holes: Vec = joined.holes.iter().map(|h| section(h, from, -taper)).collect::>()?; + // The sections where the walls are farthest moved, the two ends: each hole stays inside the + // outer loop and clear of the other holes there (the walls are planes, cones and their like, + // which move monotonically in between). + for at in [from, to] { + let o = section(&joined.outer, at, taper)?; + let hs: Vec = joined.holes.iter().map(|h| section(h, at, -taper)).collect::>()?; + let pts = |l: &NumberedLoop| l.lp.segs.iter().flat_map(|s| s.polyline(1e-3)).collect::>(); + // Apart: no point of either inside the other. + let apart = |a: &NumberedLoop, b: &NumberedLoop| !pts(a).iter().any(|p| b.lp.contains(*p)) && !pts(b).iter().any(|p| a.lp.contains(*p)); + for (i, h) in hs.iter().enumerate() { + let inside = pts(h).iter().all(|p| o.lp.contains(*p)) && !pts(&o).iter().any(|p| h.lp.contains(*p)); + if !inside || hs.iter().skip(i + 1).any(|k| !apart(h, k)) { + return Err(KernelError::Invalid("the draft makes a hole meet the outer wall or another hole".into())); + } + } + } + let all: Vec = std::iter::once(outer.clone()).chain(holes.iter().map(|h| h.oriented(true))).collect(); + crate::smlib_sweeps::extrude_drafted_with_holes( + plane, + &crate::smlib_sweeps::pieces([&outer]), + &holes.iter().map(|h| crate::smlib_sweeps::pieces([h])).collect::>(), + &crate::smlib_sweeps::pieces(all.iter()), + from * sign, + to - from, + sign, + draft, + ) } /// A planar region on `plane` as the schema 4 record of one face (an open sheet): the plane's diff --git a/crates/kernel/src/chamfer_sides_curved_tests.rs b/crates/kernel/src/chamfer_sides_curved_tests.rs index 915901a13..07b834010 100644 --- a/crates/kernel/src/chamfer_sides_curved_tests.rs +++ b/crates/kernel/src/chamfer_sides_curved_tests.rs @@ -214,7 +214,7 @@ fn too_large_or_unsupported_is_refused() { .record() .edges .iter() - .filter_map(|e| solidcraft_geom::brep::eval::CurveEval::new(&e.curve).ok()?.point(0.5 * (e.interval[0] + e.interval[1]))) + .filter_map(|e| solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).ok()?.point(0.5 * (e.interval[0] + e.interval[1]))) .find(|m| (m.z - 10.0).abs() < 1e-6) .unwrap(); match chamfer_sides(&t, &[rim], 1.0, ChamferSide::Distance(2.0), false) { diff --git a/crates/kernel/src/continuity_order.rs b/crates/kernel/src/continuity_order.rs index 2e93d27ea..98318cdee 100644 --- a/crates/kernel/src/continuity_order.rs +++ b/crates/kernel/src/continuity_order.rs @@ -132,9 +132,8 @@ impl Continuity { /// What builds geometry to a continuity order, and the orders each one builds today. /// /// HAND-OFF POINT: this table is the only place that says how far a construction goes. When a -/// construction learns a higher order, raise its `highest` in [`Construction::orders`] (for the -/// patch, from the fill's own `supported_orders` once it has one); every command, dialog and -/// kernel entry point reads it from here, so nothing else changes. +/// construction learns a higher order, raise its `highest` in [`Construction::orders`]; every +/// command, dialog and kernel entry point reads it from here, so nothing else changes. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Construction { /// A patch filling a loop of edges (`surface.patch`). @@ -154,7 +153,7 @@ impl Construction { /// The lowest and the highest order this construction builds. pub fn orders(self) -> (Continuity, Continuity) { match self { - Construction::Patch => (Continuity::G0, Continuity::G2), + Construction::Patch => (Continuity::G0, Continuity::G4), Construction::Bridge => (Continuity::G0, Continuity::G3), Construction::Network => (Continuity::G0, Continuity::G2), Construction::Match => (Continuity::G1, Construction::Bridge.orders().1), @@ -224,14 +223,15 @@ mod tests { fn a_construction_refuses_what_it_does_not_build_and_names_what_it_does() { assert_eq!(Continuity::words(Continuity::G0, Continuity::G2), "g0, g1 or g2"); assert_eq!(Continuity::words(Continuity::G4, Continuity::G4), "g4"); - assert_eq!(Continuity::G2.built_by(Construction::Patch).unwrap(), Continuity::G2); - let e = Continuity::G3.built_by(Construction::Patch).unwrap_err().to_string(); + assert_eq!(Continuity::G4.built_by(Construction::Patch).unwrap(), Continuity::G4); + let e = Continuity::G3.built_by(Construction::Network).unwrap_err().to_string(); assert!(e.contains("not supported yet") && e.contains("g0, g1 or g2") && e.contains("g3"), "{e}"); let e = Continuity::G0.built_by(Construction::Match).unwrap_err().to_string(); assert!(e.contains("g1, g2 or g3"), "{e}"); assert!(Continuity::G4.built_by(Construction::Bridge).is_err()); assert!(Continuity::G4.built_by(Construction::BlendCurve).is_ok()); - assert_eq!(Construction::Patch.offered(), vec![Continuity::G0, Continuity::G1, Continuity::G2]); + assert_eq!(Construction::Patch.offered(), Continuity::ALL.to_vec()); + assert_eq!(Construction::Network.offered(), vec![Continuity::G0, Continuity::G1, Continuity::G2]); assert_eq!(Construction::BlendCurve.offered().first(), Some(&Continuity::G1)); } } diff --git a/crates/kernel/src/curvecorner_tests.rs b/crates/kernel/src/curvecorner_tests.rs index af199c53c..db182389f 100644 --- a/crates/kernel/src/curvecorner_tests.rs +++ b/crates/kernel/src/curvecorner_tests.rs @@ -251,16 +251,25 @@ fn the_arc_rounded_after_the_back_edge_matches_both_together() { one_then_the_other(BACK, arc_top()); } -/// The edge at `first` rounded (2), then the one at `then` as a fillet of its own, against both -/// rounded together. +/// The edge at `first` rounded (2), then the one at `then` as a fillet of its own, each with its +/// tangent chain as the Fillet feature rounds by default (tangent propagation), against the same +/// edges of the part rounded together: the picks' chains, and every edge of the part that the +/// second round's chain carried on into across the first round (the left front upright, after +/// the front edge's round: the left top edge runs on round that round's end arc and down the +/// upright, a sphere octant at the corner where the three rounds meet). fn one_then_the_other(first: Vec3, then: Vec3) { let body = arc_part(); - let step = crate::fillet(&body, &[first], 2.0).unwrap(); - let after = crate::fillet(&step, &[then], 2.0).unwrap(); + let chained = |b: &Body, pts: &[Vec3]| crate::tangent_chain(b, pts).unwrap(); + let step = crate::fillet(&body, &chained(&body, &[first]), 2.0).unwrap_or_else(|e| panic!("{first:?}: {e}")); + let second = chained(&step, &[then]); + let after = crate::fillet(&step, &second, 2.0).unwrap_or_else(|e| panic!("{first:?} then {then:?}: {e}")); let v = volume(&after); - let together = volume(&crate::fillet(&body, &[first, then], 2.0).unwrap()); + // The part's own edges among the second chain's (points on an edge of the part). + let mut picks = vec![first, then]; + picks.extend(second.iter().skip(1).filter(|p| crate::tangent_chain(&body, &[**p]).is_ok())); + let together = volume(&crate::fillet(&body, &chained(&body, &picks), 2.0).unwrap()); // Within the display meshes' accuracy (two different B-reps, meshed apart). - assert!((v - together).abs() < 5e-3, "{first:?} then {then:?}: {v} vs together {together}"); + assert!((v - together).abs() < 5e-3, "{first:?} then {then:?}: {v} vs together {together} ({picks:?})"); } /// Edges rounded together come out the same in any order: a round made first doesn't carry the diff --git a/crates/kernel/src/display_mesh_tests.rs b/crates/kernel/src/display_mesh_tests.rs index 8da23163d..e34b8ba35 100644 --- a/crates/kernel/src/display_mesh_tests.rs +++ b/crates/kernel/src/display_mesh_tests.rs @@ -378,7 +378,8 @@ fn a_cylinder_wall_split_along_its_seam_meshes_round() { let outer: Vec = (0..cup.face_count()) .map(|i| matches!(face_surface(&cup, i), Some(FaceSurface::Cylinder { radius, .. }) if (radius - 50.0).abs() < 1e-6)) .collect(); - assert_eq!(outer.iter().filter(|o| **o).count(), 2); + // One periodic face (SMLib sweeps the one circle segment once), its seam split at z = 2. + assert_eq!(outer.iter().filter(|o| **o).count(), 1); for tol in [display_tol(&cup), 0.1, 0.01] { let m = cup.mesh(&crate::MeshTolerance::chord(tol)).unwrap(); assert_eq!(open_sides(&m, 1e-6), 0); diff --git a/crates/kernel/src/emboss.rs b/crates/kernel/src/emboss.rs index e4b200f36..be32fce8b 100644 --- a/crates/kernel/src/emboss.rs +++ b/crates/kernel/src/emboss.rs @@ -9,7 +9,7 @@ use crate::numbered::NumberedRegion; use crate::offset::{Surf, face_edges, surf_of}; use crate::{KernelError, Result, guard}; use solidcraft_geom::brep::eval::CurveEval; -use solidcraft_geom::brep::{Brep, Curve, Frame, Loop, Surface}; +use solidcraft_geom::brep::{Brep, Curve, Frame, Loop, Surface, form}; use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; fn fail(s: &str) -> KernelError { @@ -40,10 +40,11 @@ fn wall_angles(b: &Brep, face: usize, o: Vec3, axis: Vec3, radial: Vec3, tangent if z.dot(axis).abs() < 1.0 - 1e-9 { continue; } - // The circle's parameter is its angle: the wall spans the edge's interval about the - // angle of its middle (a whole turn, from the seam, for a wall in one piece). - let c = CurveEval::new(e.parameters()).ok()?; - let [t0, t1] = e.interval; + // The circle's parameter is its angle: the wall spans the edge's angles on the circle + // (`interval` is on its NURBS form where it has one) about the angle of its middle (a + // whole turn, from the seam, for a wall in one piece). + let c = CurveEval::new(&e.curve).ok()?; + let [t0, t1] = e.curve_interval()?; let am = angle(c.point(0.5 * (t0 + t1))?, o, axis, radial, tangent); let half = 0.5 * (t1 - t0); return Some((am - half, am + half)); @@ -327,9 +328,12 @@ fn emboss_impl(body: &Body, anchor: Option, plane: &Plane, regions: &[Regi let at = o + axis * p.y + (radial * (p.x / r).cos() + tangent * (p.x / r).sin()) * r; return Ok(EmbossOutcome::Anchor(fi, at)); } - let wall = Wrap { o, axis, radial, tangent, r }; let mut asm = Assembly::from_record(&rec)?; let selected = asm.faces.get_mut(fi).and_then(Option::take).ok_or_else(|| fail("face"))?; + // The footprint's arcs lie on the wall face and are labelled on its frame, so their NURBS + // forms run on the face's own quarter grid and their pcurves there are exact. + let label = form::frame_of(&selected.surface); + let wall = Wrap { o, axis, radial, tangent, r, label, tol }; // The wall's pieces left around the footprints: the face itself, then one per profile // hole (the original radius inside it). let mut base_patches: Vec>> = vec![selected.loops.clone()]; @@ -416,6 +420,9 @@ struct Wrap { radial: Vec3, tangent: Vec3, r: f64, + /// The wall face's own frame, which the arcs at its radius are labelled on. + label: Option, + tol: f64, } impl Wrap { @@ -441,7 +448,12 @@ impl Wrap { let (ta, tb) = (p.x / self.r, q.x / self.r); let forward = ta < tb; let (interval, ends) = if forward { ([ta, tb], (a, b)) } else { ([tb, ta], (b, a)) }; - Ok(AUse { edge: asm.edge(Curve::Circle { frame, radius }, interval, ends.0, ends.1)?, forward, given: None }) + let circle = Curve::Circle { frame, radius }; + let (circle, interval) = match &self.label { + Some(label) if (radius - self.r).abs() <= self.tol => form::on_frame(&circle, interval, label, self.tol).unwrap_or((circle, interval)), + _ => (circle, interval), + }; + Ok(AUse { edge: asm.edge(circle, interval, ends.0, ends.1)?, forward, given: None }) } /// A profile loop wrapped onto the wall: its footprint at the wall's radius and its cap's diff --git a/crates/kernel/src/face_source_tests.rs b/crates/kernel/src/face_source_tests.rs index 6b52e8033..a612a97c4 100644 --- a/crates/kernel/src/face_source_tests.rs +++ b/crates/kernel/src/face_source_tests.rs @@ -27,6 +27,12 @@ fn box_certificates_are_six_construction_roles_with_dimension_stable_axes() { (Vec3::new(2., 3., 4.), Vec3::new(12., 23., 34.)), (Vec3::new(12., 23., 34.), Vec3::new(2., 3., 4.)), (Vec3::new(2., -8., 4.), Vec3::new(22., 43., 54.)), + // A side far shorter than the body (a 0.3 mm label of a metre): its walls' edges lie + // closer together than the sweep's body-sized nearness, and each keeps its own role. + (Vec3::new(500., -0.3, 1400.), Vec3::new(1500., 0., 1800.)), + // Far thinner than the body's flatness tolerance (0.1 µm in 14 mm): each cap is in its + // own plane only. + (Vec3::ZERO, Vec3::new(10., 10., 1e-4)), ] { let body = crate::box_solid(a, b).unwrap().with_box_certificate(42).unwrap(); let mut roles = std::collections::HashSet::new(); @@ -94,7 +100,14 @@ fn construction_planes_follow_reflected_and_sheared_affine_images() { [[-1., 0., 0., 0.], [0.4, 2., 0., 0.], [0., 0.3, 1., 0.], [8., 9., 10., 1.]], ] { let placed = transform_matrix(&body, m).unwrap(); - for (original, transformed) in body.face_sources().unwrap().iter().zip(placed.face_sources().unwrap()) { + // SMLib numbers the placed faces afresh: each is matched with the face its history names. + let history = placed.history().unwrap(); + let originals = body.face_sources().unwrap(); + for (f, transformed) in placed.face_sources().unwrap().iter().enumerate() { + let [crate::history::FaceOrigin::Face { operand: 0, face }] = history.faces[f].origins.as_slice() else { + panic!("face {f} has no one origin") + }; + let original = &originals[*face]; let ( Some(FaceSource::Box { producer: a, axis: aa, high: ah, plane: ap }), Some(FaceSource::Box { producer: b, axis: ba, high: bh, plane: bp }), @@ -259,7 +272,7 @@ fn constructed_annulus_sides_follow_exact_source_edges() { } assert!(vertices > 0); } - assert_eq!((outer, inner), (2, 2), "full circles split into two actual edges each"); + assert_eq!((outer, inner), (1, 1), "each full circle sweeps one side face"); assert_eq!(sources.iter().filter(|source| matches!(source, Some(FaceSource::ExtrudeCap { .. }))).count(), 2); } } @@ -298,7 +311,7 @@ fn constructed_large_arc_split_and_reversal_preserve_one_source_segment() { _ => None, }) .collect(); - assert_eq!(arcs.len(), 2, "large input arc explicitly creates two actual boundary edges"); + assert_eq!(arcs.len(), 1, "the large input arc sweeps one side face"); assert!(arcs.iter().all(|(radius, sweep)| (**radius - 10.).abs() < 1e-12 && (sweep.abs() - std::f64::consts::PI * 5. / 3.).abs() < 1e-12)); assert_eq!(sources.iter().filter(|source| matches!(source, Some(FaceSource::ExtrudeSide { segment: Seg2::Line { .. }, .. }))).count(), 1); let mesh = body.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(); diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rs index e009123e5..592693acb 100644 --- a/crates/kernel/src/fair.rs +++ b/crates/kernel/src/fair.rs @@ -1379,6 +1379,7 @@ mod tests { let vertices: Vec<[f64; 3]> = corners.iter().map(|&(i, j)| net[j * cu + i]).collect(); let edges = (0..4) .map(|k| PartEdge { + nurbs: None, curve: b::Curve::Line { start: vertices[k], end: vertices[(k + 1) % 4] }, interval: [0.0, 1.0], vertices: [k as u32, ((k + 1) % 4) as u32], diff --git a/crates/kernel/src/fill.rs b/crates/kernel/src/fill.rs index 33f650cfc..003061f28 100644 --- a/crates/kernel/src/fill.rs +++ b/crates/kernel/src/fill.rs @@ -5,11 +5,14 @@ //! parameters are plane coordinates, so each edge's pcurve is its exact projection onto the //! plane. //! -//! The general fill, which also meets the faces beside the loop with G1 or G2, passes through +//! The general fill, which also meets the faces beside the loop with G1 … G4, passes through //! given points, and fills loops that bound no height field, is a patch whose boundary rows are //! the loop's own edges (`solidcraft_geom::fill_iso`): each edge's pcurve is a straight line in -//! (u, v). It takes loops of three or four line or spline edges; the frames across each edge are -//! read off the neighbouring face's record surface (exact second derivatives for G2). +//! (u, v), affine in the edge's own parameter. It takes loops of three to sixteen line, spline or +//! rational edges (a circle's arc on the NURBS form SMLib holds it as); the frames across each +//! edge are read off the neighbouring face's record surface, with its exact derivatives to the +//! order asked: the neighbour as a height over its tangent plane to that order +//! (`solidcraft_geom::linkage`). use solidcraft_geom::Vec3; use solidcraft_geom::brep::eval::SurfaceEval; @@ -25,7 +28,7 @@ use crate::history::{Change, EdgeOrigin, EdgeProv, FaceProv, History}; use crate::sew::{PartEdge, PartFace, PartUse, Parts, assemble}; use crate::{KernelError, Result}; -/// How far (degrees) a G1 or G2 patch's normal may turn from its neighbour's along the loop. +/// How far (degrees) a G1 … G4 patch's normal may turn from its neighbour's along the loop. pub const PATCH_ANGLE_TOL_DEG: f64 = 0.05; /// A spline error as the patch reports it. @@ -39,7 +42,7 @@ fn spline_error(e: SplineError) -> KernelError { /// What a patch on a loop of edges must do besides filling it. #[derive(Clone, Debug, PartialEq)] pub struct PatchSpec { - /// How every edge's neighbour is met (G0, G1 or G2). + /// How every edge's neighbour is met (G0 … G4). pub continuity: Continuity, /// Edges met otherwise: a point on the edge and its continuity. pub edges: Vec<(Vec3, Continuity)>, @@ -77,9 +80,14 @@ pub struct PatchReport { /// corners where the neighbours themselves disagree, and anywhere. pub normal_deviation_deg: f64, pub normal_deviation_all_deg: f64, - /// The largest difference (1/mm) between the patch's normal curvature across a G2 edge and - /// the neighbour's. - pub curvature_mismatch: f64, + /// The largest angle (degrees) by which the patch's normal misses a neighbour's beyond the + /// loop edge's own lean out of that neighbour's tangent plane (what the tolerance holds). + pub normal_excess_deg: f64, + /// `jumps[k]`, k = 2 … 4: the largest jump across the edges asked for order k or more, clear + /// of the loop's corners, of the k-th derivative of the linkage curves' height above the + /// neighbour (1/mmᵏ⁻¹): the normal curvature (k = 2), its rate of change + /// (3) and that rate's (4) (`solidcraft_geom::fill_iso::Achieved::jumps`). + pub jumps: [f64; solidcraft_geom::linkage::MAX_CONTINUITY + 1], /// The farthest point from the surface. pub point_gap: f64, } @@ -100,10 +108,6 @@ pub fn patch_edges_report(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result< if !(solidcraft_geom::fill::MIN_CROWN..=solidcraft_geom::fill::MAX_CROWN).contains(&spec.crown) { return Err(KernelError::Invalid("a patch's crown must be between -0.9 and 3".into())); } - let g3 = |g: Continuity| g == Continuity::G3; - if g3(spec.continuity) || spec.edges.iter().any(|(_, g)| g3(*g)) { - return Err(KernelError::Invalid("not supported yet: a patch meets its neighbours with g0, g1 or g2".into())); - } if spec.edges.len() > 10_000 || spec.edges.iter().any(|(p, _)| !p.is_finite()) { return Err(KernelError::Invalid("pick at most 10000 edges, each by a finite point, for their continuity".into())); } @@ -125,7 +129,7 @@ pub fn patch_edges_report(body: &Body, at: &[Vec3], spec: &PatchSpec) -> Result< } } if spec.crown != 0.0 && orders.iter().all(|g| *g == Continuity::G0) { - return Err(KernelError::Invalid("not supported yet: a crown on a patch through points with no g1 or g2 edge".into())); + return Err(KernelError::Invalid("not supported yet: a crown on a patch through points with no g1 or higher edge".into())); } general_fill(body, &record, &chain, &orders, &spec.points, spec.crown) } @@ -140,30 +144,20 @@ fn general_fill( points: &[Vec3], crown: f64, ) -> Result<(Body, PatchReport)> { - if !(3..=solidcraft_geom::fill_iso::MAX_ISO_EDGES).contains(&chain.len()) { + if !(1..=solidcraft_geom::fill_iso::MAX_ISO_EDGES).contains(&chain.len()) { return Err(KernelError::Invalid(format!( - "not supported yet: a general patch on a loop of {} edges (three to {})", + "not supported yet: a general patch on a loop of {} edges (one to {})", chain.len(), solidcraft_geom::fill_iso::MAX_ISO_EDGES ))); } - let edges: Vec = chain.iter().map(|&(e, forward)| iso_edge(record, e, forward)).collect::>()?; + let pieces = loop_pieces(record, chain)?; + let edges: Vec = pieces.iter().map(|p| iso_edge(record, p)).collect::>()?; let size = body.size().max(solidcraft_geom::LINEAR_TOL); - let mut beside: Vec> = Vec::with_capacity(chain.len()); - for (&(e, forward), order) in chain.iter().zip(orders) { - beside.push(if *order == Continuity::G0 { None } else { Some(Beside::new(record, e, forward, *order == Continuity::G2, size)?) }); - } - // Where a G1/G2 edge's neighbour and the one before disagree at their corner. - let n = chain.len(); - let mut clash = vec![false; n]; - for (k, slot) in clash.iter_mut().enumerate() { - let prev = (k + n - 1) % n; - let (Some(Some(a)), Some(Some(b))) = (beside.get(prev), beside.get(k)) else { continue }; - let (Some(ea), Some(eb)) = (edges.get(prev), edges.get(k)) else { continue }; - let (end, start) = (ea.knots.last().copied().unwrap_or(0.0), eb.knots.first().copied().unwrap_or(0.0)); - if let (Some(x), Some(y)) = (a.across(record, end)?, b.across(record, start)?) { - *slot = x.normal.dot(y.normal).abs() < (2.0 * PATCH_ANGLE_TOL_DEG).to_radians().cos(); - } + let mut beside: Vec> = Vec::with_capacity(pieces.len()); + for p in &pieces { + let order = chain.iter().position(|&(e, _)| e == p.edge).and_then(|k| orders.get(k)).copied().unwrap_or(Continuity::G0); + beside.push(if order == Continuity::G0 { None } else { Some(Beside::new(record, p.edge, p.forward, order, size)?) }); } let mut across = |k: usize, ts: &[f64]| -> std::result::Result>, String> { match beside.get(k) { @@ -173,15 +167,16 @@ fn general_fill( } }; let spec = IsoSpec { tol: face_tolerance(body), angle_tol: PATCH_ANGLE_TOL_DEG.to_radians(), crown, points }; - let fill = solidcraft_geom::fill_iso::iso_fill(&edges, &mut across, &clash, &spec).map_err(spline_error)?; - let made = quilt_body(body, record, chain, &fill, face_tolerance(body))?; + let fill = solidcraft_geom::fill_iso::iso_fill(&edges, &mut across, &spec).map_err(spline_error)?; + let made = quilt_body(body, record, &pieces, &fill, face_tolerance(body))?; let a = fill.achieved; let report = PatchReport { general: true, gap: 0.0, normal_deviation_deg: a.normal_deviation.to_degrees(), normal_deviation_all_deg: a.normal_deviation_all.to_degrees(), - curvature_mismatch: a.curvature_mismatch, + normal_excess_deg: a.normal_excess.to_degrees(), + jumps: a.jumps, point_gap: a.point_deviation, }; Ok((made, report)) @@ -208,7 +203,7 @@ pub(crate) fn matched_patch(body: &Body, chain: &[(usize, bool)], curvature_tol: let mut beside = Vec::with_capacity(chain.len()); for &(e, forward) in chain { sides.push(Side::new(&record, e, forward)?); - beside.push(Beside::new(&record, e, forward, true, size)?); + beside.push(Beside::new(&record, e, forward, Continuity::G2, size)?); } // A vertex of the loop is a corner where the loop turns there: the edge arriving and the one // leaving go different ways. @@ -241,84 +236,157 @@ pub(crate) fn matched_patch(body: &Body, chain: &[(usize, bool)], curvature_tol: Ok((made, fill)) } -/// A loop edge as the patch takes it: a non-rational B-spline on the edge's interval, running -/// the loop's way, its ends on the edge's vertices. Conics and traced curves have no such form -/// in their own parameter (an arc's angle is no rational function of a NURBS parameter), and a -/// rational edge none the Coons sum can blend: refused by name. -fn iso_edge(record: &b::Brep, e: usize, forward: bool) -> Result { +/// A piece of a loop edge as the general fill takes it: record edge `edge` over `interval` (in +/// its own parameter, min < max), run the loop's way along it (`forward`) or back. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Piece { + edge: usize, + forward: bool, + interval: [f64; 2], +} + +/// The loop `chain` as the general fill's sides: each edge whole, but for a loop of one or two +/// edges (a tube's end: one closed circle) each edge in equal pieces of its parameter, four sides +/// in all, so the fill is one four-sided patch on pieces of the edges' own curves. +fn loop_pieces(record: &b::Brep, chain: &[(usize, bool)]) -> Result> { + let split = match chain.len() { + 1 => 4, + 2 => 2, + _ => 1, + }; + let mut out = Vec::with_capacity(chain.len() * split); + for &(e, forward) in chain { + let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; + let [a, z] = edge.interval; + // A break that falls on one of the curve's own knots (a conic's quarter points) is that + // knot exactly: a piece must not start a rounding error off one. + let own: Vec = match edge.parameters() { + b::Curve::Spline { knots, .. } | b::Curve::RationalSpline { knots, .. } => knots.clone(), + _ => Vec::new(), + }; + let at = |i: usize| { + if i == 0 { + a + } else if i == split { + z + } else { + let t = a + (z - a) * i as f64 / split as f64; + own.iter().copied().find(|k| (k - t).abs() <= 1e-9 * (z - a).abs()).unwrap_or(t) + } + }; + let mut pieces: Vec = (0..split).map(|i| Piece { edge: e, forward, interval: [at(i), at(i + 1)] }).collect(); + if !forward { + pieces.reverse(); + } + out.extend(pieces); + } + Ok(out) +} + +/// `t` on an edge's interval `[a, z]` reflected about its middle: the loop's parameter along an +/// edge it runs against. +fn reflected(a: f64, z: f64, t: f64) -> f64 { + if t == a { + z + } else if t == z { + a + } else { + a + z - t + } +} + +/// A loop edge as the patch takes it: a B-spline on the edge's interval, rational when the edge +/// is (a circle or ellipse on the NURBS form SMLib holds it as, whose parameter the edge's interval +/// and pcurves are in), running the loop's way, its ends on the edge's vertices. A traced curve +/// has no such form in its own parameter and is refused by name. +fn iso_edge(record: &b::Brep, piece: &Piece) -> Result { + let Piece { edge: e, forward, interval: [lo, hi] } = *piece; let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; let v3 = |p: &[f64; 3]| Vec3::new(p[0], p[1], p[2]); let [a, z] = edge.interval; - let (degree, knots, points): (usize, Vec, Vec) = match &edge.curve { + let (degree, knots, h): (usize, Vec, Vec) = match edge.parameters() { b::Curve::Line { start, end } => { let (s, t) = (v3(start), v3(end)); - (1, vec![a, a, z, z], vec![s + (t - s) * a, s + (t - s) * z]) + (1, vec![a, a, z, z], vec![HPoint::weighted(s + (t - s) * a, 1.0), HPoint::weighted(s + (t - s) * z, 1.0)]) } b::Curve::Polyline { points } => { let mut knots = vec![0.0]; knots.extend((0..points.len()).map(|i| i as f64)); knots.push(points.len().saturating_sub(1) as f64); - (1, knots, points.iter().map(v3).collect()) + (1, knots, points.iter().map(|p| HPoint::weighted(v3(p), 1.0)).collect()) } - b::Curve::Spline { knots, points } => (knots.len().saturating_sub(points.len() + 1), knots.clone(), points.iter().map(v3).collect()), - b::Curve::RationalSpline { knots, homogeneous } if homogeneous.windows(2).all(|w| w[0][3] == w[1][3]) => ( + b::Curve::Spline { knots, points } => { + (knots.len().saturating_sub(points.len() + 1), knots.clone(), points.iter().map(|p| HPoint::weighted(v3(p), 1.0)).collect()) + } + b::Curve::RationalSpline { knots, homogeneous } => ( knots.len().saturating_sub(homogeneous.len() + 1), knots.clone(), - homogeneous.iter().map(|h| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])).collect(), + homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(), ), _ => { return Err(KernelError::Invalid(format!( - "not supported yet: a general patch on edge {e}, a circle, ellipse, rational or traced curve (its pcurve on the patch has no exact form in its own parameter)" + "not supported yet: a general patch on edge {e}, a circle or ellipse with no NURBS form, or a traced curve (its pcurve on the patch has no exact form in its own parameter)" ))); } }; - // The piece on the edge's interval, then run the loop's way. - let h: Vec = points.iter().map(|p| HPoint::weighted(*p, 1.0)).collect(); - let (mut knots, h) = solidcraft_geom::bspline::segment(degree, &knots, &h, a, z).map_err(spline_error)?; - let mut points: Vec = h.iter().map(|p| p.xyz()).collect(); + // The piece of the edge, then run the loop's way (the edge's parameter reflected about its + // interval's middle). + let (mut knots, mut h) = solidcraft_geom::bspline::segment(degree, &knots, &h, lo, hi).map_err(spline_error)?; if !forward { knots = knots.iter().rev().map(|k| a + z - k).collect(); - points.reverse(); - // The interval's ends exactly (the reflection's rounding), so a piece's ends name them. + h.reverse(); + // The ends exactly (the reflection's rounding), so a piece's ends name them. + let (rlo, rhi) = (reflected(a, z, hi), reflected(a, z, lo)); let n = knots.len(); for (i, k) in knots.iter_mut().enumerate() { if i <= degree { - *k = a; + *k = rlo; } else if i + degree + 1 >= n { - *k = z; + *k = rhi; } } } - // Its ends exactly on the loop's vertices. - let vertex = |end: usize| record.vertices.get(edge.vertices[end] as usize).map(|v| v3(&v.point)); - let (first, last) = if forward { (vertex(0), vertex(1)) } else { (vertex(1), vertex(0)) }; - if let (Some(p), Some(q), Some(f)) = (first, last, points.first_mut()) { + let rational = h.iter().any(|q| q.w != 1.0); + let mut points = h + .iter() + .map(|q| q.project().filter(|_| q.w > 0.0)) + .collect::>>() + .ok_or_else(|| KernelError::Invalid(format!("not supported yet: a general patch on edge {e}, whose weights are not all positive")))?; + // Its ends exactly on the loop's vertices, where they are the edge's ends. + let vertex = |at: f64| match (at == a, at == z) { + (true, _) => record.vertices.get(edge.vertices[0] as usize).map(|v| v3(&v.point)), + (_, true) => record.vertices.get(edge.vertices[1] as usize).map(|v| v3(&v.point)), + _ => None, + }; + let (first, last) = if forward { (vertex(lo), vertex(hi)) } else { (vertex(hi), vertex(lo)) }; + if let (Some(p), Some(f)) = (first, points.first_mut()) { *f = p; - if let Some(l) = points.last_mut() { - *l = q; - } } - Ok(IsoEdge { degree, knots, points }) + if let (Some(q), Some(l)) = (last, points.last_mut()) { + *l = q; + } + let weights = rational.then(|| h.iter().map(|q| q.w).collect()); + Ok(IsoEdge { degree, knots, points, weights }) } -/// The face beside a G1/G2 edge, read at points of the edge: its record surface, which side of -/// it is outward, whether its boundary runs the edge the loop's way, and whether its curvature -/// is read (G2). +/// The face beside a G1 … G4 edge, read at points of the edge: its record surface, which side of +/// it is outward, whether its boundary runs the edge the loop's way, and how much of it is read +/// (`order`: its tangent plane for G1, and its jet to that order above). struct Beside { surface: SurfaceEval, side: f64, along: bool, edge: usize, forward: bool, - curvature: bool, + order: Continuity, reach: f64, } impl Beside { - fn new(record: &b::Brep, e: usize, forward: bool, curvature: bool, size: f64) -> Result { + fn new(record: &b::Brep, e: usize, forward: bool, order: Continuity, size: f64) -> Result { let edge = record.edges.get(e).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; let [u] = edge.uses.as_slice() else { - return Err(KernelError::Invalid("an edge of the loop lies between two faces: g1 and g2 need the one face beside it".into())); + return Err(KernelError::Invalid("an edge of the loop lies between two faces: g1 and up need the one face beside it".into())); }; let face = record.faces.get(u.face as usize).ok_or_else(|| KernelError::Failed("patch: face reference".into()))?; let surface = SurfaceEval::new(face.parameters()) @@ -345,15 +413,17 @@ impl Beside { along: runs_forward == forward, edge: e, forward, - curvature, + order, reach: (size * 1e-4).max(1e-6), }) } /// The neighbour's conditions at parameter `t` of the loop's edge (its `IsoEdge`, run the /// loop's way, whose parameter is the edge's reversed where the loop runs against it): - /// its normal, the direction it leaves the edge in, away from it, and for G2 its curvature - /// vector along that direction. `None` where the edge has no tangent there. + /// its normal, the direction it leaves the edge in, away from it, and for G2 and up its + /// curvature vector along that direction and its jet to the order asked + /// (`solidcraft_geom::linkage::surface_jet`, on the frame of the boundary and the leave + /// direction). `None` where the edge has no tangent there. fn across(&self, record: &b::Brep, t: f64) -> Result> { let edge = record.edges.get(self.edge).ok_or_else(|| KernelError::Failed("patch: edge reference".into()))?; let [a, z] = edge.interval; @@ -370,11 +440,23 @@ impl Beside { // Away from the face: its boundary's direction × its outward normal. let boundary = if self.along { tangent } else { tangent * -1.0 }; let leave = boundary.cross(normal).normalized().ok_or_else(|| KernelError::Invalid("the boundary runs along the face's normal".into()))?; - let bend = if self.curvature { Some(normal * normal_curvature(&self.surface, uv, normal, leave)?) } else { None }; - Ok(Some(Across { leave, normal, bend })) + let order = continuity_order(self.order); + if order < 2 { + return Ok(Some(Across { leave, normal, bend: None, jet: None })); + } + let bend = Some(normal * normal_curvature(&self.surface, uv, normal, leave)?); + let jet = solidcraft_geom::linkage::surface_jet(&self.surface, uv, normal, leave, order).ok_or_else(|| { + KernelError::Invalid(format!("not supported yet: g{order} to a face whose surface has no derivatives of order {order} there")) + })?; + Ok(Some(Across { leave, normal, bend, jet: Some(jet) })) } } +/// The continuity order a [`Continuity`] asks: 0 (G0) … n, the one place it is read as a number. +fn continuity_order(g: Continuity) -> usize { + g.conditions().saturating_sub(1) +} + /// The normal curvature of a surface at `uv` along the unit tangent `w`: `n·r''` of the unit-speed /// curve on it leaving that way (the second fundamental form, exact second derivatives). fn normal_curvature(s: &SurfaceEval, uv: [f64; 2], n: Vec3, w: Vec3) -> Result { @@ -695,13 +777,14 @@ fn patch_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], surface: b })?), Pcurves::Computed => None, }; - edges.push(PartEdge { curve: edge.parameters().clone(), interval: edge.interval, vertices: ends }); + edges.push(PartEdge { curve: edge.curve.clone(), nurbs: edge.nurbs.clone(), interval: edge.interval, vertices: ends }); uses.push(PartUse { edge: k as u32, forward, given }); } if !ccw { uses = uses.into_iter().rev().map(|u| PartUse { forward: !u.forward, ..u }).collect(); } - let made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: tol }, false)?; + let mut made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: tol }, false)?; + hold_gap(&mut made.brep, tol); let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::Failed(format!("patch: SMLib: {e}")))?; let (patch, order) = crate::native::body_from_smlib_ordered(&smlib)?; // The patch's edges in its own order, each from the loop edge it is. @@ -726,13 +809,13 @@ fn patch_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], surface: b /// exact curve record; the spokes from the halves' common vertex to the centre; every pcurve the /// straight line in (u, v) the patch gives its side. Its history is over `[body]`: every face is /// new, each loop edge (or half) a piece of the body's own, each spoke new. -fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &IsoFill, tol: f64) -> Result { +fn quilt_body(body: &Body, record: &b::Brep, chain: &[Piece], fill: &IsoFill, tol: f64) -> Result { use solidcraft_geom::fill_iso::IsoSide; let fail = |m: &str| KernelError::Failed(format!("patch: {m}")); let index = |n: usize| u32::try_from(n).map_err(|_| fail("budget")); let mut vertices: Vec<[f64; 3]> = Vec::new(); let mut vertex_of: std::collections::HashMap = std::collections::HashMap::new(); - let mut middle_of: std::collections::HashMap = std::collections::HashMap::new(); + let mut middle_of: std::collections::HashMap<(usize, u64), u32> = std::collections::HashMap::new(); let mut edges: Vec = Vec::new(); // Each part edge's origin: the record edge it is a piece of (`None` for a spoke). let mut origin: Vec> = Vec::new(); @@ -755,12 +838,14 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso }; match *side { IsoSide::Edge { edge: k, from, to, uv } => { - let &(e, forward) = chain.get(k).ok_or_else(|| fail("side"))?; + let &Piece { edge: e, forward, interval: [plo, phi] } = chain.get(k).ok_or_else(|| fail("side"))?; let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?; let [a, z] = edge.interval; - // The patch's parameter runs the loop's way: the edge's own, reversed where the - // loop runs against it. - let tau = |t: f64| if forward { t } else { a + z - t }; + // The patch's parameter runs the loop's way: the edge's own, reflected where the + // loop runs against it; a side's ends are its piece's ends or middle, exactly. + let near = 1e-9 * (1.0 + (z - a).abs() + a.abs().max(z.abs())); + let snap = |t: f64| [plo, phi, 0.5 * (plo + phi)].into_iter().find(|s| (s - t).abs() <= near).unwrap_or(t); + let tau = |t: f64| snap(if forward { t } else { reflected(a, z, t) }); let (tf, tt) = (tau(from), tau(to)); let (lo, hi, along) = if tf < tt { (tf, tt, true) } else { (tt, tf, false) }; let key = (e, lo.to_bits(), hi.to_bits()); @@ -779,11 +864,13 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso } id } else { - middle(&mut vertices, &mut middle_of, k, edge, t)? + middle(&mut vertices, &mut middle_of, e, edge, t)? }; } let id = index(edges.len())?; - edges.push(PartEdge { curve: edge.curve.clone(), interval: [lo, hi], vertices: ends }); + // The edge itself: the interval and the pcurve's parameter are on its + // NURBS form (a conic's), which it keeps. + edges.push(PartEdge { curve: edge.curve.clone(), nurbs: edge.nurbs.clone(), interval: [lo, hi], vertices: ends }); origin.push(Some(e)); piece_of.insert(key, id); id @@ -797,17 +884,21 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso Some(id) => *id, None => { let curve = fill.spokes.get(spoke).ok_or_else(|| fail("spoke"))?; - let &(e, _) = chain.get(spoke).ok_or_else(|| fail("spoke"))?; + let &Piece { edge: e, interval: [plo, phi], .. } = chain.get(spoke).ok_or_else(|| fail("spoke"))?; let edge = record.edges.get(e).ok_or_else(|| fail("edge reference"))?; - let start = middle(&mut vertices, &mut middle_of, spoke, edge, 0.5 * (edge.interval[0] + edge.interval[1]))?; + let start = middle(&mut vertices, &mut middle_of, e, edge, 0.5 * (plo + phi))?; let end = centre.ok_or_else(|| fail("centre"))?; let id = index(edges.len())?; - let points = curve.points.iter().map(|p| [p.x, p.y, p.z]).collect(); - edges.push(PartEdge { - curve: b::Curve::Spline { knots: curve.knots.clone(), points }, - interval: [0.0, 1.0], - vertices: [start, end], - }); + let spline = match &curve.weights { + Some(w) => b::Curve::RationalSpline { + knots: curve.knots.clone(), + homogeneous: curve.points.iter().zip(w).map(|(p, w)| [p.x * w, p.y * w, p.z * w, *w]).collect(), + }, + None => { + b::Curve::Spline { knots: curve.knots.clone(), points: curve.points.iter().map(|p| [p.x, p.y, p.z]).collect() } + } + }; + edges.push(PartEdge { curve: spline, nurbs: None, interval: [0.0, 1.0], vertices: [start, end] }); origin.push(None); spoke_of.insert(spoke, id); id @@ -820,7 +911,8 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso } faces.push(PartFace { surface: crate::surfaces::spline_surface(&patch.surface), forward: true, loops: vec![uses] }); } - let made = assemble(Parts { vertices, edges, faces, tolerance: tol }, false)?; + let mut made = assemble(Parts { vertices, edges, faces, tolerance: tol }, false)?; + hold_gap(&mut made.brep, tol); let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::Failed(format!("patch: SMLib: {e}")))?; let (sheet, order) = crate::native::body_from_smlib_ordered(&smlib)?; let Some(order) = order else { return Ok(sheet) }; @@ -843,8 +935,23 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], fill: &Iso sheet.with_history(history, &[body]) } -/// The vertex at parameter `t` inside loop edge `k` (record edge `edge`), made once. -fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap, k: usize, edge: &b::Edge, t: f64) -> Result { +/// A patch record's edges and vertices given the tolerances that hold a surface `gap` from them. +/// A record's tolerance is SMLib's intersection tolerance, twice the zone tolerance SMLib holds an +/// edge's gap to its faces to, and a vertex holds gaps up to half its zone tolerance (SMLib's +/// `SM_XSECT_TO_ZONETOL3D`, `SmBrep::ValidateAndUpdateTolerances`): an edge takes `2·gap`, a +/// vertex `4·gap`. +fn hold_gap(brep: &mut b::Brep, gap: f64) { + for e in &mut brep.edges { + e.tolerance = e.tolerance.max(2.0 * gap); + } + for v in &mut brep.vertices { + v.tolerance = v.tolerance.max(4.0 * gap); + } +} + +/// The vertex at parameter `t` inside record edge `e` (`edge`), made once. +fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap<(usize, u64), u32>, e: usize, edge: &b::Edge, t: f64) -> Result { + let k = (e, t.to_bits()); if let Some(v) = made.get(&k) { return Ok(*v); } @@ -861,18 +968,31 @@ fn middle(vertices: &mut Vec<[f64; 3]>, made: &mut std::collections::HashMap f64 { - (body.size() * 1e-7).max(solidcraft_geom::LINEAR_TOL) + (placed_size(body) * 1e-7).max(solidcraft_geom::LINEAR_TOL) } -/// How far the fill's surface may be from the loop's edges: `10⁻⁶` of the body's size, at least +/// The body's size as the fill tolerances take it, the same wherever the body is and however it +/// is turned (the bounding box's diagonal is not: a cup turned 0.7 rad about (1, 2, 3) grows from +/// 54.7 to 61.6, and its fill was sampled to another tolerance): the diameter of the smallest ball +/// holding its vertices. (Twice the farthest vertex's distance from their centroid is not the +/// body's size where the vertices crowd one end: up to twice its diameter, and a rounded box's G2 +/// corner patch, its vertices crowding that corner, then fitted past the box.) A body with no +/// vertices takes its box's diagonal. +fn placed_size(body: &Body) -> f64 { + let vertices: Vec = body.record().vertices.iter().map(|v| Vec3::new(v.point[0], v.point[1], v.point[2])).collect(); + solidcraft_geom::Ball::enclosing(&vertices).map_or_else(|| body.size(), |ball| ball.diameter()) +} + +/// How far the fill's surface may be from the loop's edges: `10⁻⁶` of the body's size +/// ([`placed_size`]), at least /// `10⁻⁵` mm — ten times [`planarity_tolerance`]. Ten times the linear tolerance because a /// fitted surface approaches curved edges like a cubic spline, so each further factor of ten /// costs about twice the spans each way, and imported edges may already lie `10⁻⁵` mm or more off /// their vertices. Later operations must take the face to contain its edges within this /// tolerance, not the linear one: the face's edges are the body's exact edges, the surface -/// between them is the fit (the patch record gives its edges this tolerance). +/// between them is the fit (the patch record's edges and vertices hold this gap: [`hold_gap`]). pub(crate) fn face_tolerance(body: &Body) -> f64 { - (body.size() * 1e-6).max(1e-5) + (placed_size(body) * 1e-6).max(1e-5) } #[cfg(test)] @@ -956,11 +1076,24 @@ mod tests { worst } - /// Whether every edge of `made` is one of `of`'s own (the same curve record on the same - /// interval). + /// Whether every edge of `made` is one of `of`'s own: the same kind of curve, on the same + /// interval, on the curve it is parameterised on (its NURBS form where it has one) to + /// rounding: the same knots and control points within 10⁻¹² of their size. (SMLib makes a + /// conic's frame and NURBS form again on a round trip, the last bit of a coordinate apart.) fn own_edges(made: &Body, of: &Body) -> bool { let own = record(of).edges; - record(made).edges.iter().all(|e| own.iter().any(|o| o.curve == e.curve && o.interval == e.interval)) + let kind = |e: &b::Edge| std::mem::discriminant(&e.curve); + let close = |p: &[f64], q: &[f64]| p.len() == q.len() && p.iter().zip(q).all(|(x, y)| (x - y).abs() <= 1e-12 * (1.0 + x.abs().max(y.abs()))); + let same = |c: &b::Curve, d: &b::Curve| match (c, d) { + (b::Curve::Spline { knots: k, points: p }, b::Curve::Spline { knots: l, points: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + (b::Curve::RationalSpline { knots: k, homogeneous: p }, b::Curve::RationalSpline { knots: l, homogeneous: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + _ => c == d, + }; + record(made).edges.iter().all(|e| own.iter().any(|o| kind(o) == kind(e) && same(o.parameters(), e.parameters()) && o.interval == e.interval)) } /// The fill's mesh: every normal finite, and no triangle folded over (all face the same way @@ -1089,9 +1222,10 @@ mod tests { let mut edges = Vec::new(); for k in 0..n { let c = &top[k]; - edges.push(PartEdge { curve: c.clone(), interval: interval(c), vertices: [k as u32, ((k + 1) % n) as u32] }); - edges.push(PartEdge { curve: moved(c), interval: interval(c), vertices: [(n + k) as u32, (n + (k + 1) % n) as u32] }); + edges.push(PartEdge { nurbs: None, curve: c.clone(), interval: interval(c), vertices: [k as u32, ((k + 1) % n) as u32] }); + edges.push(PartEdge { nurbs: None, curve: moved(c), interval: interval(c), vertices: [(n + k) as u32, (n + (k + 1) % n) as u32] }); edges.push(PartEdge { + nurbs: None, curve: b::Curve::Line { start: arr(corners[k]), end: arr(corners[k] + drop) }, interval: [0.0, 1.0], vertices: [k as u32, (n + k) as u32], diff --git a/crates/kernel/src/fill_general_tests.rs b/crates/kernel/src/fill_general_tests.rs index c23e44b46..7fee97f5a 100644 --- a/crates/kernel/src/fill_general_tests.rs +++ b/crates/kernel/src/fill_general_tests.rs @@ -108,7 +108,7 @@ fn rim_points(body: &Body, per: usize) -> Vec { let r = body.record(); let mut out = Vec::new(); for e in r.edges.iter().filter(|e| e.uses.len() == 1) { - let c = CurveEval::new(&e.curve).unwrap(); + let c = CurveEval::new(e.parameters()).unwrap(); let [t0, t1] = e.interval; for k in 0..per { out.push(c.point(t0 + (t1 - t0) * (k as f64 + 0.5) / per as f64).unwrap()); @@ -164,8 +164,21 @@ fn check_face(name: &str, open: &Body, fill: &Body) -> f64 { assert!(fill.is_surface()); assert!(fill.face_count() >= 1, "{name}: a face"); let (own, made) = (open.record(), fill.record()); + // The same kind of curve on the same curve it is parameterised on, to rounding (SMLib makes a + // conic's frame and NURBS form again on a round trip, the last bit of a coordinate apart). + let close = |p: &[f64], q: &[f64]| p.len() == q.len() && p.iter().zip(q).all(|(x, y)| (x - y).abs() <= 1e-12 * (1.0 + x.abs().max(y.abs()))); + let same = |c: &b::Curve, d: &b::Curve| match (c, d) { + (b::Curve::Spline { knots: k, points: p }, b::Curve::Spline { knots: l, points: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + (b::Curve::RationalSpline { knots: k, homogeneous: p }, b::Curve::RationalSpline { knots: l, homogeneous: q }) => { + k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y)) + } + _ => c == d, + }; + let kind = |e: &b::Edge| std::mem::discriminant(&e.curve); for e in made.edges.iter().filter(|e| e.uses.len() == 1) { - assert!(own.edges.iter().any(|o| o.curve == e.curve), "{name}: an edge that is not the body's"); + assert!(own.edges.iter().any(|o| kind(o) == kind(e) && same(o.parameters(), e.parameters())), "{name}: an edge that is not the body's"); } let faces = Faces::of(fill); let tol = face_tolerance(open); @@ -195,7 +208,7 @@ fn spec(g: Continuity) -> PatchSpec { fn report(name: &str, r: &PatchReport) { eprintln!( "{name}: fill reports gap {:e}, normals within {:.4}° ({:.4}° near clashing corners), curvature mismatch {:e}, points within {:e}", - r.gap, r.normal_deviation_deg, r.normal_deviation_all_deg, r.curvature_mismatch, r.point_gap + r.gap, r.normal_deviation_deg, r.normal_deviation_all_deg, r.jumps[2], r.point_gap ); } @@ -238,7 +251,7 @@ fn free_edge_points(body: &Body) -> Vec { .edges .iter() .filter(|e| e.uses.len() == 1) - .map(|e| CurveEval::new(&e.curve).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap()) + .map(|e| CurveEval::new(e.parameters()).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap()) .collect::>(); // In a fixed order. points.sort_by(|a, b| (a.z, a.y, a.x).partial_cmp(&(b.z, b.y, b.x)).unwrap()); @@ -462,8 +475,6 @@ fn per_edge_continuity_and_hostile_specs() { check_face("pentagon, two edges g1/g2", &open, &fill); let bad = |spec: PatchSpec| patch_edges_report(&open, &rim, &spec).is_err(); let g1 = PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }; - assert!(bad(PatchSpec { continuity: Continuity::G3, ..g1.clone() })); - assert!(bad(PatchSpec { edges: vec![(rim[0], Continuity::G3)], ..g1.clone() })); assert!(bad(PatchSpec { edges: vec![(Vec3::new(0.0, 0.0, 40.0), Continuity::G1)], ..g1.clone() }), "an edge off the loop"); assert!(bad(PatchSpec { edges: vec![(Vec3::new(f64::NAN, 0.0, 0.0), Continuity::G1)], ..g1.clone() })); assert!(bad(PatchSpec { points: vec![Vec3::new(f64::INFINITY, 0.0, 0.0)], ..g1.clone() })); @@ -492,3 +503,128 @@ fn per_edge_continuity_and_hostile_specs() { let top = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; assert!(patch_edges_report(&b, &top, &PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }).is_err()); } + +/// The seams between `fill` and the faces of `open` beside its edges, in the middle of each +/// edge (30 % to 70 %): per seam, the largest normal angle (degrees) and jumps of `H₂`, `H₃` and +/// `H₄` along the direction across the seam (`solidcraft_geom::linkage`), read off the two +/// faces' own surfaces: the normal curvature, its rate of change and that rate's. +fn seam_jumps(open: &Body, fill: &Body) -> Vec<[f64; 4]> { + use solidcraft_geom::linkage::surface_jet; + let (ro, rf) = (open.record(), fill.record()); + let normal = |s: &SurfaceEval, uv: [f64; 2]| { + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + su.cross(sv).normalized().unwrap() + }; + let mut out = Vec::new(); + for e in &rf.edges { + let curve = CurveEval::new(e.parameters()).unwrap(); + let [t0, t1] = e.interval; + let on_fill = SurfaceEval::new(rf.faces[e.uses[0].face as usize].parameters()).unwrap(); + // The face of `open` whose own free edge this is. + let mid = curve.point(0.5 * (t0 + t1)).unwrap(); + let near = |x: &b::Edge| { + let c = CurveEval::new(x.parameters()).unwrap(); + (0..=32).map(|k| c.point(x.interval[0] + (x.interval[1] - x.interval[0]) * k as f64 / 32.0).unwrap().dist(mid)).fold(f64::MAX, f64::min) + }; + let beside = ro.edges.iter().filter(|x| x.uses.len() == 1).min_by(|a, b| near(a).total_cmp(&near(b))).unwrap(); + let on_open = SurfaceEval::new(ro.faces[beside.uses[0].face as usize].parameters()).unwrap(); + let mut worst = [0.0f64; 4]; + for i in 0..=20 { + let (p, d) = curve.derivs(t0 + (t1 - t0) * (0.3 + 0.4 * i as f64 / 20.0)).unwrap(); + let (ua, ub) = (on_fill.project(p, None, f64::INFINITY).unwrap(), on_open.project(p, None, f64::INFINITY).unwrap()); + let na = normal(&on_fill, ua); + let nb = normal(&on_open, ub) * normal(&on_open, ub).dot(na).signum(); + let w = na.cross(d.normalized().unwrap()).normalized().unwrap(); + let (ja, jb) = (surface_jet(&on_fill, ua, na, w, 4).unwrap(), surface_jet(&on_open, ub, nb, w, 4).unwrap()); + worst[0] = worst[0].max(na.dot(nb).clamp(-1.0, 1.0).acos().to_degrees()); + for k in 2..=4 { + worst[k - 1] = worst[k - 1].max((ja.form(k, [0.0, 1.0]).unwrap() - jb.form(k, [0.0, 1.0]).unwrap()).abs()); + } + } + out.push(worst); + } + out +} + +/// The Continuity Analysis (`inspect.continuity`) of `fill` sewn into `open`, on the seams at +/// `hole`: per seam, its order over the whole edge, its order over the stations from 30 % to 70 % +/// (the corners left out), and the worst G3 jump there (1/mm²). +fn continuity_analysis(open: &Body, fill: &Body, hole: &[Vec3]) -> Vec<(Option, Option, f64)> { + use crate::{ContinuityTolerances, EdgePick, pick_edges, seam_diagnostics}; + let sewn = stitch(&[open, fill], 1e-3).unwrap(); + let picks: Vec = hole.iter().map(|p| EdgePick::Point(*p)).collect(); + let edges = pick_edges(&sewn, &picks).unwrap(); + let t = ContinuityTolerances::default(); + let limits = [t.gap_mm, t.angle_deg, t.curvature_per_mm, t.curvature_change_per_mm2, t.curvature_change_rate_per_mm3]; + let report = seam_diagnostics(&sewn, &edges, 33, t).unwrap(); + report + .seams + .iter() + .map(|seam| { + let inside: Vec<_> = seam.stations.iter().filter(|s| (0.3..=0.7).contains(&s.edge_fraction)).collect(); + let worst = |f: fn(&crate::SeamStation) -> f64| inside.iter().map(|s| f(s)).fold(0.0f64, f64::max); + let metrics = [ + worst(|s| s.gap_mm), + worst(|s| s.normal_angle_deg), + worst(|s| s.curvature_jump_per_mm), + worst(|s| s.curvature_change_jump_per_mm2), + worst(|s| s.curvature_change_rate_jump_per_mm3), + ]; + let met = metrics.iter().zip(limits).take_while(|(w, l)| **w <= *l).count(); + (seam.order, met.checked_sub(1).and_then(Continuity::from_order), metrics[3]) + }) + .collect() +} + +/// A box's corner where a round of 8 up the vertical edge meets the rounds of 4 along the top +/// (one blend face rolls the top round over the vertical one); that face taken off, and the hole +/// patched G2, G3 and G4 to the rounds and the top around it. Read off the faces themselves in +/// the middle of each seam: all meet the tangent planes and the curvature; the G3 patch also meets +/// the curvature's rate of change, which the G2 patch leaves many times larger. The Continuity +/// Analysis reads each seam's middle at the order asked, and the whole seam G1: at the corners the +/// rounds' curvatures differ, so no patch can meet both. G3 to an edge between two faces is +/// refused. +#[test] +fn a_corner_of_three_rounds_patched_g3_holds_the_curvature_change_a_g2_patch_does_not() { + let solid = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 30.0)).unwrap(); + let up = crate::fillet(&solid, &[Vec3::new(40.0, 40.0, 15.0)], 8.0).unwrap(); + // The top edges and the arc between them over the vertical round: one tangent chain. + let arc = Vec3::new(32.0, 32.0, 30.0) + Vec3::new(1.0, 1.0, 0.0) * (8.0 / 2f64.sqrt()); + let rounded = crate::fillet(&up, &[Vec3::new(40.0, 20.0, 30.0), arc, Vec3::new(20.0, 40.0, 30.0)], 4.0).unwrap(); + // The blend face at the corner: the one face neither plane nor cylinder there. + let corner = Vec3::new(37.79, 36.155, 28.43); + let faces = Faces::of(&rounded); + let (k, _, _) = faces.nearest(corner); + let open = crate::remove_faces(&rounded, &[k]).unwrap(); + assert!(open.is_surface()); + let hole = [Vec3::new(34.828, 34.828, 30.0), Vec3::new(37.657, 37.657, 26.0), Vec3::new(38.828, 32.0, 28.828), Vec3::new(32.0, 38.828, 28.828)]; + let mut read = Vec::new(); + for g in [Continuity::G2, Continuity::G3, Continuity::G4] { + let name = format!("three-round corner {}", g.as_str()); + let (fill, r) = patch_edges_report(&open, &hole, &spec(g)).unwrap(); + report(&name, &r); + let seams = seam_jumps(&open, &fill); + eprintln!("{name}: jumps of the fill's report {:?}; read off the faces, per seam [angle°, H2, H3, H4] {seams:?}", r.jumps); + let analysed = continuity_analysis(&open, &fill, &hole); + eprintln!("{name}: Continuity Analysis, per seam [order over the edge, order 30-70 %, worst G3 jump 30-70 % /mm²] {analysed:?}"); + assert_eq!(analysed.len(), 4, "{name}: four seams analysed"); + for (whole, middle, _) in &analysed { + assert_eq!(*middle, Some(g), "{name}: the Continuity Analysis reads the order asked in the middle of each seam"); + assert_eq!(*whole, Some(Continuity::G1), "{name}: the corners, where the rounds' curvatures differ, hold the tangent plane only"); + } + assert_eq!(seams.len(), 4, "{name}: four seams"); + for s in &seams { + assert!(s[0] < PATCH_ANGLE_TOL_DEG, "{name}: the tangent planes meet: {s:?}"); + assert!(s[1] < 1e-3, "{name}: the curvature meets: {s:?}"); + } + read.push(seams); + } + for (g2, g3) in read[0].iter().zip(&read[1]) { + assert!(g3[2] < 1e-2, "G3 meets the curvature change: {g3:?}"); + assert!(g2[2] > 20.0 * g3[2].max(1e-6), "G2 leaves the curvature change: {g2:?} vs G3 {g3:?}"); + } + // A closed box's top edges lie between two faces: there is no one face to meet G3. + let top = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + assert!(patch_edges_report(&b, &top, &spec(Continuity::G3)).is_err()); +} diff --git a/crates/kernel/src/helix.rs b/crates/kernel/src/helix.rs index 8a18254f9..7667b09a4 100644 --- a/crates/kernel/src/helix.rs +++ b/crates/kernel/src/helix.rs @@ -147,7 +147,8 @@ mod tests { let region = Region2 { outer: Loop2::circle(Vec2::new(20.0, 0.0), 2.0), holes: vec![] }; let b = sweep_helix(&pl, ®ion, Vec3::ZERO, Vec3::Z, 8.0, 3.0).unwrap(); let v = crate::measure(&b).unwrap().volume; - assert_eq!(b.face_count(), 4, "two smooth walls and two caps"); + // SMLib sweeps the circle (one segment) as one smooth wall. + assert_eq!(b.face_count(), 3, "one smooth wall and two caps"); let want = std::f64::consts::PI * 4.0 * std::f64::consts::TAU * 20.0 * 3.0; assert!((v - want).abs() / want < 1e-3, "{v} vs {want}"); assert!(sweep_helix(&pl, ®ion, Vec3::ZERO, Vec3::Z, 3.0, 3.0).is_err(), "pitch below the section"); diff --git a/crates/kernel/src/issue_1510_tests.rs b/crates/kernel/src/issue_1510_tests.rs index b5980f181..9d0b6ee14 100644 --- a/crates/kernel/src/issue_1510_tests.rs +++ b/crates/kernel/src/issue_1510_tests.rs @@ -22,11 +22,13 @@ fn plate(width: f64) -> Body { fn a_split_in_the_plane_of_a_face_keeps_all_of_the_body() { for width in [4.0, 5.0] { let b = plate(width); - let v = b.volume_at(1e-3).unwrap(); + // Exact volumes (SMLib's, to 1e-8): a mesh's at a 1e-3 chord sags round the hole by more + // than the millionth the parts are held to. + let v = crate::measure(&b).unwrap().volume; let plane = Plane::from_normal(Vec3::new(0.0, 0.0, 1.5), Vec3::Z).unwrap(); let parts = split_by_plane(&b, &plane).unwrap(); assert_eq!(parts.len(), 2, "{width}"); - let vs: Vec = parts.iter().map(|p| p.volume_at(1e-3).unwrap()).collect(); + let vs: Vec = parts.iter().map(|p| crate::measure(p).unwrap().volume).collect(); assert!((vs.iter().sum::() - v).abs() < 1e-6 * v, "{width}: {vs:?} against {v}"); // Above: the plate from 1.5 to 2.5 less the hole; below: less the hole and the groove. let (r, h) = (2.5f64, width / 2.0); diff --git a/crates/kernel/src/issue_2005_tests.rs b/crates/kernel/src/issue_2005_tests.rs index 532a07b43..98c67eda9 100644 --- a/crates/kernel/src/issue_2005_tests.rs +++ b/crates/kernel/src/issue_2005_tests.rs @@ -31,8 +31,10 @@ fn circle_path() -> [PathSeg; 2] { fn tube(body: &Body, volume: f64, genus: usize) { let m = measure(body).unwrap(); assert!((m.volume - volume).abs() < volume * 0.01, "{m:?}, expected {volume}"); - // A closed orientable tube has Euler characteristic 2 - 2g. Coincident caps gave 2. - assert_eq!(m.vertices + m.faces + 2 * genus, m.edges + 2, "{m:?}"); + // A closed orientable tube of genus g: V - E + F - (L - F) = 2 - 2g (Euler-Poincare, L the + // loops: an annular face has two). Coincident caps gave 2 - 2g + 2. + let loops: usize = body.record().faces.iter().map(|f| f.loops.len()).sum(); + assert_eq!(m.vertices + 2 * m.faces + 2 * genus, m.edges + loops + 2, "{m:?}, {loops} loops"); // Every shell closed: each edge bounds two faces. assert!(body.record().edges.iter().all(|e| e.uses.len() >= 2)); let h = body.history().expect("sweep provenance"); diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 1ad251cdc..3c7f72a2e 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -113,6 +113,7 @@ mod prism_measure; pub mod profile; pub mod provenance; mod record; +mod repair; #[cfg(test)] mod seam_faces_tests; mod sew; @@ -154,8 +155,8 @@ mod validity; pub mod watch; pub use blend::{ - ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_least_setback, fillet_max, fillet_max_each, - fillet_setback, tangent_chain, + ChamferSide, blend_edges, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_least_setback, fillet_max, + fillet_max_each, fillet_setback, tangent_chain, }; pub use blend_corner::fillet_radii; pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper}; @@ -206,6 +207,7 @@ pub use polybool::faceted_boolean; pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell}; pub use prism::{PLANAR_FIT_TOL, extrude_planar_regions, planar_regions_boolean}; pub use prism_measure::certified_prism_equivalent; +pub use repair::{Hole, RebuiltFace, RefusedFace, RepairOptions, RepairReport, SewnGap, repair}; pub use sew::{EdgeSpec, FaceSpec, SurfSpec, sew, sew_touching}; /// Which kernel answers each operation, SMLib or solidcore (crates/smlib/src/route.rs). pub use solidcraft_smlib::route as kernel_route; diff --git a/crates/kernel/src/matchsurf_tests.rs b/crates/kernel/src/matchsurf_tests.rs index e7e9b0a1e..9699b8024 100644 --- a/crates/kernel/src/matchsurf_tests.rs +++ b/crates/kernel/src/matchsurf_tests.rs @@ -60,7 +60,7 @@ fn edge_at(body: &Body, p: Vec3) -> Chain { let mut best: Option<(f64, usize)> = None; for u in edges { let e = &r.edges[u.edge as usize]; - let m = CurveEval::new(&e.curve).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap(); + let m = CurveEval::new(e.parameters()).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap(); let d = m.dist(p); if best.is_none_or(|(b, _)| d < b) { best = Some((d, u.edge as usize)); diff --git a/crates/kernel/src/measure.rs b/crates/kernel/src/measure.rs index beecbe483..0915b0337 100644 --- a/crates/kernel/src/measure.rs +++ b/crates/kernel/src/measure.rs @@ -43,10 +43,11 @@ pub struct MassMeasure { pub notes: Vec, } -/// The relative accuracy SMLib integrates at: the finest of SmApiBrepComputeMassProperties' -/// documented range ("clamped to [1e-4, 1e-1]", SmApiQueries.h). Its cost is "governed by -/// dRelativeAccuracy". -const ACCURACY: f64 = 1e-4; +/// The relative accuracy SMLib integrates at: the finest the C API takes +/// ([`solidcraft_smlib::MEASURE_ACCURACY`], 1e-8). `smlib_brep_mass_properties` calls the +/// kernel's integration directly because SmApiBrepComputeMassProperties clamps to [1e-4, 1e-1], +/// which leaves curved faces off by 1e-5 to 1e-3; asking 1e-4 here threw that away. +const ACCURACY: f64 = solidcraft_smlib::MEASURE_ACCURACY; /// Measure a body. A B-rep body's volume, area and centre are SMLib's, integrated on its exact /// surfaces over its material regions (a sheet's: its faces' area and their centre, volume 0), diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index fe9b33ad2..eff7ee3db 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -21,9 +21,18 @@ pub enum BoolOp { /// everything or an intersection of disjoint bodies. A result SMLib's check refuses is an error. /// /// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`, from -/// SMLib's own tags, or none where a body's order cannot be matched to SMLib's. +/// SMLib's own tags, or none where a body's order cannot be matched to SMLib's. A cut by a tool +/// apart from the body is the body itself (its faces and edges kept), and their intersection empty. pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { crate::profile::timed(crate::profile::Kind::Boolean, "boolean", || { + // A tool apart from the body (their exact boxes, grown by the tolerances, do not meet) + // leaves a cut the body itself and an intersection nothing, with no intersection work. + if matches!(op, BoolOp::Cut | BoolOp::Intersect) && apart(a, b)? { + return Ok(match op { + BoolOp::Cut => Some(crate::boolean_record::operand(a, 0, &crate::record::counts(&[a, b]))), + _ => None, + }); + } let r = guard("SMLib boolean", || crate::smlib_boolean::smlib_boolean(a, b, op)); with_operand_roles(a, b, op, r) }) @@ -44,6 +53,16 @@ pub fn union_all(bodies: &[&Body]) -> Result { }) } +/// Whether B-rep bodies `a` and `b` are apart: their exact boxes, each grown by twice its +/// record's tolerance (as [`union_apart`] takes them), do not meet. +fn apart(a: &Body, b: &Body) -> Result { + if a.is_mesh() || b.is_mesh() { + return Ok(false); + } + let grown = |x: &Body| x.exact_bounds().map(|bb| bb.inflated(2.0 * x.record().tolerance)); + Ok(!grown(a)?.meets(&grown(b)?)) +} + /// A boolean's result with what its operands' faces stood for carried over: regularization /// protection and the planar construction and shell roles on supports it kept. fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result>) -> Result> { @@ -141,15 +160,44 @@ pub fn transform_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result { return placed.with_history(history, &[body]); } let sources = body.transformed_sources(m)?; - let placed = match Rigid::of_matrix(&m) { + let (placed, sources, paint) = match Rigid::of_matrix(&m) { Some(motion) => { let moved = Body::from_record(body.record().moved(&motion))?; let history = History::identity(&moved); - moved.with_history(history, &[body])? + (moved.with_history(history, &[body])?, sources, body.paint().cloned()) + } + None => { + // SMLib numbers the moved body's faces afresh: each face's source and paint follow it + // by the history (a face whose origin is not known keeps no source; with no history + // the paint stays as it was). + let placed = transformed(body, &m)?; + let origin: Vec> = (0..placed.face_count()).map(|f| moved_from(placed.history(), f)).collect(); + let sources = sources.map(|s| std::sync::Arc::new(origin.iter().map(|o| o.and_then(|j| s.get(j).cloned().flatten())).collect())); + let paint = body.paint().cloned().map(|mut p| { + if placed.history().is_none() { + return p; + } + p.faces = p + .faces + .iter() + .flat_map(|fp| { + origin.iter().enumerate().filter(|(_, o)| **o == Some(fp.face)).map(|(face, _)| crate::FacePaint { face, ..fp.clone() }) + }) + .collect(); + p + }); + (placed, sources, paint) } - None => transformed(body, &m)?, }; - Ok(placed.with_color(body.color()).with_paint(body.paint().cloned()).with_face_sources(sources).inherit_regularization_protection(body)) + Ok(placed.with_color(body.color()).with_paint(paint).with_face_sources(sources).inherit_regularization_protection(body)) +} + +/// The face of the operand that face `f` of a moved body is, by the move's history. +fn moved_from(history: Option<&History>, f: usize) -> Option { + match history?.faces.get(f)?.origins.as_slice() { + [crate::history::FaceOrigin::Face { operand: 0, face }] => Some(*face), + _ => None, + } } /// `body` moved by a matrix that is not a rigid motion, in SMLib, its history from SMLib's tags. diff --git a/crates/kernel/src/outline_tests.rs b/crates/kernel/src/outline_tests.rs index 017dd54eb..c1579db16 100644 --- a/crates/kernel/src/outline_tests.rs +++ b/crates/kernel/src/outline_tests.rs @@ -30,8 +30,12 @@ fn a_lip_swept_on_a_round_rim_joins_it() { let r = boolean(a, b, BoolOp::Union).unwrap().unwrap(); assert_eq!(r.shell_count(), 1, "inset {inset}: one solid"); assert!(r.validity().is_empty(), "inset {inset}: {:?}", r.validity()); + // Each mesh lies within its chord (1e-5) of its faces: two meshes of the same solid, + // tessellated face by face as each body has its faces, differ by at most their area + // times twice that. let v = mesh_volume(&r); - assert!((v - want).abs() < 1e-3, "inset {inset}: volume {v} vs {want}"); + let bound = crate::measure(&r).unwrap().area * 2e-5; + assert!((v - want).abs() < bound, "inset {inset}: volume {v} vs {want} (within {bound})"); } } } diff --git a/crates/kernel/src/planar_regularize.rs b/crates/kernel/src/planar_regularize.rs index 6d5a8cc46..5f263c0c3 100644 --- a/crates/kernel/src/planar_regularize.rs +++ b/crates/kernel/src/planar_regularize.rs @@ -41,13 +41,14 @@ impl Body { return Ok(None); } let actual = super::planar_sources::actual_planes(&self)?; + let at = super::planar_sources::Resolution::of(&self); let valid: Vec<_> = actual .iter() .zip(sources) .map(|(actual, s)| { s.as_ref() .and_then(super::planar_sources::certified_plane) - .filter(|p| actual.is_some_and(|actual| super::planar_sources::same_support(p, &actual))) + .filter(|p| actual.is_some_and(|actual| super::planar_sources::same_support(p, &actual, at))) }) .collect(); let record = self.record(); diff --git a/crates/kernel/src/planar_sources.rs b/crates/kernel/src/planar_sources.rs index ad0ee3249..43c8e559a 100644 --- a/crates/kernel/src/planar_sources.rs +++ b/crates/kernel/src/planar_sources.rs @@ -40,23 +40,48 @@ pub(super) fn actual_planes(body: &Body) -> Result>> { .collect()) } -/// How far apart the normals' x components of two planes `same_support` accepts can be, with -/// room to spare: their unit normals are within about 1e-12 of each other. -const NORMAL_WINDOW: f64 = 1e-9; +/// The resolution two planar supports are compared at: SMLib's own, by which it calls two planes +/// coincident (SmPlane::CoincidenceCheck): a distance within the body's intersection tolerance +/// (the record's `tolerance`, SMLib's XSectTol3d) and normals within the angle that tolerance +/// makes across the body (`tolerance / size`; SMLib takes the plane's own extent, the body's is +/// at least as large, so this is no looser), never finer than rounding. Faces SMLib rebuilt +/// through a boolean lie within it of the plane they were made on (a cut cap at z = 10 came back +/// 2.1e-11 off and 1.4e-12 rad turned), not within a few ulps of it. +#[derive(Clone, Copy, Debug)] +pub(super) struct Resolution { + linear: f64, + angular: f64, +} -/// The entries of `sorted` (ordered by their plane's normal x) whose normal x is within -/// [`NORMAL_WINDOW`] of `nx`: the only ones `same_support` can accept for a plane with that normal. -fn normal_window(sorted: &[T], plane: impl Fn(&T) -> &Plane, nx: f64) -> &[T] { - let first = sorted.partition_point(|t| plane(t).normal().x < nx - NORMAL_WINDOW); - let last = sorted.partition_point(|t| plane(t).normal().x <= nx + NORMAL_WINDOW); +impl Resolution { + pub(super) fn of(body: &Body) -> Self { + let tolerance = body.record().tolerance; + let size = body.size(); + let rounding = 4096. * f64::EPSILON; + let linear = if tolerance.is_finite() && tolerance > 0. { tolerance } else { 0. }; + let angular = if size.is_finite() && size > 0. { linear / size } else { 0. }; + Resolution { linear: linear.max(rounding * (1. + size.max(0.))), angular: angular.max(rounding) } + } +} + +/// The entries of `sorted` (ordered by their plane's normal x) whose normal x is within the +/// resolution's angle of `nx` (and rounding): the only ones `same_support` can accept for a plane +/// with that normal. +fn normal_window(sorted: &[T], plane: impl Fn(&T) -> &Plane, nx: f64, at: Resolution) -> &[T] { + let window = 2. * at.angular + 1e-12; + let first = sorted.partition_point(|t| plane(t).normal().x < nx - window); + let last = sorted.partition_point(|t| plane(t).normal().x <= nx + window); sorted.get(first..last.max(first)).unwrap_or_default() } -pub(super) fn same_support(a: &Plane, b: &Plane) -> bool { - let error = 4096. * f64::EPSILON * (1. + a.origin.len() + b.origin.len()); - a.normal().cross(b.normal()).len() <= 4096. * f64::EPSILON - && a.normal().dot(b.normal()) > 0. - && (a.origin - b.origin).dot(a.normal()).abs() <= error +/// Whether `a` and `b` are one oriented plane at resolution `at`: normals the same way within its +/// angle, each origin within its distance of the other plane. +pub(super) fn same_support(a: &Plane, b: &Plane, at: Resolution) -> bool { + let (na, nb) = (a.normal(), b.normal()); + na.cross(nb).len() <= at.angular + && na.dot(nb) > 0. + && (b.origin - a.origin).dot(na).abs() <= at.linear + && (a.origin - b.origin).dot(nb).abs() <= at.linear } fn base_plane(source: &FaceSource, actual: &Plane) -> Option { @@ -195,13 +220,18 @@ impl Body { if open.len() > 256 { return Ok(self); } + let at = Resolution::of(&self); let opening_tolerance = if shell.is_some() { inputs.iter().map(|input| input.size()).fold(0., f64::max) * 1e-4 + 1e-6 } else { 0. }; let mapped = guard("exact planar support lineage", || { let mut competing = Vec::new(); for plane in blocker.map(actual_planes).transpose()?.into_iter().flatten().flatten() { - // A tool face blocks a face on its plane facing either way. + // A cut's tool face enters the result turned round (the wall of the hollow it + // leaves), so it competes only with a face on its plane facing against it: a + // pocket's floor, or a target face the tool sat on from outside. A tool face that + // faces the same way as the target's face on its plane (a pocket cut down from a + // cap, its top on the cap) is the tool's own outside and leaves the cap the cap. let opposing = Plane::new(plane.origin, plane.x, -plane.y).ok_or_else(|| KernelError::Invalid("invalid opposing plane".into()))?; - competing.extend([plane, opposing]); + competing.push(opposing); } competing.sort_by(|a, b| a.normal().x.total_cmp(&b.normal().x)); let mut candidates = Vec::new(); @@ -226,7 +256,7 @@ impl Body { unknown_supports.push(actual); continue; }; - if !same_support(&plane, &actual) || (shell.is_some() && open.iter().any(|p| actual.height(*p).abs() <= opening_tolerance)) { + if !same_support(&plane, &actual, at) || (shell.is_some() && open.iter().any(|p| actual.height(*p).abs() <= opening_tolerance)) { unknown_supports.push(actual); continue; } @@ -254,16 +284,16 @@ impl Body { if let Some(actual) = actual { let mut blocked = false; let nx = actual.normal().x; - for plane in normal_window(&unknown_supports, |p| p, nx) { + for plane in normal_window(&unknown_supports, |p| p, nx, at) { work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("unknown planar source comparison budget exceeded".into()))?; - if same_support(plane, &actual) { + if same_support(plane, &actual, at) { blocked = true; break; } } - for plane in normal_window(&competing, |p| p, nx) { + for plane in normal_window(&competing, |p| p, nx, at) { work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("planar tool comparison budget exceeded".into()))?; - if same_support(plane, &actual) { + if same_support(plane, &actual, at) { blocked = true; break; } @@ -286,9 +316,9 @@ impl Body { continue; } let mut chosen: Option<(Plane, &FaceSource, bool, usize)> = None; - for (plane, source, inner, cost) in normal_window(&candidates, |c| &c.0, nx) { + for (plane, source, inner, cost) in normal_window(&candidates, |c| &c.0, nx, at) { work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("planar source comparison budget exceeded".into()))?; - if same_support(plane, &actual) { + if same_support(plane, &actual, at) { if let Some((previous_plane, previous_source, previous_inner, _)) = chosen { let Some(remaining) = identity_bytes.checked_sub(*cost) else { chosen = None; @@ -444,7 +474,9 @@ mod tests { .map(|(i, p)| { let p = (*p)?; let find = |of: &Body, ps: &[Option]| { - ps.iter().position(|q| q.is_some_and(|q| same_support(&q, &p))).and_then(|i| of.face_sources()?[i].clone()) + ps.iter() + .position(|q| q.is_some_and(|q| same_support(&q, &p, Resolution::of(&combined)))) + .and_then(|i| of.face_sources()?[i].clone()) }; let in_a = face_points(&combined, i).iter().all(|q| q.x <= a_right + 1e-9); if in_a { @@ -496,7 +528,7 @@ mod tests { if matches!(s, Some(FaceSource::ExtrudeSide { coalesced: true, plane: None, .. })) { assert!(cup.face_plane(i).is_none(), "loss witness is not source authority"); } else if s.is_some() { - assert!(same_support(&cup.face_plane(i).unwrap(), &cup.planar_face(i).unwrap())); + assert!(same_support(&cup.face_plane(i).unwrap(), &cup.planar_face(i).unwrap(), Resolution::of(&cup))); } } let moved = transform_matrix(&cup, [[0., 1., 0., 0.], [-1., 0., 0., 0.], [0., 0., 1., 0.], [100., 200., 300., 1.]]).unwrap(); diff --git a/crates/kernel/src/polybool.rs b/crates/kernel/src/polybool.rs index a722c1882..59deb9279 100644 --- a/crates/kernel/src/polybool.rs +++ b/crates/kernel/src/polybool.rs @@ -39,6 +39,8 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result MAX_TRIANGLES { return Err(failed(&format!("the mesh is too detailed ({} triangles, at most {MAX_TRIANGLES})", b.triangles.len()))); } + let welded = welded(b); + let b = &welded; let groups = coplanar_groups(b, tol)?; let mut faces = Vec::new(); let mut face_group = Vec::new(); @@ -60,6 +62,26 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result Mesh { + let mut at: BTreeMap<[u64; 3], u32> = BTreeMap::new(); + let mut positions = Vec::with_capacity(m.positions.len()); + let index: Vec = m + .positions + .iter() + .map(|p| { + *at.entry([p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]).or_insert_with(|| { + positions.push(*p); + (positions.len() - 1) as u32 + }) + }) + .collect(); + let triangles = m.triangles.iter().map(|t| t.map(|i| index.get(i as usize).copied().unwrap_or(i))).collect(); + Mesh { positions, triangles, ..Mesh::default() } +} + /// The mesh's triangles in runs that make one planar face each: triangles sharing an edge, on /// one plane within `tol`, are one run. fn coplanar_groups(m: &Mesh, tol: f64) -> Result>> { diff --git a/crates/kernel/src/prism_curve.rs b/crates/kernel/src/prism_curve.rs index 611ffc3e2..508ef1f06 100644 --- a/crates/kernel/src/prism_curve.rs +++ b/crates/kernel/src/prism_curve.rs @@ -578,14 +578,35 @@ mod tests { } out } - fn trap() -> Vec { - let mut p = vec![1.]; - for k in 0..=16 { - p = multiply(&p, &[-(k as f64) / 16., 1.]); + /// The power basis `p` (in t) over the span t = a + h s, in s. + fn shifted(p: &[f64], a: f64, h: f64) -> Vec { + let mut out = vec![0.]; + for c in p.iter().rev() { + out = multiply(&out, &[a, h]); + out[0] += c; } - let mid = (0..=16).map(|k| 1. / 32. - k as f64 / 16.).product::(); - p.iter_mut().for_each(|v| *v /= mid); - p + out + } + /// A spline of `degree` over spans [k/16, (k+1)/16] (k = 0..16), joined C0 (each interior + /// knot `degree` times), whose homogeneous `x`, `y`, `w` are the power bases `f(k)` gives + /// in the span's own parameter s ∈ [0, 1]: a curve that bends only between the knots. + fn spans(degree: usize, f: impl Fn(usize) -> [Vec; 3]) -> Curve { + let mut knots = vec![0.; degree + 1]; + let mut homogeneous: Vec<[f64; 4]> = Vec::new(); + for k in 0..16 { + let [x, y, w] = f(k); + let (x, y, w) = (bernstein(&x, degree), bernstein(&y, degree), bernstein(&w, degree)); + let controls = x.iter().zip(y).zip(w).map(|((x, y), w)| [*x, y, 0., w]); + homogeneous.extend(controls.skip(usize::from(k > 0))); + knots.extend(std::iter::repeat_n((k + 1) as f64 / 16., degree)); + } + knots.push(1.); + Curve::RationalSpline { knots, homogeneous } + } + /// The bump s (1 - s) / (1/4) in the span's own parameter: 0 at both its ends (every old + /// sample location k/16 is a knot), 1 half way along the first span (t = 1/32). + fn bump(k: usize) -> Vec { + if k == 0 { vec![0., 4., -4.] } else { vec![0.] } } fn bezier_knots(degree: usize) -> Vec { std::iter::repeat_n(0., degree + 1).chain(std::iter::repeat_n(1., degree + 1)).collect() @@ -615,27 +636,37 @@ mod tests { Curve::RationalSpline { knots: bezier_knots(2), homogeneous: vec![[10., 0., 0., 1.], [10. * w, 10. * w, 0., w], [0., 10., 0., 1.]] } } + /// Sampling must not certify a spline cap that merely passes through the sample points. + /// Once that took a single polynomial of degree 17 with a root at each of the 17 old sample + /// locations k/16, more than a B-rep record holds (MAX_SPLINE_DEGREE 16); here the aliasing is + /// in the knots instead: a C0 quadratic spline with a knot at every k/16, on the line (or + /// the circle) at each of them, and bowing off it between (by 1 mm, 1/32 along). #[test] fn sample_aliasing_does_not_certify_spline_caps() { - let e = curve(&[0., 10.], &trap(), &[1.], 17); + let e = spans(2, |k| { + let h = 1. / 16.; + [shifted(&[0., 10.], k as f64 * h, h), bump(k), vec![1.]] + }); for k in 0..=16 { - assert!(at(&e, k as f64 / 16.).y.abs() < 1e-4, "old sample locations must see a line"); + assert!(at(&e, k as f64 / 16.).y.abs() < 1e-12, "old sample locations must see a line"); } - assert!((at(&e, 1. / 32.).y - 1.).abs() < 1e-6); + assert!((at(&e, 1. / 32.).y - 1.).abs() < 1e-12); assert!(segment(&run(&e, true), &Plane::XY, 1e-3, &mut 2_000_000).is_none()); - let q = trap(); - let mut perturb = q.iter().map(|v| v * 0.1).collect::>(); - perturb[0] += 1.; + // The quarter circle of radius 10, its homogeneous coordinates scaled by 1 + bump / 10 but + // its weight not: radius 10 at every k/16, 11 at 1/32. let w = std::f64::consts::FRAC_1_SQRT_2; - let x = multiply(&[10., 20. * (w - 1.), 10. * (1. - 2. * w)], &perturb); - let y = multiply(&[0., 20. * w, 10. * (1. - 2. * w)], &perturb); - let circle = curve(&x, &y, &[1., 2. * (w - 1.), 2. * (1. - w)], 19); + let (x, y, wt) = ([10., 20. * (w - 1.), 10. * (1. - 2. * w)], [0., 20. * w, 10. * (1. - 2. * w)], [1., 2. * (w - 1.), 2. * (1. - w)]); + let circle = spans(4, |k| { + let (a, h) = (k as f64 / 16., 1. / 16.); + let scale: Vec = bump(k).iter().enumerate().map(|(i, v)| v / 10. + if i == 0 { 1. } else { 0. }).collect(); + [multiply(&shifted(&x, a, h), &scale), multiply(&shifted(&y, a, h), &scale), shifted(&wt, a, h)] + }); for k in 0..=16 { let p = at(&circle, k as f64 / 16.); - assert!((p.x.hypot(p.y) - 10.).abs() < 1e-3, "old sample locations must see a circle"); + assert!((p.x.hypot(p.y) - 10.).abs() < 1e-9, "old sample locations must see a circle"); } let p = at(&circle, 1. / 32.); - assert!((p.x.hypot(p.y) - 11.).abs() < 1e-5); + assert!((p.x.hypot(p.y) - 11.).abs() < 1e-9); assert!(segment(&run(&circle, true), &Plane::XY, 1e-3, &mut 2_000_000).is_none()); } @@ -649,7 +680,8 @@ mod tests { assert!((sweep.abs() - std::f64::consts::FRAC_PI_2).abs() < 1e-8); assert_eq!(sweep > 0., forward); } - let line = curve(&[0., 10.], &[0.], &[1.], 17); + // A line written at the highest degree a B-rep record holds (MAX_SPLINE_DEGREE). + let line = curve(&[0., 10.], &[0.], &[1.], solidcraft_geom::bspline::MAX_SPLINE_DEGREE); assert!(matches!(segment(&run(&line, true), &Plane::XY, 1e-5, &mut 2_000_000).unwrap()[0], Seg2::Line { .. })); // The longitudinal derivative is negative at t=1/3, independently // establishing genuine retracing rather than a stationary tangent. diff --git a/crates/kernel/src/prism_measure.rs b/crates/kernel/src/prism_measure.rs index eee0405a2..41036f34b 100644 --- a/crates/kernel/src/prism_measure.rs +++ b/crates/kernel/src/prism_measure.rs @@ -927,9 +927,15 @@ mod tests { } } assert_eq!(equivalent(&original, source.size(), &same, source.size()), Some(true)); - let last = original.faces.len() - 1; - let outward = preflight(&original).unwrap()[last]; - let runs = loop_runs(&original, last, 0, outward).unwrap(); + // A cap: a face whose plane is square to z (the record's face order is SMLib's, its last + // face may be the hole's wall). + let cap = original + .faces + .iter() + .position(|f| plane_of(&f.surface).is_some_and(|(_, u, v)| u.cross(v).normalized().is_some_and(|n| n.z.abs() > 0.9))) + .unwrap(); + let outward = preflight(&original).unwrap()[cap]; + let runs = loop_runs(&original, cap, 0, outward).unwrap(); assert!( loops_same( &cap_loop(&runs, &Plane::XY, 3e-9, &mut 2_000_000).unwrap(), @@ -950,8 +956,10 @@ mod tests { let region = solidcraft_geom::Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]); let doubled = CapLoop { segments: region.segs.iter().chain(®ion.segs).copied().collect(), area: Interval::enclosing(800., 1e-8).unwrap() }; assert!(separated_material(&[doubled], 1e-6, &mut 16_000_000).is_none()); - let thin = crate::box_solid(Vec3::ZERO, Vec3::new(20., 20., 1e-5)).unwrap(); - assert!(cert(&thin, 3e-6).is_none()); + // Thinner than a body's tolerance (2e-5): SMLib refuses it as a solid; built, it gets none. + if let Ok(thin) = crate::box_solid(Vec3::ZERO, Vec3::new(20., 20., 1e-5)) { + assert!(cert(&thin, 3e-6).is_none()); + } } #[test] diff --git a/crates/kernel/src/record_tests.rs b/crates/kernel/src/record_tests.rs index 54ac6c194..0c0e20653 100644 --- a/crates/kernel/src/record_tests.rs +++ b/crates/kernel/src/record_tests.rs @@ -141,24 +141,30 @@ fn extrude_sides_follow_profile_segments_in_any_order() { // The certificates are produced as before. assert!(b.face_sources().unwrap().iter().all(Option::is_some)); } - // The +x side is whichever segment of the given loop runs along x = 40. + // The +x side is whichever segment of the given loop runs along x = 40 (the hole's wall at + // x = 10 faces +x too). let r = &variants[2]; let b = crate::extrude(&Plane::XY, std::slice::from_ref(r), 0.0, 10.0).unwrap().pop().unwrap(); let k = r.outer.segs.iter().position(|s| s.start().x == 40.0 && s.end().x == 40.0).unwrap(); - let side = b.faces(1e-3).unwrap().iter().position(|f| f.plane_normal.is_some_and(|n| n.dist(Vec3::X) < 1e-9)).unwrap(); + let side = b + .faces(1e-3) + .unwrap() + .iter() + .position(|f| f.plane_normal.is_some_and(|n| n.dist(Vec3::X) < 1e-9) && (f.centroid.x - 40.0).abs() < 1e-6) + .unwrap(); assert_eq!(origins(&b)[side], [P(k)]); } -/// A big arc is built as two edges: both faces come from it. +/// A big arc sweeps one face, as every segment does. #[test] -fn extrude_a_big_arc_gives_two_faces_of_one_segment() { +fn extrude_a_big_arc_gives_one_face_of_one_segment() { let (a, b) = (Vec2::new(10.0 * (0.3f64).cos(), -10.0 * (0.3f64).sin()), Vec2::new(10.0 * (0.3f64).cos(), 10.0 * (0.3f64).sin())); let arc = Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: 0.3, sweep: TAU - 0.6 }; let r = Region2 { outer: Loop2 { segs: vec![arc, Seg2::Line { a, b }] }, holes: vec![] }; let body = crate::extrude(&Plane::XY, std::slice::from_ref(&r), 0.0, 5.0).unwrap().pop().unwrap(); let got = origins(&body); assert_eq!(got, expected_extrusion(&body, &Plane::XY, &r, 5.0)); - assert_eq!(got.iter().filter(|o| **o == [P(0)]).count(), 2); + assert_eq!(got.iter().filter(|o| **o == [P(0)]).count(), 1); assert_eq!(got.iter().filter(|o| **o == [P(1)]).count(), 1); } @@ -177,18 +183,18 @@ fn primitives_report_their_construction() { assert_eq!(o, &[want]); } assert!(b.face_sources().unwrap().iter().all(|s| matches!(s, Some(crate::FaceSource::Box { .. })))); - // Cylinder: a circle of two arcs, extruded. + // Cylinder: a circle (one arc), extruded. let c = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.0, 8.0).unwrap(); let r = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 5.0, crate::build::SEAM_ANGLE), holes: vec![] }; let frame = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap(); let want = expected_extrusion(&c, &frame, &r, 8.0); assert_eq!(origins(&c), want); - // Sphere: six patches, all from the arc of the half disc it revolves. + // Sphere: one face, from the arc of the half disc it revolves. let s = crate::sphere(Vec3::ZERO, 5.0).unwrap(); - assert_eq!(origins(&s), vec![vec![P(0)]; 6]); - // Torus: a circle re-split for its seam, turned in three: each face from both arcs. + assert_eq!(origins(&s), vec![vec![P(0)]]); + // Torus: one face, from the circle (segment 0) it turns. let t = crate::torus(Vec3::ZERO, 10.0, 2.0).unwrap(); - assert_eq!(origins(&t), vec![vec![P(0), P(1)]; 6]); + assert_eq!(origins(&t), vec![vec![P(0)]]); } /// The plane the revolve tests sketch in (x across, y up the world z axis, the revolve axis). @@ -209,31 +215,28 @@ fn expected_revolution(b: &Body, r: &Region2) -> Vec> { #[test] fn revolve_partial_and_full() { let r = Region2 { outer: rect(10.0, 0.0, 20.0, 5.0), holes: vec![rect(12.0, 1.0, 14.0, 2.0).reversed()] }; - // Under half a turn truck sweeps in two parts, beyond it in three; a full turn has no caps, - // and its planar faces (from the segments square to the axis) are whole (#726), as a partial + // SMLib turns each segment into one face whatever the angle; a full turn has no caps, and + // its planar faces (from the segments square to the axis) are whole (#726), as a partial // turn's are when it is final (`revolve_whole`). let segs: Vec = r.outer.segs.iter().chain(r.holes.iter().flat_map(|h| &h.segs)).cloned().collect(); for whole in [false, true] { - for (angle, parts, caps) in [(FRAC_PI_2, 2, 2), (1.5 * PI, 3, 2), (TAU, 3, 0)] { + for (angle, caps) in [(FRAC_PI_2, 2), (1.5 * PI, 2), (TAU, 0)] { let revolve = if whole { crate::revolve_whole } else { crate::revolve }; let b = revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap(); let got = origins(&b); assert_eq!(got, expected_revolution(&b, &r), "angle {angle}, whole {whole}"); - for (k, s) in segs.iter().enumerate() { - let square = matches!(s, Seg2::Line { a, b } if (a.y - b.y).abs() < 1e-12); - let want = if (angle == TAU || whole) && square { 1 } else { parts }; - assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), want, "segment {k} at angle {angle}, whole {whole}"); + for k in 0..segs.len() { + assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), 1, "segment {k} at angle {angle}, whole {whole}"); } assert_eq!(got.iter().filter(|o| **o == [START] || **o == [END]).count(), caps); } } } -/// Loops given clockwise, a hole that is a full circle of three arcs: extrude numbers every -/// face by the segment as given; revolve re-seams the circle into two half circles, each from -/// every given arc it runs over. +/// Loops given clockwise, a hole that is a full circle of three arcs: extrude and revolve +/// number every face by the segment as given, one face each. #[test] -fn clockwise_loops_and_a_reseamed_circle_keep_their_numbers() { +fn clockwise_loops_and_a_circle_of_arcs_keep_their_numbers() { let (c, rad) = (Vec2::new(20.0, 10.0), 4.0); let arcs = [(0.3, 2.0), (2.3, 2.5), (4.8, TAU - 4.5)]; let ccw = Loop2 { segs: arcs.iter().map(|&(start, sweep)| Seg2::Arc { center: c, radius: rad, start, sweep }).collect() }; @@ -245,28 +248,14 @@ fn clockwise_loops_and_a_reseamed_circle_keep_their_numbers() { for k in 0..7 { assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), 1, "segment {k}"); } - // Revolved, the circle restarts at 0.4142 rad: the half from there runs over the first two - // arcs (6, 5), the other half over all three (it ends past the first arc's start). - let first_half = |q: Vec2| (q - c).angle().rem_euclid(TAU); + // Revolved, each arc turns into a face of its own, as the rectangle's sides do. for angle in [FRAC_PI_2, TAU] { let b = crate::revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap(); let got = origins(&b); - let want = expected_revolution(&b, &r); - let (_, centres) = mesh_points(&b); - let mut halves = [0, 0]; - for ((g, w), centres) in got.iter().zip(&want).zip(¢res) { - let flat: Vec = centres.iter().map(|p| Vec2::new(p.x.hypot(p.y), p.z)).collect(); - if flat.iter().all(|q| (q.dist(c) - rad).abs() < 0.1) { - let first = flat.iter().all(|q| (0.4142 - 1e-3..=0.4142 + PI + 1e-3).contains(&first_half(*q))); - assert_eq!(g, &if first { vec![P(5), P(6)] } else { vec![P(4), P(5), P(6)] }, "angle {angle}"); - halves[usize::from(!first)] += 1; - } else { - assert_eq!(g, w, "angle {angle}"); - } + assert_eq!(got, expected_revolution(&b, &r), "angle {angle}"); + for k in 0..7 { + assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), 1, "segment {k} at angle {angle}"); } - // Truck turns each half in as many parts as each rectangle side. - let parts = got.iter().filter(|o| **o == [P(0)]).count(); - assert_eq!(halves, [parts, parts], "angle {angle}"); } } @@ -278,11 +267,11 @@ fn revolve_with_an_edge_on_the_axis() { let got = origins(&partial); assert_eq!(got, expected_revolution(&partial, &r)); assert_eq!(got.len(), 5); - // A full turn: the radial segments 0 and 2 sweep discs, segment 1 the cylinder (three parts). + // A full turn: the radial segments 0 and 2 sweep discs, segment 1 the cylinder (one face). let full = crate::revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, TAU).unwrap().pop().unwrap(); let got = origins(&full); assert_eq!(got, expected_revolution(&full, &r)); - assert_eq!(got.iter().filter(|o| **o == [P(1)]).count(), 3); + assert_eq!(got.iter().filter(|o| **o == [P(1)]).count(), 1); assert_eq!(got.iter().filter(|o| **o == [P(0)] || **o == [P(2)]).count(), 2); // A cone: the slanted segment ends on the axis (the apex), the base disc. let tri = Region2 { outer: Loop2::polygon(&[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(0.0, 8.0)]), holes: vec![] }; @@ -292,7 +281,7 @@ fn revolve_with_an_edge_on_the_axis() { let turned = Region2 { outer: rotated(&tri.outer.reversed(), 1), holes: vec![] }; let cone = crate::revolve(&SIDE, std::slice::from_ref(&turned), Vec2::ZERO, Vec2::Y, TAU).unwrap().pop().unwrap(); assert_eq!(origins(&cone), expected_revolution(&cone, &turned)); - // A half disc: a sphere, every patch from the arc (segment 1 here). + // A half disc: a sphere, its one face from the arc (segment 1 here). let half = Region2 { outer: Loop2 { segs: vec![ @@ -303,7 +292,7 @@ fn revolve_with_an_edge_on_the_axis() { holes: vec![], }; let ball = crate::revolve(&SIDE, std::slice::from_ref(&half), Vec2::ZERO, Vec2::Y, TAU).unwrap().pop().unwrap(); - assert_eq!(origins(&ball), vec![vec![P(1)]; 6]); + assert_eq!(origins(&ball), vec![vec![P(1)]]); } #[test] @@ -439,13 +428,13 @@ fn check_sweep(b: &Body, plane: &Plane, r: &Region2, faces_per_segment: Option = (0..=40) .map(|i| { @@ -468,7 +457,8 @@ fn sweeps_along_paths() { check_sweep(&b, &side, &ring, Some(1)); } -/// Kept faces are their origins, unchanged; each edge an operand still owns is that edge. +/// Kept faces are their origins, unchanged; each edge an operand still owns is that edge (a new +/// edge, where two faces meet, has a Meet origin instead). fn check_kept(result: &Body, input: &Body) { let h = result.history().unwrap(); h.check(result, &[input]).unwrap(); @@ -482,7 +472,11 @@ fn check_kept(result: &Body, input: &Body) { let mut owned = 0; for (e, p) in re.iter().zip(&h.edges) { for o in &p.origins { - let crate::history::EdgeOrigin::Edge { operand: 0, edge } = o else { panic!("{o:?}") }; + let edge = match o { + crate::history::EdgeOrigin::Edge { operand: 0, edge } => edge, + crate::history::EdgeOrigin::Meet { .. } => continue, + _ => panic!("{o:?}"), + }; assert!(e.mid.dist(ie[*edge].mid) < 1e-6, "edge {}", e.index); owned += 1; } @@ -506,12 +500,14 @@ fn thicken_reports_copies_offsets_and_walls() { let h = t.history().unwrap(); assert_eq!(h.faces[0].origins, [FaceOrigin::Face { operand: 0, face: 0 }]); assert_eq!(h.faces[1].origins, [FaceOrigin::Offset { operand: 0, face: 0 }]); - let free: Vec = (0..half.edge_count()).collect(); + // A wall along each free edge of the sheet: the side's two rims, not its seam (an edge the + // one face meets itself along, no boundary). + let free: Vec = (0..half.edge_count()).filter(|e| half.record().edges[*e].uses.len() == 1).collect(); for (i, f) in h.faces.iter().enumerate().skip(2) { let [FaceOrigin::Edge { operand: 0, edge }] = f.origins.as_slice() else { panic!("{f:?}") }; assert_eq!(*edge, nearest_edge(&t, i, &half, &free)); } - assert_eq!(h.faces.len(), 2 + half.edge_count()); + assert_eq!(h.faces.len(), 2 + free.len()); } #[test] diff --git a/crates/kernel/src/repair.rs b/crates/kernel/src/repair.rs new file mode 100644 index 000000000..348ae3898 --- /dev/null +++ b/crates/kernel/src/repair.rs @@ -0,0 +1,588 @@ +//! Repair Part (#8371): a part SMLib refuses, or an open part that should be a solid, made into +//! one SMLib takes, saying what changed face by face. In order: +//! +//! 1. A face SMLib refuses on its own is rebuilt from its own surface, its geometry unchanged: a +//! cylinder, cone, sphere or torus face on a NURBS form SMLib rejects goes as the analytic +//! surface it is, which SMLib parameterises on its own form (the form's control net is the +//! import's construction; the surface it stands for is the label's, exactly). +//! 2. Free edges that pair up within `gap` (a sliver between two faces that should meet) are sewn +//! by SMLib's stitch, which gives each edge it glues its own tolerance from that pair's gap +//! (`SmBrep::GlueEdgesGeneral`: at least twice the gap); the body's tolerance, and every other +//! edge's, stays as it was. +//! 3. A loop of free edges no pair explains is a missing face: Patch on that loop is offered (and +//! made, and sewn in, when asked), planar only where the faces around it are that plane; where +//! they are curved the patch meets them tangent (G1). Extending the neighbours is not done. +//! +//! Nothing is moved: a face rebuilt keeps its surface, a sewn edge keeps its curve (SMLib keeps +//! one of the pair), a patch is a new face. What was done comes back in [`RepairReport`]. + +use solidcraft_geom::Vec3; +use solidcraft_geom::brep::eval::CurveEval; +use solidcraft_geom::brep::{self as b, Brep}; + +use crate::body::{Body, SurfaceKind}; +use crate::{Continuity, KernelError, Result}; + +/// Most free edges paired against each other (each against every other near it). +const MAX_FREE_EDGES: usize = 20_000; +/// Most faces sent into SMLib one by one to find the ones it refuses. +const MAX_FACE_PROBES: usize = 20_000; +/// Points along an edge where its distance to its partner is measured. +const GAP_SAMPLES: usize = 16; +/// SMLib's check tests that bound an item's tolerance by the body's (`SmBrep::AssertValid` #5, +/// #6: face; #59: edge, under 1000 times the body's; #82: vertex). An edge sewn across a gap +/// carries that gap; the body's tolerance is not raised to cover it, so these may fail on sewn +/// items, as they already fail on an import's edges that lie off their faces by more. +const TOLERANCE_BOUND_TESTS: [u32; 4] = [5, 6, 59, 82]; + +/// What a repair may do. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RepairOptions { + /// The widest gap between two free edges that is sewn, mm (> 0). + pub gap: f64, + /// Patch the loops of free edges no pair explains (missing faces), and sew the patches in. + pub patch_holes: bool, +} + +/// A face rebuilt so SMLib takes it. +#[derive(Clone, Debug, PartialEq)] +pub struct RebuiltFace { + /// Its index in the body before the repair. + pub face: usize, + pub surface: SurfaceKind, + /// Why SMLib refused it before. + pub why: String, +} + +/// A face SMLib refuses that the repair could not rebuild. +#[derive(Clone, Debug, PartialEq)] +pub struct RefusedFace { + pub face: usize, + pub surface: SurfaceKind, + pub why: String, +} + +/// Two free edges sewn into one. +#[derive(Clone, Debug, PartialEq)] +pub struct SewnGap { + /// The faces on either side, by index before the repair. + pub faces: [usize; 2], + /// The widest distance between the two edges, mm. + pub gap: f64, + /// A point halfway along the first edge. + pub at: Vec3, +} + +/// A loop of free edges no pair explains: a face is missing there. +#[derive(Clone, Debug, PartialEq)] +pub struct Hole { + /// The faces around it, by index before the repair. + pub faces: Vec, + /// A point halfway along each of its edges: Patch's `edges`. + pub edges: Vec, + /// How a patch meets the faces around it: G0 (the plane they lie in) or G1 (curved neighbours). + pub continuity: Continuity, + /// The patch was made and sewn in. + pub patched: bool, + /// Why it was not, when it was asked for. + pub why: Option, +} + +/// What a repair did. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RepairReport { + pub rebuilt: Vec, + pub refused: Vec, + pub sewn: Vec, + pub holes: Vec, + /// Faces before and after. + pub faces: [usize; 2], + /// The largest edge tolerance before and after, mm. + pub largest_edge_tolerance: [f64; 2], + /// The result is a closed solid. + pub closed: bool, + /// Whether SMLib takes the result as it is. + pub modelling: bool, +} + +impl RepairReport { + /// Whether the repair changed anything. + pub fn changed(&self) -> bool { + !self.rebuilt.is_empty() || !self.sewn.is_empty() || self.holes.iter().any(|h| h.patched) + } +} + +fn invalid(what: impl Into) -> KernelError { + KernelError::Invalid(what.into()) +} + +fn v3(p: [f64; 3]) -> Vec3 { + Vec3::new(p[0], p[1], p[2]) +} + +/// `body` repaired as the module says, with what was done. Refused (with why) when nothing +/// applies: SMLib takes it and it has no free edges, or its only free edges bound holes and +/// `patch_holes` is off (the report's holes are then in the message). +pub fn repair(body: &Body, opts: &RepairOptions) -> Result<(Body, RepairReport)> { + let _span = solidcraft_profile::span("kernel", "repair"); + body.require_brep("repair")?; + if !(opts.gap.is_finite() && opts.gap > 0.0 && opts.gap <= 1.0) { + return Err(invalid("the gap to sew must be more than 0 and at most 1 mm")); + } + let before = body.record(); + let mut report = + RepairReport { faces: [before.faces.len(), 0], largest_edge_tolerance: [largest_tolerance(before), 0.0], ..RepairReport::default() }; + + // 1. Faces SMLib refuses on their own, rebuilt from their surfaces. + let mut record = before.clone(); + if body.smlib().is_err() { + rebuild_refused(&mut record, &mut report)?; + } + let mut current = if report.rebuilt.is_empty() { body.clone() } else { Body::from_record(record)?.with_color(body.color()) }; + if !report.refused.is_empty() && current.smlib().is_err() { + // SMLib still refuses the part: nothing can be sewn or patched (both are SMLib's). The + // faces rebuilt are kept, and the report names the ones left. + let list: Vec = report.refused.iter().map(|r| format!("face {} ({:?}): {}", r.face + 1, r.surface, r.why)).collect(); + if report.rebuilt.is_empty() { + return Err(KernelError::Failed(format!("SMLib refuses faces the repair cannot rebuild: {}", list.join("; ")))); + } + let r = current.record(); + report.holes = loops_of(r, &free_edges(r)?).iter().map(|l| hole(r, l)).collect(); + report.faces[1] = r.faces.len(); + report.largest_edge_tolerance[1] = largest_tolerance(r); + report.closed = false; + report.modelling = false; + return Ok((current, report)); + } + + // 2. and 3. The free edges: pairs within the gap, and loops of the rest. + let free = free_edges(current.record())?; + let pairs = pair_up(current.record(), &free, opts.gap); + let paired: std::collections::HashSet = pairs.iter().flat_map(|p| [p.edges[0], p.edges[1]]).collect(); + let rest: Vec = free.iter().copied().filter(|e| !paired.contains(e)).collect(); + let loops = loops_of(current.record(), &rest); + for l in &loops { + report.holes.push(hole(current.record(), l)); + } + for p in &pairs { + report.sewn.push(SewnGap { faces: p.faces, gap: p.gap, at: p.at }); + } + if !pairs.is_empty() { + let widest = pairs.iter().map(|p| p.gap).fold(0.0, f64::max); + // SMLib glues the lamina pairs within the stitch tolerance: just past the widest pair, so + // each of them glues and nothing farther apart does. + let tol = (widest * 1.05).max(current.record().tolerance * 2.0); + current = crate::surfaces::stitch_no_worse(&[¤t], tol, &TOLERANCE_BOUND_TESTS)?; + } + if opts.patch_holes && !report.holes.is_empty() { + current = patch_holes(current, &mut report.holes)?; + } + if !report.changed() { + let holes: Vec = report + .holes + .iter() + .map(|h| { + format!( + "a loop of {} edges around faces {}", + h.edges.len(), + h.faces.iter().map(|f| (f + 1).to_string()).collect::>().join(", ") + ) + }) + .collect(); + return Err(invalid(if holes.is_empty() { + "nothing to repair: SMLib takes the part and it has no gaps or holes".to_string() + } else { + format!("nothing sewn: the free edges bound holes ({}); patch them to close the part", holes.join("; ")) + })); + } + let after = current.record(); + report.faces[1] = after.faces.len(); + report.largest_edge_tolerance[1] = largest_tolerance(after); + report.closed = !after.faces.is_empty() && after.edges.iter().all(|e| e.uses.len() >= 2); + report.modelling = current.smlib().is_ok(); + Ok((current, report)) +} + +fn largest_tolerance(r: &Brep) -> f64 { + r.edges.iter().map(|e| e.tolerance).fold(r.tolerance, f64::max) +} + +// ---- 1. Faces SMLib refuses ------------------------------------------------------------- + +/// Whether SMLib takes face `f` of `r` on its own; `Err` with SMLib's reason when it does not. +fn alone(r: &Brep, f: usize) -> Result> { + let one = crate::surfaces::Parts::of(r, &[(f, false)])?.canonical()?; + Ok(solidcraft_smlib::Brep::from_record(&one.brep, true).map(|_| ()).map_err(|e| e.to_string())) +} + +/// Every face of `record` SMLib refuses on its own, rebuilt where its surface allows (into +/// `report.rebuilt`), else listed (`report.refused`). +fn rebuild_refused(record: &mut Brep, report: &mut RepairReport) -> Result<()> { + if record.faces.len() > MAX_FACE_PROBES { + return Err(KernelError::TooLarge(format!("a part of {} faces (the repair looks at most {MAX_FACE_PROBES})", record.faces.len()))); + } + for f in 0..record.faces.len() { + let Err(why) = alone(record, f)? else { continue }; + let Some(face) = record.faces.get(f) else { continue }; + let surface = SurfaceKind::of(&face.surface); + match rebuilt_face(record, f) { + Ok(Some(face)) => { + let mut trial = record.clone(); + if let Some(slot) = trial.faces.get_mut(f) { + *slot = face; + } + match alone(&trial, f)? { + Ok(()) => { + *record = trial; + report.rebuilt.push(RebuiltFace { face: f, surface, why }); + } + Err(still) => { + report.refused.push(RefusedFace { face: f, surface, why: format!("{why}; rebuilt on its own surface, still: {still}") }) + } + } + } + Ok(None) => report.refused.push(RefusedFace { face: f, surface, why }), + Err(e) => report.refused.push(RefusedFace { face: f, surface, why: format!("{why}; not rebuilt: {e}") }), + } + } + Ok(()) +} + +/// Face `f` of `r` rebuilt on its own surface: a cylinder, cone, sphere or torus face on a +/// NURBS form of the surface laid on arcs from where the face starts +/// ([`b::form::surface_on_own_arcs`]) instead of its frame's quarter grid, the same surface +/// exactly, with SMLib's own trims of the face's edges on it (`SmlibTrims`, as the import makes the +/// trims it has no closed form for). The face's edges and loops stay as they were. `None` for a +/// face on another surface. +fn rebuilt_face(r: &Brep, f: usize) -> Result> { + use b::pcurve::{TrimEdge, TrimFace, TrimUse, Trims}; + let face = r.faces.get(f).ok_or_else(|| invalid(format!("no face {f}")))?; + if !matches!(face.surface, b::Surface::Cylinder { .. } | b::Surface::Cone { .. } | b::Surface::Sphere { .. } | b::Surface::Torus { .. }) { + return Ok(None); + } + // The face's edges and vertices, numbered here as the trim face takes them. + let mut local: Vec = Vec::new(); + let mut vertices: Vec = Vec::new(); + let mut loops = Vec::with_capacity(face.loops.len()); + let mut boundary = Vec::with_capacity(face.loops.len()); + for l in &face.loops { + let b::Loop::Edges { edges } = l else { return Ok(None) }; + let mut uses = Vec::with_capacity(edges.len()); + let mut lb = Vec::with_capacity(edges.len()); + for u in edges { + let e = r.edges.get(u.edge as usize).ok_or_else(|| invalid(format!("no edge {}", u.edge)))?; + let k = match local.iter().position(|&x| x == u.edge) { + Some(k) => k, + None => { + local.push(u.edge); + local.len() - 1 + } + }; + uses.push(TrimUse { edge: u32::try_from(k).map_err(|_| invalid("too many edges"))?, forward: u.forward, pcurve: None }); + lb.push((&e.curve, e.interval, u.forward)); + } + loops.push(uses); + boundary.push(lb); + } + let mut edges = Vec::with_capacity(local.len()); + for &e in &local { + let edge = r.edges.get(e as usize).ok_or_else(|| invalid(format!("no edge {e}")))?; + let mut ends = [0u32; 2]; + for (end, v) in ends.iter_mut().zip(edge.vertices) { + let k = match vertices.iter().position(|&x| x == v) { + Some(k) => k, + None => { + vertices.push(v); + vertices.len() - 1 + } + }; + *end = u32::try_from(k).map_err(|_| invalid("too many vertices"))?; + } + edges.push(TrimEdge { curve: &edge.curve, nurbs: edge.nurbs.as_ref(), interval: edge.interval, vertices: ends, tolerance: edge.tolerance }); + } + let points = vertices + .iter() + .map(|&v| r.vertices.get(v as usize).map(|v| v.point).ok_or_else(|| invalid(format!("no vertex {v}")))) + .collect::>>()?; + let extent = b::form::extent(&face.surface, &boundary).ok_or_else(|| invalid("its boundary does not lie on its surface"))?; + let (form, domain) = b::form::surface_on_own_arcs( + &face.surface, + extent, + local.iter().filter_map(|&e| r.edges.get(e as usize)).map(|e| e.tolerance).fold(r.tolerance, f64::max), + ) + .ok_or_else(|| invalid("no NURBS form of its surface over its boundary"))?; + let trim = TrimFace { surface: &face.surface, nurbs: Some(&form), domain, edges, vertices: points, loops, tolerance: r.tolerance }; + let pcurves = solidcraft_smlib::pcurves::SmlibTrims.trims(&trim).map_err(KernelError::Failed)?; + let mut out = face.clone(); + out.nurbs = Some(form); + out.domain = domain; + let mut it = pcurves.into_iter(); + for l in &mut out.loops { + let b::Loop::Edges { edges } = l else { continue }; + let pcs = it.next().ok_or_else(|| invalid("pcurves of a loop"))?; + for (u, pc) in edges.iter_mut().zip(pcs) { + u.pcurve = pc; + } + } + Ok(Some(out)) +} + +// ---- 2. Gaps ---------------------------------------------------------------------------- + +/// The edges of `r` only one face uses. +fn free_edges(r: &Brep) -> Result> { + let free: Vec = + (0..r.edges.len()).filter(|&e| r.edges.get(e).is_some_and(|e| e.uses.len() == 1)).filter_map(|e| u32::try_from(e).ok()).collect(); + if free.len() > MAX_FREE_EDGES { + return Err(KernelError::TooLarge(format!("a part with {} free edges (the repair pairs at most {MAX_FREE_EDGES})", free.len()))); + } + Ok(free) +} + +/// Two free edges within the gap of each other. +struct Pair { + edges: [u32; 2], + faces: [usize; 2], + gap: f64, + at: Vec3, +} + +/// An edge's points, evenly in its parameter (ends included). +fn points(r: &Brep, e: u32, n: usize) -> Vec { + let Some(edge) = r.edges.get(e as usize) else { return Vec::new() }; + let Ok(c) = CurveEval::new(edge.parameters()) else { return Vec::new() }; + let [t0, t1] = edge.interval; + (0..=n).filter_map(|k| c.point(t0 + (t1 - t0) * k as f64 / n as f64)).collect() +} + +/// The widest distance from a point of edge `a` to edge `b` (each of `a`'s points to its nearest +/// point on `b`), `None` where `b` cannot be evaluated. +fn reach(r: &Brep, a: &[Vec3], b: u32) -> Option { + let edge = r.edges.get(b as usize)?; + let c = CurveEval::new(edge.parameters()).ok()?; + let ends = [c.point(edge.interval[0])?, c.point(edge.interval[1])?]; + a.iter() + .map(|p| { + let inside = crate::surfaces::nearest_parameter(&c, edge.interval, *p).map_or(f64::INFINITY, |(_, d)| d); + inside.min(ends[0].dist(*p)).min(ends[1].dist(*p)) + }) + .try_fold(0.0f64, |m, d| d.is_finite().then_some(m.max(d))) +} + +/// The free edges that pair up within `gap`, both ways (each edge's every point near the other), +/// each edge in at most one pair: the closest pairs first. An edge of a face with itself is not +/// a gap. +fn pair_up(r: &Brep, free: &[u32], gap: f64) -> Vec { + let samples: Vec> = free.iter().map(|&e| points(r, e, GAP_SAMPLES)).collect(); + let boxes: Vec> = samples + .iter() + .map(|s| { + let first = *s.first()?; + Some(s.iter().fold((first, first), |(lo, hi), p| (lo.min(*p), hi.max(*p)))) + }) + .collect(); + let face = |e: u32| r.edges.get(e as usize).and_then(|e| e.uses.first()).map(|u| u.face as usize); + let mut candidates = Vec::new(); + for i in 0..free.len() { + for j in i + 1..free.len() { + let (Some(&a), Some(&b)) = (free.get(i), free.get(j)) else { continue }; + let (Some(Some((alo, ahi))), Some(Some((blo, bhi)))) = (boxes.get(i), boxes.get(j)) else { continue }; + let apart = (blo.x - ahi.x).max(alo.x - bhi.x).max(blo.y - ahi.y).max(alo.y - bhi.y).max(blo.z - ahi.z).max(alo.z - bhi.z); + if apart > gap || face(a) == face(b) { + continue; + } + let (Some(sa), Some(sb)) = (samples.get(i), samples.get(j)) else { continue }; + let Some(d) = reach(r, sa, b).zip(reach(r, sb, a)).map(|(x, y)| x.max(y)) else { continue }; + if d <= gap { + candidates.push((d, a, b)); + } + } + } + candidates.sort_by(|x, y| x.0.total_cmp(&y.0)); + let mut taken = std::collections::HashSet::new(); + let mut out = Vec::new(); + for (d, a, b) in candidates { + if taken.contains(&a) || taken.contains(&b) { + continue; + } + let (Some(fa), Some(fb)) = (face(a), face(b)) else { continue }; + taken.insert(a); + taken.insert(b); + let at = points(r, a, 2).get(1).copied().unwrap_or(Vec3::ZERO); + out.push(Pair { edges: [a, b], faces: [fa, fb], gap: d, at }); + } + out +} + +// ---- 3. Holes --------------------------------------------------------------------------- + +/// The edges `rest` of `r` in chains joined at shared vertices: each a loop around a hole (or an +/// open run where the boundary does not close). +fn loops_of(r: &Brep, rest: &[u32]) -> Vec> { + let mut by_vertex: std::collections::HashMap> = std::collections::HashMap::new(); + for &e in rest { + if let Some(edge) = r.edges.get(e as usize) { + for v in edge.vertices { + by_vertex.entry(v).or_default().push(e); + } + } + } + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::new(); + for &start in rest { + if !seen.insert(start) { + continue; + } + let mut chain = vec![start]; + let mut stack = vec![start]; + while let Some(e) = stack.pop() { + let Some(edge) = r.edges.get(e as usize) else { continue }; + for v in edge.vertices { + for &n in by_vertex.get(&v).into_iter().flatten() { + if seen.insert(n) { + chain.push(n); + stack.push(n); + } + } + } + } + out.push(chain); + } + out +} + +/// The hole a loop of free edges bounds, and how a patch would meet the faces around it: flat +/// (the loop's plane) when the loop is planar and every face around it is a plane, else tangent +/// to them. +fn hole(r: &Brep, edges: &[u32]) -> Hole { + let mut faces: Vec = edges.iter().filter_map(|&e| r.edges.get(e as usize)?.uses.first().map(|u| u.face as usize)).collect(); + faces.sort_unstable(); + faces.dedup(); + let at: Vec = edges.iter().filter_map(|&e| points(r, e, 2).get(1).copied()).collect(); + let along: Vec = edges.iter().flat_map(|&e| points(r, e, 8)).collect(); + let tol = edges.iter().filter_map(|&e| r.edges.get(e as usize)).map(|e| e.tolerance).fold(r.tolerance, f64::max); + let planes = faces.iter().all(|&f| r.faces.get(f).is_some_and(|face| plane_of(&face.surface).is_some())); + let flat = planes && plane_through(&along).is_some_and(|(o, n)| along.iter().all(|p| (*p - o).dot(n).abs() <= tol)); + Hole { faces, edges: at, continuity: if flat { Continuity::G0 } else { Continuity::G1 }, patched: false, why: None } +} + +/// The plane of a closed polygon's points (Newell's normal, through their centroid); `None` +/// where they enclose no area. +fn plane_through(pts: &[Vec3]) -> Option<(Vec3, Vec3)> { + let n = pts.len(); + if n < 3 { + return None; + } + let c = pts.iter().fold(Vec3::ZERO, |s, p| s + *p) * (1.0 / n as f64); + let normal = (0..n).filter_map(|i| Some((pts.get(i)?, pts.get((i + 1) % n)?))).fold(Vec3::ZERO, |s, (p, q)| s + (*p - c).cross(*q - c)); + Some((c, normal.normalized()?)) +} + +/// A plane surface's point and unit normal. +fn plane_of(s: &b::Surface) -> Option<(Vec3, Vec3)> { + let (o, u, v) = match s { + b::Surface::Plane { origin, u_axis, v_axis } => (v3(*origin), v3(*u_axis), v3(*v_axis)), + b::Surface::PlaneThrough { origin, u_point, v_point } => (v3(*origin), v3(*u_point) - v3(*origin), v3(*v_point) - v3(*origin)), + _ => return None, + }; + Some((o, u.cross(v).normalized()?)) +} + +/// `body` with each hole patched (Patch on its loop, at its continuity) and the patches sewn in +/// along the hole's own edges; a hole whose patch fails keeps why. +fn patch_holes(body: Body, holes: &mut [Hole]) -> Result { + let mut patches = Vec::new(); + let mut tol = body.record().tolerance; + for h in holes.iter_mut() { + let spec = crate::PatchSpec { continuity: h.continuity, ..crate::PatchSpec::default() }; + match crate::patch_edges_with(&body, &h.edges, &spec) { + Ok(p) => { + tol = tol.max(largest_tolerance(p.record())); + patches.push(p); + h.patched = true; + } + Err(e) => h.why = Some(e.to_string()), + } + } + if patches.is_empty() { + return Ok(body); + } + let mut all: Vec<&Body> = vec![&body]; + all.extend(patches.iter()); + // A patch's edges are the hole's own: they meet within those edges' tolerances. + crate::surfaces::stitch_no_worse(&all, tol * 2.0, &TOLERANCE_BOUND_TESTS) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{box_solid, copy_faces, measure, stitch, transform}; + + /// The six faces of a 10 × 20 × 30 box, each its own surface body: bottom, top, then the sides. + fn box_faces() -> Vec { + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); + [[5.0, 10.0, 0.0], [5.0, 10.0, 30.0], [0.0, 10.0, 15.0], [10.0, 10.0, 15.0], [5.0, 0.0, 15.0], [5.0, 20.0, 15.0]] + .iter() + .map(|p| copy_faces(&b, &[v3(*p)]).unwrap()) + .collect() + } + + /// The box without its top: an open part with a hole the four sides and their plane bound. + fn open_box(faces: &[Body]) -> Body { + stitch(&[&faces[0], &faces[2], &faces[3], &faces[4], &faces[5]], 0.0).unwrap() + } + + #[test] + fn a_gap_between_faces_is_sewn_each_sewn_edge_carrying_its_gap() { + let faces = box_faces(); + let open = open_box(&faces); + // The lid 0.05 mm above the walls: one part of six faces whose top edges pair up 0.05 apart. + let lid = transform(&faces[1], Vec3::new(0.0, 0.0, 0.05), Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap(); + let part = stitch(&[&open, &lid], 1e-6).unwrap(); + assert_eq!(part.record().edges.iter().filter(|e| e.uses.len() == 1).count(), 8, "the gap's edges are free"); + let opts = RepairOptions { gap: 0.1, patch_holes: false }; + let (fixed, report) = repair(&part, &opts).unwrap(); + assert_eq!(report.sewn.len(), 4, "{report:?}"); + assert!(report.sewn.iter().all(|g| (g.gap - 0.05).abs() < 1e-6), "{report:?}"); + assert!(report.holes.is_empty() && report.rebuilt.is_empty()); + assert!(report.closed && report.modelling, "{report:?}"); + assert_eq!(report.faces, [6, 6]); + let volume = measure(&fixed).unwrap().volume; + assert!((6000.0..=6010.0).contains(&volume), "{volume}"); + // Only the four sewn edges carry the gap; the body's tolerance and every other edge's + // stay SMLib's own. + let r = fixed.record(); + assert_eq!(r.tolerance, part.record().tolerance); + let loose: Vec = r.edges.iter().map(|e| e.tolerance).filter(|t| *t > 0.01).collect(); + assert_eq!(loose.len(), 4, "{loose:?}"); + assert!(loose.iter().all(|t| *t >= 0.05 && *t <= 0.25), "{loose:?}"); + // A gap wider than asked for is not sewn: the free edges then bound holes. + let err = repair(&part, &RepairOptions { gap: 0.01, patch_holes: false }).unwrap_err().to_string(); + assert!(err.contains("nothing sewn"), "{err}"); + } + + #[test] + fn a_hole_is_offered_then_patched_flat_in_the_plane_around_it() { + let open = open_box(&box_faces()); + let opts = RepairOptions { gap: 0.2, patch_holes: false }; + let err = repair(&open, &opts).unwrap_err().to_string(); + assert!(err.contains("a loop of 4 edges"), "{err}"); + // Planar walls around a planar loop: the patch is the loop's plane. + let (fixed, report) = repair(&open, &RepairOptions { patch_holes: true, ..opts }).unwrap(); + let [hole] = report.holes.as_slice() else { panic!("{report:?}") }; + assert_eq!((hole.faces.len(), hole.edges.len(), hole.continuity, hole.patched), (4, 4, Continuity::G0, true), "{hole:?}"); + assert!(report.closed && report.modelling, "{report:?}"); + assert_eq!(report.faces, [5, 6]); + assert!((measure(&fixed).unwrap().volume - 6000.0).abs() < 1e-6); + } + + #[test] + fn a_part_with_nothing_to_repair_is_refused_with_why() { + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap(); + let err = repair(&b, &RepairOptions { gap: 0.2, patch_holes: true }).unwrap_err().to_string(); + assert!(err.contains("nothing to repair"), "{err}"); + for gap in [0.0, -1.0, 2.0, f64::NAN, f64::INFINITY] { + assert!(repair(&b, &RepairOptions { gap, patch_holes: false }).is_err(), "{gap}"); + } + } +} diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rs index 7a7a0199c..81a449426 100644 --- a/crates/kernel/src/sew.rs +++ b/crates/kernel/src/sew.rs @@ -286,7 +286,7 @@ impl Builder { } }; let id = u32::try_from(self.edges.len()).map_err(|_| KernelError::Invalid("sew: edge budget exceeded".into()))?; - self.edges.push(PartEdge { curve, interval, vertices: [va, vb] }); + self.edges.push(PartEdge { nurbs: None, curve, interval, vertices: [va, vb] }); self.by_key.insert((ka, fa, kb, fb, mid, sheet), id); Ok((id, true)) } @@ -1303,6 +1303,10 @@ pub(crate) struct PartUse { pub(crate) struct PartEdge { pub curve: b::Curve, + /// The NURBS form the edge is parameterised on, as a record edge keeps it + /// ([`b::Edge::nurbs`]): given, `interval` is on it and `curve` only says what the edge is, + /// so an edge taken from a record goes back as that same edge. + pub nurbs: Option, pub interval: [f64; 2], pub vertices: [u32; 2], } @@ -1366,8 +1370,8 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { g }; // Each edge's label and NURBS form (`form::edge`): a circle about a revolved face's axis on - // that face's frame, so its form lies on the face's quarter grid; an edge the caller gave a - // pcurve for keeps the parameter that pcurve is on. + // that face's frame, so its form lies on the face's quarter grid; an edge given with its form + // keeps it, and an edge the caller gave a pcurve for keeps the parameter that pcurve is on. let mut frames_of: Vec> = vec![Vec::new(); edges.len()]; for f in &faces { let Some(frame) = b::form::frame_of(&f.surface) else { continue }; @@ -1380,6 +1384,13 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result { let mut labels: Vec<(b::Curve, [f64; 2])> = Vec::with_capacity(edges.len()); let mut forms: Vec> = Vec::with_capacity(edges.len()); for ((e, frames), given) in edges.iter().zip(&frames_of).zip(&given_on) { + if let Some(form) = &e.nurbs { + let on_label = + b::curve_interval(&e.curve, Some(form), e.interval).ok_or_else(|| fail("an edge's NURBS form does not evaluate".into()))?; + labels.push((e.curve.clone(), on_label)); + forms.push(Some((form.clone(), e.interval))); + continue; + } if *given { labels.push((e.curve.clone(), e.interval)); forms.push(None); diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rs index bc26f505b..008b981ac 100644 --- a/crates/kernel/src/smlib_sweeps.rs +++ b/crates/kernel/src/smlib_sweeps.rs @@ -71,8 +71,8 @@ pub(crate) struct Draft { } pub(crate) use imp::{ - body_from_record, curve, extrude, face_section, loft, loft_rails, loft_to_point, path_curve, project_onto_face, revolve, screw, screw_radial, - sphere, sweep, sweep_controlled, + body_from_record, curve, extrude, extrude_drafted_with_holes, face_section, loft, loft_rails, loft_to_point, path_curve, project_onto_face, + revolve, screw, screw_radial, sphere, sweep, sweep_controlled, }; /// Refuses what no SMLib sweep does, before any work. @@ -272,7 +272,17 @@ mod imp { let m = body.mesh(&crate::MeshTolerance::chord(mesh_tol))?; let faces = face_tris(&m); let n = body.face_count(); - let flat_tol = size * 1e-5 + 1e-9; + // A cap's points lie on its plane to the evaluation's precision. Sized to the body, the + // flatness tolerance can exceed the gap between parallel start and end planes (a box + // 0.1 µm thick in a 14 mm body), which would put each cap in both: it stays under a + // quarter of that gap. Planes that coincide (the ends of a half turn) are told apart by + // the profile's edges instead. + let gap = end + .filter(|e| e.normal().cross(start.normal()).len() < 1e-9) + .map(|e| start.height(e.origin).abs()) + .filter(|g| *g > size * 1e-9) + .unwrap_or(f64::INFINITY); + let flat_tol = (size * 1e-5 + 1e-9).min(0.25 * gap); let near = 3.0 * mesh_tol + flat_tol; let flat = |f: usize, pl: &Plane| { faces.get(f).is_some_and(|ft| !ft.tris.is_empty() && ft.tris.iter().all(|(t, _)| t.iter().all(|q| pl.height(*q).abs() <= flat_tol))) @@ -289,12 +299,22 @@ mod imp { let end_cap: Vec = (0..n).map(|f| end.is_some_and(|e| flat(f, e))).collect(); let cap = |f: usize| start_cap.get(f).copied().unwrap_or(false) || end_cap.get(f).copied().unwrap_or(false); let mut swept: Vec> = vec![BTreeSet::new(); n]; - for (poly, fs) in m.edges.iter().zip(&m.edge_faces) { - if poly.len() < 2 || !poly.iter().all(|q| start.height(*q).abs() <= flat_tol) { - continue; - } - for s in edges { - if poly.windows(2).any(|w| s.at.dist_to_segment(w[0], w[1]) <= near) { + // Each seed lies on its own piece's edge (within the mesh's sag on a curve); `near` is + // sized to the body, so on a side shorter than it (a 0.3 mm wall of a 1 m label) the + // neighbours' edges are near too. The seed marks only the edges nearest it: the one it + // lies on, or both pieces of an edge split at its middle. + let start_edges: Vec<(&Vec, &Vec)> = m + .edges + .iter() + .zip(&m.edge_faces) + .filter(|(poly, _)| poly.len() >= 2 && poly.iter().all(|q| start.height(*q).abs() <= flat_tol)) + .collect(); + for s in edges { + let dist = |poly: &[Vec3]| poly.windows(2).map(|w| s.at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min); + let ds: Vec = start_edges.iter().map(|(poly, _)| dist(poly)).collect(); + let nearest = ds.iter().copied().fold(f64::INFINITY, f64::min); + for ((_, fs), d) in start_edges.iter().zip(&ds) { + if *d <= near && *d <= nearest + flat_tol { for f in fs.iter().map(|f| *f as usize).filter(|f| !cap(*f)) { if let Some(set) = swept.get_mut(f) { set.insert(s.piece); @@ -427,6 +447,79 @@ mod imp { with_history(body, &roles, pieces) } + /// The solid `pieces` (one closed loop) on `plane` sweep, moved `from` along its normal and + /// drafted `d` over `distance` along `sign` × the normal, as [`extrude`] builds it, without + /// its roles. + fn drafted_loop(plane: &Plane, pieces: &[Piece], from: f64, distance: f64, sign: f64, d: Draft) -> Result { + let base = plane.offset(from); + let n = plane.x.cross(plane.y).normalized().ok_or_else(|| KernelError::Invalid("profile plane".into()))?; + let dir = n * sign.signum(); + if d.foot > 0.0 { + if !(d.foot < distance) { + return Err(KernelError::Invalid(format!("taper foot = {}", d.foot))); + } + let knee = plane.offset(from + sign.signum() * d.foot); + let lean = -(distance * d.taper.tan() / (distance - d.foot)).atan(); + let prism = + Brep::extrude(&curves(&base, pieces)?, p(dir), d.foot, 0.0, DraftCorner::default(), true).map_err(|e| failed("extrude", e))?; + let slope = + Brep::extrude(&curves(&knee, pieces)?, p(dir), distance - d.foot, lean, corner(d.corner), true).map_err(|e| failed("extrude", e))?; + let brep = prism.boolean(&slope, solidcraft_smlib::BooleanOp::Union).map_err(|e| failed("extrude", e))?; + return brep.ok_or_else(|| failed("extrude", "nothing is left")); + } + Brep::extrude(&curves(&base, pieces)?, p(dir), distance, -d.taper, corner(d.corner), true).map_err(|e| failed("extrude", e)) + } + + /// A drafted extrusion of a region with holes: SMLib's draft extrusion takes one loop, so the + /// outer loop is drafted and each hole, turned counter-clockwise, is drafted the other way + /// and cut from it. Every wall leans by the taper on the material's side, as a single + /// drafted sweep would: a taper that narrows the outer boundary widens the holes. `outer` and + /// `holes` are the loops' pieces at `from` as [`extrude`] takes them, `all` the region's + /// pieces in their numbering (outer, then the holes as they bound the material), which the + /// walls' roles name. + pub(crate) fn extrude_drafted_with_holes( + plane: &Plane, + outer: &[Piece], + holes: &[Vec], + all: &[Piece], + from: f64, + distance: f64, + sign: f64, + draft: Draft, + ) -> Result { + let mut brep = drafted_loop(plane, outer, from, distance, sign, draft)?; + for h in holes { + let cutter = drafted_loop(plane, h, from, distance, sign, Draft { taper: -draft.taper, ..draft })?; + brep = brep + .boolean(&cutter, solidcraft_smlib::BooleanOp::Subtract) + .map_err(|e| failed("extrude", e))? + .ok_or_else(|| KernelError::Invalid("the draft leaves nothing of the profile".into()))?; + } + let body = body_of(&brep, "extrude")?; + let base = plane.offset(from); + let top = plane.offset(from + sign.signum() * distance); + let low = roles(&body, &base, Some(&top), &seeds(&base, all, |q| q), &[], false)?; + let roles: Vec = if draft.foot > 0.0 { + // The sloping walls stand on their edges at the knee, as in [`extrude`]. + let knee = plane.offset(from + sign.signum() * draft.foot); + let high = roles(&body, &knee, Some(&top), &seeds(&knee, all, |q| q), &[], false)?; + low.into_iter() + .zip(high) + .map(|(a, b)| match (a, b) { + (Role::Wall(mut x), Role::Wall(y)) => { + x.extend(y); + Role::Wall(x) + } + (Role::Unknown, w @ Role::Wall(_)) => w, + (a, _) => a, + }) + .collect() + } else { + low + }; + with_history(body, &roles, all) + } + /// The construction sources of a straight extrusion's faces along the normal of `sketch`, as /// [`crate::extrude`] gives them: each cap the region at its end (both caps found once /// each), each wall swept from one piece that piece as drawn, a line's with the wall's plane. @@ -531,13 +624,32 @@ mod imp { /// it when `translate`. SMLib's sweep follows a smooth path; at a corner (the direction /// jumping) the path is swept piece by piece ([`cornered`]). pub(crate) fn sweep(plane: &Plane, pieces: &[Piece], path: &[crate::PathSeg], translate: bool) -> Result { + if translate { + // Every segment's direction of travel, at its ends and between them. + let bad = || KernelError::Invalid("a path segment has no direction".into()); + let tangents = path + .iter() + .flat_map(|s| (0..=CROSSING_SAMPLES).map(move |i| seg_at(s, i as f64 / CROSSING_SAMPLES as f64).map(|(_, t)| t))) + .collect::>>() + .ok_or_else(bad)?; + crate::sweep_path::crossing_check(plane, &tangents)?; + } let runs = smooth_runs(path)?; if runs.len() > 1 { return cornered(plane, pieces, path, &runs, translate); } - let (brep, _) = swept(plane, pieces, path, translate)?; + let (brep, [_, middle, last]) = swept(plane, pieces, path, translate)?; let body = body_of(&brep, "sweep")?; - let roles = roles(&body, plane, None, &seeds(plane, pieces, |q| q), &[], true)?; + // The walls known by the profile carried half way (past the start's edges: a wall the + // start touches by no edge, as round a closed path, and walls along later path segments). + let inside = seeds(plane, pieces, |q| apply(&middle, q)); + let start = path.first().map(crate::PathSeg::start); + let end = path.last().map(seg_ends).transpose()?.map(|(_, b)| b); + let roles = match (start, end) { + // Round a closed path there are no caps, and the start holds seams only. + (Some(a), Some(b)) if a.dist(b) <= 1e-6 => roles(&body, &plane.offset(body.size().max(1e-9) * 10.0), None, &[], &inside, false)?, + _ => roles(&body, plane, Some(&placed(plane, &last)), &seeds(plane, pieces, |q| q), &inside, false)?, + }; with_history(body, &roles, pieces) } @@ -823,6 +935,8 @@ mod imp { /// Fewest and most stations of a sweep that twists, scales or follows rails. const MIN_STATIONS: usize = 16; + /// Directions of travel read along each path segment for the parallel sweep's crossing check. + const CROSSING_SAMPLES: usize = 32; const MAX_STATIONS: usize = 2048; /// The profile `region` on `plane` swept along the smooth `path` the way `ctl` asks: twisted, diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs index f6d809828..219c813a2 100644 --- a/crates/kernel/src/splitface.rs +++ b/crates/kernel/src/splitface.rs @@ -154,8 +154,9 @@ fn face_patch(body: &Body, face: usize) -> Result { let record = body.record(); let f = record.faces.get(face).ok_or_else(|| invalid(format!("the tool body has no face {face}")))?; let forward = body.face_forward(face); - // The surface's own parameter box, unbounded where it is. - let dom = SurfaceEval::new(f.parameters()).map_err(|e| invalid(format!("the split tool's surface: {e}")))?.domain(); + // The surface's own parameter box, unbounded where it is: of `surface` itself, not of its + // NURBS form (SMLib's cylinder is held on one, parameterised otherwise). + let dom = SurfaceEval::new(&f.surface).map_err(|e| invalid(format!("the split tool's surface: {e}")))?.domain(); let range = |k: usize| dom.range[k].map_or(ALL, |(a, b)| [a, b]); Ok(Patch { surface: f.surface.clone(), domain: [range(0), range(1)], flip: !forward }) } @@ -631,9 +632,14 @@ mod tests { assert!(n > c.face_count()); // The pieces stay apart; the cylinder's incidental seam pieces still join as before. assert_eq!(round_trip_faces(&cs), round_trip_faces(&c) + 1); - // Without the record the export joins the top's pieces again (as it does for pieces a - // boolean left). - assert_eq!(round_trip_faces(&s.clone().with_split_lines(None)), 6); + // Without the record (no operation drops it: only Split Face's own removal, which + // rebuilds without the split) the pieces are incidental: the file has what the body + // has, and the next operation joins them as it joins any pieces on one surface (SMLib's + // booleans at their end, the local modifiers through the heal). + let unrecorded = s.clone().with_split_lines(None); + assert_eq!(round_trip_faces(&unrecorded), unrecorded.face_count()); + let joined = crate::boolean_record::healed(&unrecorded).unwrap(); + assert_eq!((joined.face_count(), round_trip_faces(&joined)), (6, 6)); // A split after a split keeps both lines. let pl2 = Plane::new(Vec3::new(0.0, 12.0, 0.0), Vec3::X, Vec3::Z).unwrap(); let tops: Vec = @@ -655,12 +661,13 @@ mod tests { let m = measure(&s).unwrap(); // (Measured on meshes: curved faces agree to about 1e-4.) assert!(rel(m.volume, m0.volume) < 2e-4 && rel(m.area, m0.area) < 2e-4, "{} {} {} {}", m.volume, m0.volume, m.area, m0.area); - // The half side face splits at z = 5: a quarter and three quarters of its area. + // The side (one face round the whole turn) splits at z = 5: a quarter and three quarters + // of its area. let mut sides: Vec = s.faces(0.01).unwrap().iter().filter(|f| f.plane_normal.is_none()).map(|f| f.area).collect(); sides.sort_by(f64::total_cmp); - let half = std::f64::consts::PI * 10.0 * 20.0; - assert_eq!(sides.len(), 3); - assert!(rel(sides[0], half / 4.0) < 1e-3 && rel(sides[1], half * 0.75) < 1e-3 && rel(sides[2], half) < 1e-3, "{sides:?}"); + let whole = std::f64::consts::TAU * 10.0 * 20.0; + assert_eq!(sides.len(), 2); + assert!(rel(sides[0], whole / 4.0) < 1e-3 && rel(sides[1], whole * 0.75) < 1e-3, "{sides:?}"); assert!(s.face_count() > c.face_count()); // A smaller cylinder's side splits the top in a ring and a disc. let pin = cylinder(Vec3::ZERO, Vec3::Z, 4.0, 40.0).unwrap(); diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index ba1d39545..8b03229ed 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -88,6 +88,10 @@ pub struct StepImport { pub schema: String, /// FILE_NAME originating system. pub system: String, + /// FILE_NAME preprocessor version. + pub preprocessor: String, + /// FILE_DESCRIPTION text. + pub description: String, } /// What an import warning is about, so a window can word a summary of them (the warning's @@ -1330,7 +1334,16 @@ impl StepReading { return Err(KernelError::Failed(format!("STEP import: no bodies ({why})"))); } let bodies = std::mem::take(&mut rd.bodies); - Ok(StepImport { bodies, tree, warnings, report, schema: ex.schemas.join(", "), system: ex.originating_system.clone() }) + Ok(StepImport { + bodies, + tree, + warnings, + report, + schema: ex.schemas.join(", "), + system: ex.originating_system.clone(), + preprocessor: ex.preprocessor.clone(), + description: ex.description.clone(), + }) } /// [`Self::finish`], and the import is cached for the next read of the same text. diff --git a/crates/kernel/src/surface_kind.rs b/crates/kernel/src/surface_kind.rs index d0105ca49..94e65c7ac 100644 --- a/crates/kernel/src/surface_kind.rs +++ b/crates/kernel/src/surface_kind.rs @@ -87,11 +87,12 @@ pub fn edge_circle(b: &Body, edge: usize) -> Option { let [t0, t1] = e.interval; let (start, end) = (c.point(t0)?, c.point(t1)?); if let Curve::Circle { frame, radius } = &e.curve { - // The record's parameter is the angle about the frame's z: the edge runs counter-clockwise - // about it from its start to its end. + // The edge runs counter-clockwise about the frame's z from its start to its end, over the + // angles of its interval on the circle itself (a NURBS form is parameterised otherwise). let axis = Vec3::from(frame.x_axis).cross(Vec3::from(frame.y_axis)).unit()?; let closed = e.vertices[0] == e.vertices[1]; - let angle = if closed { std::f64::consts::TAU } else { (t1 - t0).min(std::f64::consts::TAU) }; + let [a0, a1] = e.curve_interval()?; + let angle = if closed { std::f64::consts::TAU } else { (a1 - a0).min(std::f64::consts::TAU) }; return Some(EdgeCircle { center: Vec3::from(frame.origin), axis, radius: *radius, start, end, angle }); } let tol = (b.size() * 1e-7).max(1e-9) * 100.0; diff --git a/crates/kernel/src/surface_offset.rs b/crates/kernel/src/surface_offset.rs index a87ef7bdd..cac421759 100644 --- a/crates/kernel/src/surface_offset.rs +++ b/crates/kernel/src/surface_offset.rs @@ -69,20 +69,21 @@ mod tests { assert!(copy.face_count() == 2 && rel(measure(©).unwrap().area, 200.0) < 1e-9); } - /// A cylinder's side (two halves) moved out by 2 keeps its halves joined, with radius 12: - /// area 2π·12·20. Moved in past its axis, refused. + /// A cylinder's side (one face, closed round its seam) moved out by 2 keeps its seam joined, + /// with radius 12: area 2π·12·20. Moved in past its axis, refused. #[test] fn a_cylinder_side_changes_radius() { let c = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 20.0).unwrap(); let d = 10.0 / 2f64.sqrt(); - let halves = [face_at(&c, Vec3::new(d, d, 10.0)), face_at(&c, Vec3::new(-d, -d, 10.0))]; - let out = offset_surface(&c, &halves, 2.0, 0.01).unwrap(); - assert!(out.face_count() == 2); + let side = [face_at(&c, Vec3::new(d, d, 10.0))]; + assert_eq!(face_at(&c, Vec3::new(-d, -d, 10.0)), side[0], "the side is one face"); + let out = offset_surface(&c, &side, 2.0, 0.01).unwrap(); + assert!(out.face_count() == 1); let want = 2.0 * std::f64::consts::PI * 12.0 * 20.0; assert!(rel(measure(&out).unwrap().area, want) < 1e-3, "{} vs {want}", measure(&out).unwrap().area); // (measured on meshes) - let joined = offset_surface(&c, &halves, 0.0, 0.01).unwrap(); - assert_eq!(edges(&out), edges(&joined), "the halves still share their seams"); - assert!(offset_surface(&c, &halves, -10.5, 0.01).is_err()); + let joined = offset_surface(&c, &side, 0.0, 0.01).unwrap(); + assert_eq!(edges(&out), edges(&joined), "the side still closes on its seam"); + assert!(offset_surface(&c, &side, -10.5, 0.01).is_err()); } /// A sphere (fitted faces) moved out by 2: area 4π·12², within the tolerance; moved in to diff --git a/crates/kernel/src/surface_ruled.rs b/crates/kernel/src/surface_ruled.rs index 7715eac84..43e9cec93 100644 --- a/crates/kernel/src/surface_ruled.rs +++ b/crates/kernel/src/surface_ruled.rs @@ -145,8 +145,9 @@ pub fn ruled_surface_with(body: &Body, at: &[Vec3], r: &Ruled, handles: &[Option return Err(KernelError::Invalid("the corners cut a strip away entirely: try a shorter distance".into())); } let edge = chain.get(j).map_or(0, |(e, _)| *e); - pieces - .push((s.face(&up_start, &up_end, top_start, top_end, tolerance)?, vec![record::generated(vec![FaceOrigin::Edge { operand: 0, edge }])])); + let face = s.face(&up_start, &up_end, top_start, top_end, tolerance)?; + let h = vec![record::generated(vec![FaceOrigin::Edge { operand: 0, edge }]); face.faces.len()]; + pieces.push((face, h)); } // Corner faces are made in place of the two edges meeting at the corner. for (j, jt) in joints.iter().enumerate() { @@ -878,6 +879,9 @@ struct Strip { line: bool, /// The strip lies in a plane. planar: bool, + /// The axis (a point on it, its direction) of a strip that is a piece of a cone: the edge an + /// arc, its rulings keeping their angle to the arc's axis, leaning in or out. + cone: Option<(Vec3, Vec3)>, start: End, end: End, } @@ -891,13 +895,25 @@ impl Strip { let line = sampled.planar && base.degree == 1 && base.ctrl.len() == 2 && sampled.affine.is_some(); let tangent = |f: f64| point_tangent(&top, f).and_then(|(_, t)| t.normalized()).unwrap_or(first.1); let end = |(p, _, n, r): (Vec3, Vec3, Vec3, Vec3), tan: Vec3| End { at: p, ruling: r, top: p + r * d, tangent: tan, normal: n }; - Strip { start: end(first, tangent(0.0)), end: end(last, tangent(1.0)), base, top, kind, line, planar: sampled.planar } + let cone = match sampled.affine { + Some(Affine::Radial { c, a, scale, .. }) if !sampled.planar && (scale - 1.0).abs() > 1e-12 => Some((c, a)), + _ => None, + }; + Strip { start: end(first, tangent(0.0)), end: end(last, tangent(1.0)), base, top, kind, line, planar: sampled.planar, cone } } /// The strip's face on its own: the base edge, up the end side (`up_end`, points from the /// edge's end to `top_end`), back along the far edge, down the start side (`up_start`, from /// the edge's start to `top_start`). fn face(&self, up_start: &[Vec3], up_end: &[Vec3], top_start: Vec3, top_end: Vec3, tolerance: f64) -> Result { + // A piece of a cone between straight rulings is the ruling at the start turned about the + // cone's axis through the arc's angle, by SMLib's revolve: a cone face, as a cone, where + // the ruled B-spline between the arc and its image is the same surface on no analytic. + if let (Some((c, axis)), [_, _], [_, _]) = (self.cone, up_start, up_end) + && let Some(f) = self.revolved(c, axis, top_start)? + { + return Ok(f); + } let fail = || KernelError::Failed("ruled surface: a strip".into()); let mut parts = Parts { tolerance, ..Parts::default() }; let vertex = |p: Vec3, parts: &mut Parts| -> Result { @@ -955,6 +971,41 @@ impl Strip { }; face_of(parts, surface, uses) } + + /// [`Strip::face`] of a strip on a cone (`c`, `axis` its axis) bounded by straight rulings: + /// the start's ruling (from the edge's start to `top_start`) turned through the arc's angle, + /// right-handed about `axis` the way the edge runs; `None` where the edge's turn can't be read. + fn revolved(&self, c: Vec3, axis: Vec3, top_start: Vec3) -> Result> { + let (Some(bs), Some(be), Some((pm, _))) = (point(&self.base, 0.0), point(&self.base, 1.0), point_tangent(&self.base, 0.5)) else { + return Ok(None); + }; + let flat = |p: Vec3| { + let q = p - c; + q - axis * q.dot(axis) + }; + let angle_to = |p: Vec3| { + let (a, b) = (flat(bs), flat(p)); + a.cross(b).dot(axis).atan2(a.dot(b)) + }; + // The turn to the end, the way the edge runs (through its middle); a closed arc is a turn. + let half = angle_to(pm); + let mut turn = angle_to(be); + if bs.dist(be) <= 1e-9 * (1.0 + flat(bs).len()) { + turn = std::f64::consts::TAU.copysign(half); + } else if half > 0.0 && turn < 0.0 { + turn += std::f64::consts::TAU; + } else if half < 0.0 && turn > 0.0 { + turn -= std::f64::consts::TAU; + } + let side = top_start - bs; + let Some(x) = side.normalized() else { return Ok(None) }; + let Some(y) = (flat(bs) - x * flat(bs).dot(x)).normalized().or_else(|| (axis - x * axis.dot(x)).normalized()) else { return Ok(None) }; + let plane = solidcraft_geom::Plane { origin: bs, x, y }; + let line = solidcraft_geom::Seg2::Line { a: solidcraft_geom::Vec2::ZERO, b: solidcraft_geom::Vec2::new(side.len(), 0.0) }; + // SMLib turns right-handed about the axis it is given. + let (axis, turn) = if turn < 0.0 { (axis * -1.0, -turn) } else { (axis, turn) }; + Ok(Some(crate::surfaces::revolved_record(&plane, &[line], c, axis, turn)?)) + } } /// A pcurve given as a straight line between two (u, v) points over its edge's interval. diff --git a/crates/kernel/src/surface_untrim.rs b/crates/kernel/src/surface_untrim.rs index cacc94e77..fb8e5a793 100644 --- a/crates/kernel/src/surface_untrim.rs +++ b/crates/kernel/src/surface_untrim.rs @@ -201,10 +201,10 @@ mod tests { } /// A revolved face: the cone frustum swept by the line from radius 5 at z = 0 to radius 10 - /// at z = −10 (slant √125), its first face (angles 0…½), trimmed by the plane z = −8 + y/2. + /// at z = −10 (slant √125), one face over angles 0…1, trimmed by the plane z = −8 + y/2. /// The cut reaches lowest (profile parameter 0.8) at angle 0, so the face's own span is - /// angles 0…½ by parameters 0…0.8, restored with arcs about the axis and straight sides: - /// ½ · √125 · ∫₀^0.8 (5 + 5t) dt = ½ · √125 · 5.6. + /// angles 0…1 by parameters 0…0.8, restored with arcs about the axis and straight sides: + /// 1 · √125 · ∫₀^0.8 (5 + 5t) dt = √125 · 5.6. #[test] fn a_trimmed_cone_face_is_restored_to_its_span() { let line = vec![Seg2::Line { a: Vec2::new(5.0, 0.0), b: Vec2::new(10.0, 10.0) }]; @@ -214,7 +214,7 @@ mod tests { let cut = crate::trim(&sheet, &tool, Vec3::new(5.0 * c, 5.0 * s, 0.0)).unwrap(); let face = face_at(&cut, Vec3::new(5.5 * c, 5.5 * s, -1.0)); let restored = untrim(&cut, face, UntrimHoles::All, true, false).unwrap(); - let want = 0.5 * 125f64.sqrt() * 5.6; + let want = 125f64.sqrt() * 5.6; let a = measure(&restored).unwrap().area; assert!(rel(a, want) < 1e-3, "{a} vs {want}"); // (measured on meshes) let bb = measure(&restored).unwrap().bbox; diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index ec40d6a63..291de903c 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -699,7 +699,7 @@ const SAMPLES: usize = 64; /// The parameter of the curve's point nearest `p` inside `interval`, and the distance: the /// nearest of evenly spaced samples, then a golden-section search between its neighbours. -fn nearest_parameter(c: &CurveEval, [a, b]: [f64; 2], p: Vec3) -> Option<(f64, f64)> { +pub(crate) fn nearest_parameter(c: &CurveEval, [a, b]: [f64; 2], p: Vec3) -> Option<(f64, f64)> { let dist = |t: f64| c.point(t).map_or(f64::INFINITY, |q| q.dist(p)); let at = |k: usize| a + (b - a) * k as f64 / SAMPLES as f64; let best = (0..=SAMPLES).min_by(|&i, &j| dist(at(i)).total_cmp(&dist(at(j))))?; @@ -738,12 +738,39 @@ pub fn stitch(bodies: &[&Body], tol: f64) -> Result { Ok(body.with_checked_history(h, &record::counts(bodies))) } +/// [`stitch`] at `tol` exactly, taking a result whose SMLib check fails no more tests than the +/// bodies' own records do, leaving out the tests `exempt` (by SMLib's test number): Repair Part +/// sews parts SMLib's check already finds fault with (an import's edges off their faces), and +/// an edge sewn across a gap carries that gap as its own tolerance. +pub(crate) fn stitch_no_worse(bodies: &[&Body], tol: f64, exempt: &[u32]) -> Result { + if bodies.is_empty() { + return Err(invalid("nothing to stitch")); + } + for b in bodies { + b.require_brep("stitch")?; + } + if !(tol.is_finite() && tol > 0.0) { + return Err(invalid("a stitch tolerance must be positive")); + } + let records: Vec<&Brep> = bodies.iter().map(|b| b.record()).collect(); + let (parts, offsets) = Parts::joined(&records)?; + let c = without_t_junctions(parts.canonical()?, &offsets, tol)?; + let (body, h) = imp::stitched_no_worse(&c.brep, tol, exempt)?; + let h = h.and_then(|h| carried(&h, &c, &offsets, bodies.len(), |operand, face| FaceOrigin::Face { operand, face })); + Ok(body.with_checked_history(h, &record::counts(bodies))) +} + /// A surface body thickened into a solid: offset along the faces' normals by `thickness` /// (negative: against them), or by half each way when `symmetric`, by SMLib's thicken /// ([`crate::offset_backend::thicken`]). pub fn thicken(body: &Body, thickness: f64, symmetric: bool) -> Result { body.require_brep("thicken")?; - imp::thicken(body, thickness, symmetric) + // SMLib holds a sheet's faces with both sides and thickens along their surfaces' natural + // normals; a sheet turned to its back (every face used against its natural normal) grows the + // other way. + let sides = face_sides(body.record()); + let turned = !sides.is_empty() && sides.iter().all(|forward| !forward); + imp::thicken(body, if turned { -thickness } else { thickness }, symmetric) } /// The faces `picked` of `body` (indices in its face order) offset one by one by SMLib, each onto @@ -1248,11 +1275,34 @@ mod imp { /// and edges by their index in `r`); none where SMLib's import of `r` does not number it as /// `r` does. pub(super) fn stitched(r: &Brep, tol: f64) -> Result<(Body, Option)> { + stitched_with(r, tol, |_, sewn| checked(sewn, "stitch").map(|_| ())) + } + + /// [`stitched`], taking a result whose check fails no more tests outside `exempt` than the + /// input's does. + pub(super) fn stitched_no_worse(r: &Brep, tol: f64, exempt: &[u32]) -> Result<(Body, Option)> { + stitched_with(r, tol, |input, sewn| { + let counted = |b: &SmBrep| -> Result { + let report = b.check(CheckLevel::All).map_err(sm("stitch"))?; + Ok(report.failed_tests().into_iter().filter(|t| !exempt.contains(t)).count()) + }; + let (was, now) = (counted(input)?, counted(sewn)?); + if now > was { + let check = sewn.check(CheckLevel::All).map_err(sm("stitch"))?; + return Err(failed(format!("SMLib stitch: SMLib's check finds the sewn part worse ({now} failed tests, {was} before): {check}"))); + } + Ok(()) + }) + } + + /// The record `r` sewn at `tol`, the result taken when `accept` (given SMLib's input and + /// result) does. + fn stitched_with(r: &Brep, tol: f64, accept: impl Fn(&SmBrep, &SmBrep) -> Result<()>) -> Result<(Body, Option)> { let brep = SmBrep::from_record(r, true).map_err(sm("stitch"))?; let (back, order) = brep.to_native_ordered().map_err(|e| failed(format!("SMLib stitch: {e}")))?; let tagged = brep.tagged(0).map_err(sm("stitch"))?; let (sewn, _closed) = tagged.stitch(tol).map_err(sm("stitch"))?; - checked(&sewn, "stitch")?; + accept(&brep, &sewn)?; let (record, kept) = sewn.to_native_ordered().map_err(|e| failed(format!("SMLib stitch: {e}")))?; let h = if same_numbering(r, &back) { sewn.history().ok().and_then(|raw| raw.history(&[order], &kept).ok()) } else { None }; Ok((Body::from_smlib_record(record)?, h)) @@ -1668,8 +1718,9 @@ mod tests { assert!(walls.is_surface() && walls.face_count() == 4 && rel(area(&walls), 80.0) < 1e-9); let pts: Vec = (0..=10).map(|i| Vec3::new(0.0, 0.0, i as f64)).collect(); assert!(rel(area(&sweep_sheet_points(&Plane::XY, std::slice::from_ref(&line), &pts).unwrap()), 100.0) < 1e-6); - // A smooth point path: a quarter circle of radius 30 in the YZ plane. One smooth wall (not - // forty ruled strips), a piece of cylinder: 10 × 15π. + // A point path through a quarter circle of radius 30 in the YZ plane: the path is its + // lines (no wall is fitted through the points), a wall along each of the 40, together + // 10 × the polyline's length, within 10⁻⁴ of the cylinder's 10 × 15π. let arc: Vec = (0..=40) .map(|i| { let t = i as f64 / 40.0 * FRAC_PI_2; @@ -1677,14 +1728,16 @@ mod tests { }) .collect(); let curved = sweep_sheet_points(&Plane::XY, std::slice::from_ref(&line), &arc).unwrap(); - assert_eq!(curved.face_count(), 1, "smooth wall"); + assert_eq!(curved.face_count(), 40, "a wall along each line"); let want = 10.0 * 30.0 * FRAC_PI_2; assert!(rel(area(&curved), want) < 2e-3, "{} vs {want}", area(&curved)); // (measured on meshes) - // A bent chain along the same path: two smooth walls joined by one shared seam edge. + // A bent chain along the same path: two walls along each line, sharing every seam: the + // profile's two segments at each of the 41 points and its three vertices along each of + // the 40 lines. let bent = vec![line[0], Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(10.0, 5.0) }]; let two = sweep_sheet_points(&Plane::XY, &[bent], &arc).unwrap(); - assert_eq!(two.face_count(), 2); - assert_eq!(two.edge_count(), 7, "the walls share their seam"); + assert_eq!(two.face_count(), 2 * 40); + assert_eq!(two.edge_count(), 2 * 41 + 3 * 40, "the walls share their seams"); } #[test] @@ -1808,28 +1861,37 @@ mod tests { assert!(remove_faces(&b, &[]).is_err()); } - /// Faces that are not planes or cylinders thicken onto fitted surfaces. A sixth of a sphere - /// (one of its six patches) thickened out by 1 is a sixth of the shell between radii 10 and - /// 11; a torus patch (a symmetric share of the torus, by its area) thickened out by 1 is that + /// Faces that are not planes or cylinders thicken onto fitted surfaces. A sphere's cap above + /// z = 5 (polar angles to 60°: solid angle π) thickened out by 1 is that sector of the shell + /// between radii 10 and 11, π/3·(11³ − 10³); a torus patch (a symmetric share of the torus, by its area) thickened out by 1 is that /// share of the shell 2π²R((r+1)² − r²); thickened in past the sphere's centre, refused. #[test] fn thicken_curved_faces_onto_fitted_surfaces() { use crate::{sphere, torus}; use std::f64::consts::PI; let ball = sphere(Vec3::ZERO, 10.0).unwrap(); - let patch = copy_faces(&ball, &[Vec3::new(0.0, 0.0, 10.0)]).unwrap(); - assert!(rel(measure(&patch).unwrap().area, 4.0 * PI * 100.0 / 6.0) < 2e-3, "one sixth"); + let caps = crate::split_by_plane(&ball, &Plane::from_normal(Vec3::new(0.0, 0.0, 5.0), Vec3::Z).unwrap()).unwrap(); + let cap = caps.into_iter().find(|b| measure(b).unwrap().bbox.min.z > 5.0 - 1e-6).unwrap(); + let patch = copy_faces(&cap, &[Vec3::new(0.0, 0.0, 10.0)]).unwrap(); + assert!(rel(measure(&patch).unwrap().area, 2.0 * PI * 10.0 * 5.0) < 2e-3, "the cap"); let shell = thicken(&patch, 1.0, false).unwrap(); assert!(!shell.is_surface()); - let want = 4.0 / 3.0 * PI * (1331.0 - 1000.0) / 6.0; + let want = PI / 3.0 * (1331.0 - 1000.0); let v = measure(&shell).unwrap().volume; assert!(rel(v, want) < 3e-3, "{v} vs {want}"); // (measured on meshes) assert!(thicken(&patch, -10.0, false).is_err()); // A torus patch (R 20, r 5): between the tube radii r and r + 1 over its own angles, θ round // the tube and φ round the axis (read off its mesh): the volume is // Δφ·[R((r+1)² − r²)/2·Δθ + ((r+1)³ − r³)/3·(sin θ1 − sin θ0)]. - let ring = torus(Vec3::ZERO, 20.0, 5.0).unwrap(); - let face = copy_faces(&ring, &[Vec3::new(25.0, 0.0, 0.0)]).unwrap(); + // SMLib makes a torus one face: the patch is the piece of it with x, y > 0 and z > 1 + // (bounded by iso lines both ways: planes through the axis, and z = 1 round the tube). + let mut ring = torus(Vec3::ZERO, 20.0, 5.0).unwrap(); + for (o, n) in [(Vec3::ZERO, Vec3::X), (Vec3::ZERO, Vec3::Y), (Vec3::new(0.0, 0.0, 1.0), Vec3::Z)] { + let pieces = crate::split_by_plane(&ring, &Plane::from_normal(o, n).unwrap()).unwrap(); + ring = pieces.into_iter().find(|b| (measure(b).unwrap().bbox.min - o).dot(n) > -1e-6).unwrap(); + } + let (c, s) = (std::f64::consts::FRAC_PI_4.cos(), std::f64::consts::FRAC_PI_4.sin()); + let face = copy_faces(&ring, &[Vec3::new((20.0 + 5.0 * c) * c, (20.0 + 5.0 * c) * s, 5.0 * s)]).unwrap(); let mesh = face.mesh(&crate::MeshTolerance::chord(0.01)).unwrap(); let angles: Vec<(f64, f64)> = mesh.positions.iter().map(|p| (p.z.atan2((p.x * p.x + p.y * p.y).sqrt() - 20.0), p.y.atan2(p.x))).collect(); let span = |f: &dyn Fn(&(f64, f64)) -> f64| { @@ -1844,9 +1906,12 @@ mod tests { assert!(rel(v, want) < 3e-3, "{v} vs {want}"); // (measured on meshes) } - /// Three faces of a box meeting at a corner (sharp edges), thickened out by 1: three slabs, - /// a wedge along each sharp edge and a corner tetrahedron, 3·100 + 3·(½·1²·10) + 1/6; a closed - /// solid that every check accepts. Thickened into the inside corner, refused. + /// Three faces of a box meeting at a corner (sharp edges), thickened out by 1: each face's + /// offset extended until the offsets meet, as SMLib thickens across a convex sharp edge (and + /// other CAD does): three slabs, a 1 × 1 × 10 block along each sharp edge and a unit cube at + /// the corner, 3·100 + 3·10 + 1 = 331 = 11³ − 10³; a closed solid that every check accepts. + /// Into the inside corner, and half each way, the same with the offsets trimmed where they + /// cross. #[test] fn thicken_a_box_corner_across_its_sharp_edges() { let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); @@ -1854,12 +1919,17 @@ mod tests { assert!(corner.is_surface() && corner.face_count() == 3); let t = thicken(&corner, 1.0, false).unwrap(); assert!(!t.is_surface()); - let want = 300.0 + 15.0 + 1.0 / 6.0; + let want = 300.0 + 30.0 + 1.0; let v = measure(&t).unwrap().volume; assert!(rel(v, want) < 1e-9, "{v} vs {want}"); assert!(t.validity().is_empty(), "{:?}", t.validity()); - assert!(thicken(&corner, -1.0, false).is_err()); - assert!(thicken(&corner, 1.0, true).is_err(), "half of it goes into the inside corner"); + // Into the inside corner the offsets are trimmed where they meet: 10³ − 9³; half each way, + // 10.5³ − 9.5³. + for (t, symmetric, want) in [(-1.0, false, 1000.0 - 729.0), (1.0, true, 10.5f64.powi(3) - 9.5f64.powi(3))] { + let t = thicken(&corner, t, symmetric).unwrap(); + let v = measure(&t).unwrap().volume; + assert!(rel(v, want) < 1e-9 && t.validity().is_empty(), "{v} vs {want}"); + } } /// A saddle B-spline patch thickened by 1.5 holds the volume its offsets sweep: by Steiner, @@ -1921,24 +1991,28 @@ mod tests { #[test] fn thicken_a_cylinder_side_and_a_box_top() { let c = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 20.0).unwrap(); - // One half of the side, offset outward by 1: half of a ring. - let half = copy_faces(&c, &[Vec3::new(7.0, 7.0, 10.0)]).unwrap(); + // The side of the cylinder cut in half at x = 0, offset outward by 1: half of a ring. + let halves = crate::split_by_plane(&c, &Plane::from_normal(Vec3::ZERO, Vec3::X).unwrap()).unwrap(); + let cut = halves.into_iter().find(|b| measure(b).unwrap().bbox.min.x > -1e-6).unwrap(); + // (It comes in pieces round the axis: picked all the way round.) + let round: Vec = (-4..=4).map(|k| f64::from(k) * 0.35).map(|a| Vec3::new(10.0 * a.cos(), 10.0 * a.sin(), 10.0)).collect(); + let half = copy_faces(&cut, &round).unwrap(); + assert!(rel(measure(&half).unwrap().area, std::f64::consts::PI * 10.0 * 20.0) < 1e-3, "the half side"); let v = measure(&thicken(&half, 1.0, false).unwrap()).unwrap().volume; let want = std::f64::consts::PI * (121.0 - 100.0) / 2.0 * 20.0; assert!(rel(v, want) < 3e-4, "{v} vs {want}"); // (measured on meshes) - // Both halves (meeting smoothly): the whole ring, inward. - let d = 10.0 / 2f64.sqrt(); - let side = copy_faces(&c, &[Vec3::new(d, d, 10.0), Vec3::new(-d, -d, 10.0)]).unwrap(); - assert_eq!(side.face_count(), 2); + // The whole side (one face, closed round its seam): the whole ring, inward. + let side = copy_faces(&c, &[Vec3::new(7.0, 7.0, 10.0)]).unwrap(); + assert_eq!(side.face_count(), 1); let v = measure(&thicken(&side, -1.0, false).unwrap()).unwrap().volume; let want = std::f64::consts::PI * (100.0 - 81.0) * 20.0; assert!(rel(v, want) < 3e-4, "{v} vs {want}"); // (measured on meshes) - // Two faces meeting at a sharp edge: two slabs and the wedge closing the gap between - // them, its ends patched: 2·100 + ½·1²·10. + // Two faces meeting at a sharp edge: two slabs and, the offsets extended until they + // meet, the 1 × 1 × 10 block along the edge: 2·100 + 10. let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); let two = copy_faces(&b, &[Vec3::new(5.0, 5.0, 10.0), Vec3::new(5.0, 0.0, 5.0)]).unwrap(); let v = measure(&thicken(&two, 1.0, false).unwrap()).unwrap().volume; - assert!(rel(v, 205.0) < 1e-9, "{v}"); + assert!(rel(v, 210.0) < 1e-9, "{v}"); } #[test] diff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rs index 49d1ef8e3..6729f6d6a 100644 --- a/crates/kernel/src/sweep_path.rs +++ b/crates/kernel/src/sweep_path.rs @@ -221,6 +221,21 @@ fn frames_toward(tangents: &[Vec3], d: Vec3) -> Result> { .collect() } +/// Kept as drawn (parallel), the profile flattens to nothing where the path runs along its +/// plane: the path, by its directions of travel `tangents` (the first leaving the profile), has to +/// cross the plane at 5 degrees or more all the way. +pub(crate) fn crossing_check(plane: &Plane, tangents: &[Vec3]) -> Result<()> { + let n = plane.normal().normalized().ok_or_else(|| KernelError::Invalid("sweep frame".into()))?; + let t0 = *tangents.first().ok_or_else(|| KernelError::Invalid("sweep path".into()))?; + let axis = if n.dot(t0) < 0.0 { n * -1.0 } else { n }; + if tangents.iter().any(|t| t.dot(axis) < 5f64.to_radians().sin()) { + return Err(KernelError::Invalid( + "kept parallel, the profile would lie along the sweep path: the path must keep crossing the profile's plane (by 5 deg or more)".into(), + )); + } + Ok(()) +} + /// Stations shaped by sweep options: each maps a world vector at the first station to its image /// at its own (twisted and scaled about the profile's normal through the first station, then /// turned by the orientation's frames), optionally stretched across a corner (mitre). Twist and @@ -246,12 +261,8 @@ pub(crate) fn controlled_stations( // Twist and scale act about the profile's normal, pointing the way the path leaves it. let n = plane.normal().normalized().ok_or_else(|| KernelError::Invalid("sweep frame".into()))?; let axis = if n.dot(t0) < 0.0 { n * -1.0 } else { n }; - // Kept as drawn, the profile flattens to nothing where the path runs along its plane: the - // path has to cross it at 5 degrees or more all the way. - if ctl.orientation == SweepOrientation::Parallel && tangents.iter().any(|t| t.dot(axis) < 5f64.to_radians().sin()) { - return Err(KernelError::Invalid( - "kept parallel, the profile would lie along the sweep path: the path must keep crossing the profile's plane (by 5 deg or more)".into(), - )); + if ctl.orientation == SweepOrientation::Parallel { + crossing_check(plane, tangents)?; } let mut run = Vec::with_capacity(pts.len()); let mut total = 0.0; @@ -457,8 +468,9 @@ mod tests { let want = std::f64::consts::PI * 4.0 * len; assert!((v - want).abs() < 0.02 * want, "{v} vs {want}"); // The path is its lines (no wall is fitted through the points): a wall per profile - // segment (the circle's two arcs) along each of the 40 lines, and two caps. - assert_eq!(b.faces(0.01).unwrap().len(), 2 * 40 + 2, "walls along each line"); + // segment (the circle is one closed arc, one edge in SMLib) along each of the 40 lines, + // and two caps. + assert_eq!(b.faces(0.01).unwrap().len(), 40 + 2, "walls along each line"); // An L-shaped path (a sharp corner) with a holed square: mitred ruled walls. let path = [Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::new(20.0, 0.0, 20.0)]; let plane = Plane::from_normal(Vec3::ZERO, Vec3::Z).unwrap(); diff --git a/crates/kernel/src/sweep_rails_tests.rs b/crates/kernel/src/sweep_rails_tests.rs index 4bc438e33..76d2f9fee 100644 --- a/crates/kernel/src/sweep_rails_tests.rs +++ b/crates/kernel/src/sweep_rails_tests.rs @@ -146,7 +146,8 @@ fn two_rails_carry_a_line_between_arcs() { /// Rails the sweep cannot follow are refused with a reason, never a panic: three rails, a rail /// with a bad point, a rail with a twist or scale besides, a rail starting on the path, a rail -/// that stops short, rails along a path with a corner. +/// that stops short, a straight rail along a path with a corner (a rail must turn with the path +/// at its corners). #[test] fn rails_the_sweep_cannot_follow_are_refused() { let rail = vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(5.0, 0.0, 40.0)]; @@ -162,5 +163,5 @@ fn rails_the_sweep_cannot_follow_are_refused() { refuse(railed(vec![vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(8.0, 0.0, 20.0)]], RailFit::Scale), &up(), "whole length"); refuse(railed(vec![rail.clone(), rail.clone()], RailFit::Scale), &up(), "start at the same point"); let bent = vec![Vec3::ZERO, Vec3::new(0.0, 0.0, 20.0), Vec3::new(20.0, 0.0, 20.0)]; - refuse(railed(vec![vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 30.0)]], RailFit::Scale), &bent, "sharp corners"); + refuse(railed(vec![vec![Vec3::new(10.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 30.0)]], RailFit::Scale), &bent, "the guide rails have to turn with it"); } diff --git a/crates/kernel/src/tess/cdt.rs b/crates/kernel/src/tess/cdt.rs index 60c3dca0d..e7d80f9b4 100644 --- a/crates/kernel/src/tess/cdt.rs +++ b/crates/kernel/src/tess/cdt.rs @@ -79,6 +79,16 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range index.entry(h).or_insert(u32::try_from(i).ok()?); handles.push(h); } + // A side the loops run along both ways (a slit, where a face's boundary goes out along a + // line its two sides share and back) bounds the face on neither. + let mut sides: Vec<(FixedVertexHandle, FixedVertexHandle)> = Vec::new(); + for r in loops { + let n = r.len(); + for k in 0..n { + sides.push((*handles.get(r.start + k)?, *handles.get(r.start + (k + 1) % n)?)); + } + } + let slits = slits(&sides); for r in loops { let n = r.len(); for k in 0..n { @@ -102,7 +112,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range } if let Some((sag, budget)) = &fill.refine { let constraints = cdt.num_constraints(); - let added = refine_sag(&mut cdt, sag, *budget, &from); + let added = refine_sag(&mut cdt, sag, *budget, &from, &slits); if fill.shape { let params = RefinementParameters::::new() .keep_constraint_edges() @@ -115,7 +125,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range // Shaping flips sides and adds points of its own; the triangles it leaves may // sag again (a long strip round a cylinder), so the sag is checked once more. if shaped > 0 { - refine_sag(&mut cdt, sag, budget.saturating_sub(added + shaped), &from); + refine_sag(&mut cdt, sag, budget.saturating_sub(added + shaped), &from, &slits); } } // A split constraint would put a point on the boundary the neighbour does not have. @@ -125,7 +135,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range } let mut uv: Vec<[f64; 2]> = boundary.to_vec(); let mut tris = Vec::new(); - let region = region(&cdt); + let region = region(&cdt, &slits); for face in cdt.inner_faces() { if !region.get(face.index()).copied().unwrap_or(false) { continue; @@ -185,6 +195,8 @@ pub(crate) fn band(points: &[[f64; 2]], n: usize, loops: &[std::ops::Range) -> [f64; 2]) -> usize { +/// `slits`: constraint sides the loops run along both ways, inside the region on both sides. +fn refine_sag( + cdt: &mut Cdt, + sag: &Sag, + budget: usize, + from: &dyn Fn(Point2) -> [f64; 2], + slits: &std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)>, +) -> usize { let mut added = 0; let mut cache: HashMap)>> = HashMap::new(); // The widest turn between two corner normals. @@ -232,7 +251,7 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2 (sag.eval)(q[0], q[1]) }) }; - let region = region(cdt); + let region = region(cdt, slits); for face in cdt.inner_faces() { if !region.get(face.index()).copied().unwrap_or(false) { continue; @@ -304,18 +323,35 @@ fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2 added } +/// The sides a boundary runs along an even number of times (a slit: out along a line and back), +/// each as its vertices in index order: the region lies on both sides of them. +fn slits(sides: &[(FixedVertexHandle, FixedVertexHandle)]) -> std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)> { + let mut runs: HashMap<(FixedVertexHandle, FixedVertexHandle), usize> = HashMap::new(); + for &(a, b) in sides { + if a != b { + *runs.entry(if a.index() < b.index() { (a, b) } else { (b, a) }).or_insert(0) += 1; + } + } + runs.into_iter().filter(|(_, n)| n % 2 == 0).map(|(e, _)| e).collect() +} + /// Per face (by index): inside the region the constraint loops bound. A flood fill from the -/// outer face that flips parity each time it crosses a constraint edge (holes are out), linear -/// in the number of triangles. -fn region(cdt: &Cdt) -> Vec { +/// outer face that flips parity each time it crosses a constraint edge (holes are out), but for +/// the sides in `slits` (run along both ways, the region on both sides), linear in the number of +/// triangles. +fn region(cdt: &Cdt, slits: &std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)>) -> Vec { use spade::handles::{FixedFaceHandle, InnerTag}; + let counts = |e: spade::handles::DirectedEdgeHandle<'_, _, _, _, _>| { + let [a, b] = e.vertices().map(|v| v.fix()); + e.is_constraint_edge() && !slits.contains(&if a.index() < b.index() { (a, b) } else { (b, a) }) + }; let mut parity: Vec> = vec![None; cdt.num_all_faces()]; let mut todo: Vec<(FixedFaceHandle, bool)> = Vec::new(); for e in cdt.convex_hull() { // Hull edges have the outer face on one side; the other side is an inner face. for side in [e, e.rev()] { if let Some(inner) = side.face().as_inner() { - todo.push((inner.fix(), e.is_constraint_edge())); + todo.push((inner.fix(), counts(e))); } } } @@ -326,7 +362,7 @@ fn region(cdt: &Cdt) -> Vec { } for e in cdt.face(h).adjacent_edges() { if let Some(next) = e.rev().face().as_inner() { - todo.push((next.fix(), odd ^ e.is_constraint_edge())); + todo.push((next.fix(), odd ^ counts(e))); } } } diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs index d956b2adb..a912b3097 100644 --- a/crates/kernel/src/tess/mod.rs +++ b/crates/kernel/src/tess/mod.rs @@ -356,7 +356,14 @@ fn boundary( } let n = uvs.len(); let pole = |q: &[f64; 2]| (0..2).any(|d| pole_along(*q, d)); - if let Some(k) = (0..n).find(|&k| uvs.get(k).is_some_and(|q| !pole(q)) && uvs.get((k + n - 1) % n).is_some_and(|q| !pole(q))) { + let off = |k: usize| uvs.get(k).is_some_and(|q| !pole(q)); + // A node off the poles whose predecessor is off them too; failing that (a whole sphere's + // seam in two segments: pole, equator, pole), one whose predecessor is a pole on the same + // edge, so the step into it is the edge's own and the step into that pole, from the + // edge before, is in the loop where it is unwrapped like any other. + let same_edge = |k: usize| segs.get((k + n - 1) % n).zip(segs.get(k)).is_some_and(|(a, b)| a.0 == b.0); + let start = (0..n).find(|&k| off(k) && off((k + n - 1) % n)).or_else(|| (0..n).find(|&k| off(k) && same_edge(k))); + if let Some(k) = start { uvs.rotate_left(k); pts.rotate_left(k); segs.rotate_left(k); @@ -917,6 +924,7 @@ fn plan_face( // Whatever the layout, no triangle leaves the surface by more than the tolerance. if !planar { sag::refine(s, tol, reach, &fixed, &mut all, &mut triangles, MAX_REFINE); + sag::flip(s, tol, reach, &fixed, &all, &mut triangles); } // Both evaluators take a closed spline's parameters inside its active interval. for q in &mut all { @@ -1125,7 +1133,8 @@ fn graded(a: [f64; 2], b: [f64; 2], sa: f64, sb: f64, h: f64, speed: [f64; 2], f all.into_iter().filter(|t| *t > 0.0 && *t < 1.0).collect() } -/// Every boundary segment (consecutive nodes of a loop) is the side of exactly one triangle: +/// Every boundary segment (consecutive nodes of a loop) is the side of exactly one triangle (two +/// for a slit the loops run along both ways): /// the face covers its boundary with nothing missing or doubled, so it meets its neighbours /// exactly. Some boundary nodes are one vertex, a side ending on any of them the same side: pole /// copies of one node (consecutive in a loop, at one point, the segment between them of no @@ -1178,12 +1187,19 @@ fn closed_boundary(ranges: &[std::ops::Range], fixed: &[Vec3], uvs: &[[f6 } } } - ranges.iter().all(|r| { - (0..r.len()).all(|k| { + // Each boundary side has a triangle for every time the loops run along it: one, or two for + // a slit (a side run out and back, where the face meets itself along a line: a hole's wall + // touching the wall round it), one triangle either side. + let mut runs: HashMap<(u32, u32), u32> = HashMap::new(); + for r in ranges { + for k in 0..r.len() { let (a, b) = segment(r, k); - side(a, b).is_none_or(|k| sides.get(&k).copied() == Some(1)) - }) - }) + if let Some(k) = side(a, b) { + *runs.entry(k).or_default() += 1; + } + } + } + runs.iter().all(|(k, n)| sides.get(k).copied() == Some(*n)) } #[cfg(test)] diff --git a/crates/kernel/src/tess/sag.rs b/crates/kernel/src/tess/sag.rs index 02ebb35ef..4082c4aed 100644 --- a/crates/kernel/src/tess/sag.rs +++ b/crates/kernel/src/tess/sag.rs @@ -82,6 +82,25 @@ pub(crate) fn refine(s: &EvalSurface, tol: f64, reach: f64, fixed: &[Vec3], uv: Some((sag, _, e)) if sag > 0.25 * tol && off(centroid, (pa + pb + pc) * (1.0 / 3.0)) > tol => e, _ => continue, }; + // Splitting a triangle's shorter side leaves a child with its long side and a wider + // angle, and where the long side's middle lies on the surface (a section with an + // inflection) the children flatten toward it without end. So a triangle flattened onto its + // longest side (its widest angle past 150 degrees) splits that side, and a split never + // goes across an obtuse triangle's shorter side: that triangle's longest side is split + // first, and so on along the path (Rivara's longest-edge propagation, its lengths growing, + // so it ends). Only sides inside the face are split. + let mut split = flat_long_side(&t, &pos, &sides, shortest, 150.0).unwrap_or(split); + let mut from = ti; + while let Some(&across) = sides.get(&split).and_then(|ts| ts.iter().find(|&&o| o != from)) { + match tris.get(across as usize).and_then(|o| flat_long_side(o, &pos, &sides, shortest, 90.0)) { + Some(long) if long != split => (split, from) = (long, across), + _ => break, + } + } + // The triangle is looked at again when the split was another's, on its way. + if from != ti { + queue.push(ti); + } let (Some(ua), Some(ub)) = (q(split.0), q(split.1)) else { continue }; let m = mean(&[ua, ub]); let mi = uv.len() as u32; @@ -105,6 +124,20 @@ fn mean(s: &EvalSurface, dom: &super::uv::Domain, reach: f64, qs: &[[f64; 2]]) - out } +/// The longest side of triangle `t` when the angle opposite it is past `degrees` and the side lies +/// inside the face (two triangles on it) and is long enough to split. +fn flat_long_side(t: &[u32; 3], pos: &[Vec3], sides: &HashMap<(u32, u32), Vec>, shortest: f64, degrees: f64) -> Option<(u32, u32)> { + let p = |i: u32| pos.get(i as usize).copied(); + let len = |k: usize| p(t[k]).zip(p(t[(k + 1) % 3])).map(|(a, b)| a.dist(b)); + let lengths = [len(0)?, len(1)?, len(2)?]; + let k = (0..3).max_by(|&i, &j| lengths[i].total_cmp(&lengths[j]))?; + let (l, a, b) = (lengths[k], lengths[(k + 1) % 3], lengths[(k + 2) % 3]); + let side = key(t[k], t[(k + 1) % 3]); + let inside = sides.get(&side).is_some_and(|ts| ts.len() == 2) && l > shortest; + let flat = a > 0.0 && b > 0.0 && (a * a + b * b - l * l) / (2.0 * a * b) < degrees.to_radians().cos(); + (inside && flat).then_some(side) +} + fn key(a: u32, b: u32) -> (u32, u32) { (a.min(b), a.max(b)) } @@ -143,3 +176,150 @@ fn split_side(tris: &mut Vec<[u32; 3]>, sides: &mut HashMap<(u32, u32), Vec } touched } + +/// The sharpest corner (radians) a flip may make. +const MIN_FLIP_ANGLE: f64 = 1e-3; + +/// Flip the sides inside a face's triangulation (as [`refine`] takes it) where the two triangles +/// on a side lie closer along the surface the other way: their facets turn less from the surface +/// normal. A layout can leave +/// slivers standing on their long side across the surface (their corners on it, their plane across +/// it), which count several times the area under them and which no split repairs; the flip lays +/// them down. A side is flipped only when both new triangles keep the orientation of the old ones +/// in (u, v) and against the surface normal (nothing folds), and the new side and the new +/// triangles' middles stay within `tol` of the surface, or no farther than the old side's middle. +/// Sides with one triangle (the face's boundary) are never flipped. +pub(crate) fn flip(s: &EvalSurface, tol: f64, reach: f64, fixed: &[Vec3], uv: &[[f64; 2]], tris: &mut [[u32; 3]]) { + if !(tol.is_finite() && tol > 0.0) || tris.len() < 2 { + return; + } + let dom = super::uv::domain(s); + let mean = |qs: &[[f64; 2]]| mean(s, &dom, reach, qs); + let pos: Vec = uv.iter().enumerate().map(|(i, q)| fixed.get(i).copied().unwrap_or_else(|| s.eval(q[0], q[1]).0)).collect(); + let p = |i: u32| pos.get(i as usize).copied(); + let q = |i: u32| uv.get(i as usize).copied(); + let off = |m: [f64; 2], c: Vec3| match s.derivs(m[0], m[1]) { + Some((x, su, sv)) => su.cross(sv).normalized().map_or_else(|| x.dist(c), |n| (x - c).dot(n).abs()), + None => s.eval(m[0], m[1]).0.dist(c), + }; + // Twice the signed area in (u, v). + let area_uv = |t: [u32; 3]| match (q(t[0]), q(t[1]), q(t[2])) { + (Some(a), Some(b), Some(c)) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]), + _ => 0.0, + }; + // The triangle's smallest angle in 3D. + let min_angle = |t: [u32; 3]| -> f64 { + let (Some(a), Some(b), Some(c)) = (p(t[0]), p(t[1]), p(t[2])) else { return 0.0 }; + let angle = |o: Vec3, x: Vec3, y: Vec3| match ((x - o).normalized(), (y - o).normalized()) { + (Some(u), Some(v)) => u.dot(v).clamp(-1.0, 1.0).acos(), + _ => 0.0, + }; + angle(a, b, c).min(angle(b, c, a)).min(angle(c, a, b)) + }; + // How far a facet's normal turns from the surface normal at its middle (radians, 0 to pi/2). + let deviation = |t: [u32; 3]| -> f64 { + let (Some(a), Some(b), Some(c), Some(qa), Some(qb), Some(qc)) = (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) else { return 0.0 }; + let m = mean(&[qa, qb, qc]); + let facet = (b - a).cross(c - a).normalized(); + match (facet, s.derivs(m[0], m[1]).and_then(|(_, su, sv)| su.cross(sv).normalized())) { + (Some(f), Some(n)) => f.dot(n).abs().clamp(0.0, 1.0).acos(), + _ => 0.0, + } + }; + // Whether the facet's normal lies on the side of the surface normal that its (u, v) + // orientation `sign` says. + let upright = |t: [u32; 3], sign: f64| -> bool { + let (Some(a), Some(b), Some(c), Some(qa), Some(qb), Some(qc)) = (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) else { return false }; + let m = mean(&[qa, qb, qc]); + match s.derivs(m[0], m[1]) { + Some((_, su, sv)) => (b - a).cross(c - a).dot(su.cross(sv)) * sign > 0.0, + None => true, + } + }; + let centroid_off = |t: [u32; 3]| match (p(t[0]), p(t[1]), p(t[2]), q(t[0]), q(t[1]), q(t[2])) { + (Some(a), Some(b), Some(c), Some(qa), Some(qb), Some(qc)) => off(mean(&[qa, qb, qc]), (a + b + c) * (1.0 / 3.0)), + _ => f64::INFINITY, + }; + let mut sides: HashMap<(u32, u32), Vec> = HashMap::with_capacity(tris.len() * 2); + for (ti, t) in tris.iter().enumerate() { + for k in 0..3 { + sides.entry(key(t[k], t[(k + 1) % 3])).or_default().push(ti as u32); + } + } + let mut queue: Vec<(u32, u32)> = sides.iter().filter(|(_, ts)| ts.len() == 2).map(|(e, _)| *e).collect(); + queue.sort_unstable(); + let mut budget = tris.len().saturating_mul(8); + // Each triangle's deviation, until it is flipped. + let mut dev_of: Vec> = vec![None; tris.len()]; + while let Some(e) = queue.pop() { + if budget == 0 { + break; + } + let Some(&[t1, t2]) = sides.get(&e).map(|v| v.as_slice()) else { continue }; + let (Some(&ta), Some(&tb)) = (tris.get(t1 as usize), tris.get(t2 as usize)) else { continue }; + // [a, b, c] on one side of a -> b, [b, a, d] on the other. + let Some(k) = (0..3).find(|&k| key(ta[k], ta[(k + 1) % 3]) == e) else { continue }; + let (a, b, c) = (ta[k], ta[(k + 1) % 3], ta[(k + 2) % 3]); + let Some(d) = tb.iter().copied().find(|&v| v != a && v != b) else { continue }; + if c == d || sides.contains_key(&key(c, d)) { + continue; + } + let (n1, n2) = ([a, d, c], [d, b, c]); + let sign = area_uv(ta).signum(); + if sign == 0.0 || area_uv(tb).signum() != sign || area_uv(n1) * sign <= 0.0 || area_uv(n2) * sign <= 0.0 { + continue; + } + // The pair the other way must lie closer along the surface (its facets turn less from + // the surface normal), by more than a degree: a pair within a degree of the surface is + // left as the layout made it. + let mut cached = |ti: u32, t: [u32; 3]| match dev_of.get(ti as usize).copied().flatten() { + Some(d) => d, + None => { + let d = deviation(t); + if let Some(slot) = dev_of.get_mut(ti as usize) { + *slot = Some(d); + } + d + } + }; + let worse = cached(t1, ta).max(cached(t2, tb)); + let degree = 1f64.to_radians(); + if worse < degree || deviation(n1).max(deviation(n2)) >= worse - degree { + continue; + } + // ... and have area in 3D (three corners on one line of a cone have none, however they + // lie in (u, v)). + if min_angle(n1).min(min_angle(n2)) < MIN_FLIP_ANGLE { + continue; + } + if !(upright(n1, sign) && upright(n2, sign)) { + continue; + } + let (Some(pa), Some(pb), Some(pc), Some(pd), Some(qa), Some(qb), Some(qc), Some(qd)) = (p(a), p(b), p(c), p(d), q(a), q(b), q(c), q(d)) + else { + continue; + }; + let allowed = tol.max(off(mean(&[qa, qb]), (pa + pb) * 0.5)).max(centroid_off(ta)).max(centroid_off(tb)); + if off(mean(&[qc, qd]), (pc + pd) * 0.5) > allowed || centroid_off(n1) > allowed || centroid_off(n2) > allowed { + continue; + } + budget -= 1; + for ti in [t1, t2] { + if let Some(slot) = dev_of.get_mut(ti as usize) { + *slot = None; + } + } + if let Some(slot) = tris.get_mut(t1 as usize) { + *slot = n1; + } + if let Some(slot) = tris.get_mut(t2 as usize) { + *slot = n2; + } + sides.remove(&e); + sides.insert(key(c, d), vec![t1, t2]); + // a-d moves from t2 to t1, b-c from t1 to t2. + retag(&mut sides, a, d, t2, t1); + retag(&mut sides, b, c, t1, t2); + queue.extend([key(a, d), key(d, b), key(b, c), key(c, a)].into_iter().filter(|s| sides.get(s).is_some_and(|ts| ts.len() == 2))); + } +} diff --git a/crates/kernel/src/tess/tangle.rs b/crates/kernel/src/tess/tangle.rs index c53a982ce..877b65627 100644 --- a/crates/kernel/src/tess/tangle.rs +++ b/crates/kernel/src/tess/tangle.rs @@ -95,6 +95,19 @@ pub(crate) fn crossing(s: &EvalSurface, reach: f64, loops: &[seam::Loop]) -> Vec out.push(x.at); out.push(y.at); } + // A node of one chord lying on the other (inside it, not at its ends) is no crossing, + // but no triangulation can keep both as constraints either: where two curves leave a + // vertex they touch at along one tangent (a circle touching another from inside), the + // inner one's node can fall on the outer one's chord (with the outer chord twice the + // inner, exactly so but for the next order). The chord the node lies on is halved. + // (Not where the two chords run along one line: a seam's two uses, a period apart, + // lie on each other as copies.) + if !along(x.a, x.b, y.a, y.b) && [y.a, y.b].iter().any(|q| on(x.a, x.b, *q)) { + out.push(x.at); + } + if !along(y.a, y.b, x.a, x.b) && [x.a, x.b].iter().any(|q| on(y.a, y.b, *q)) { + out.push(y.at); + } } } out.sort_unstable(); @@ -102,6 +115,28 @@ pub(crate) fn crossing(s: &EvalSurface, reach: f64, loops: &[seam::Loop]) -> Vec out } +/// Whether `q` lies on the segment `ab` within [`STRADDLE`] (of the segment's squared length, +/// off its line) strictly between its ends (not at either, by the same measure along it). +fn on(a: [f64; 2], b: [f64; 2], q: [f64; 2]) -> bool { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let len2 = dx * dx + dy * dy; + if !(len2 > 0.0) { + return false; + } + let (qx, qy) = (q[0] - a[0], q[1] - a[1]); + let off = (dx * qy - dy * qx).abs(); + let along = (dx * qx + dy * qy) / len2; + off <= 1e3 * STRADDLE * len2 && along > 1e-6 && along < 1.0 - 1e-6 +} + +/// Whether `c` and `d` both lie on the line of `ab` (within [`on`]'s measure). +fn along(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let len2 = dx * dx + dy * dy; + let off = |q: [f64; 2]| (dx * (q[1] - a[1]) - dy * (q[0] - a[0])).abs(); + len2 > 0.0 && off(c) <= 1e3 * STRADDLE * len2 && off(d) <= 1e3 * STRADDLE * len2 +} + /// Whether the segments `ab` and `cd` cross: each one's ends strictly either side of the other. fn cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool { let orient = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rs index 45f5163c2..81730249d 100644 --- a/crates/kernel/src/tess/tests.rs +++ b/crates/kernel/src/tess/tests.rs @@ -470,11 +470,16 @@ fn iso_groove(p: f64, d: f64, wall: f64, internal: bool) -> [(f64, f64); 4] { } /// Each face's triangles, in 3D, cover as much area as its surface over the triangles' own -/// parameters, within 5% (a coarse tolerance on a small curved face, a few percent): nothing -/// zigzags across the face, which multiplies its area. The surface's area by the midpoint rule -/// on sixteen pieces of each parameter triangle. +/// parameters, within 5% (a coarse tolerance on a small curved face, a few percent) and the +/// sails along its boundary: nothing zigzags across the face, which multiplies its area. The +/// surface's area by the midpoint rule on sixteen pieces of each parameter triangle. A face's +/// boundary sides are its edges' chords, each up to the chord tolerance `tol` off its edge, and +/// between a chord of length L and its edge lies a sail of surface of at most 2/3 L tol (a +/// parabolic segment) that flat triangles bridge rather than follow: a face no wider than its +/// chords sag (the thread's crest band where it runs out through the block's end, 0.06 mm sag +/// at 0.1) takes up to that much more or less area however it is triangulated inside. #[cfg(feature = "smlib")] -fn assert_faces_lie_flat(name: &str, plan: &solidcraft_geom::tess::TessPlan) { +fn assert_faces_lie_flat(name: &str, plan: &solidcraft_geom::tess::TessPlan, tol: f64) { for fp in &plan.faces { let Some(s) = fp.surface.and_then(|i| plan.surfaces.get(i as usize)) else { continue }; let at = |i: u32| { @@ -504,7 +509,21 @@ fn assert_faces_lie_flat(name: &str, plan: &solidcraft_geom::tess::TessPlan) { } } } - assert!((flat - surface).abs() <= 0.05 * surface, "{name}: face {} has {flat} mm² of triangles over {surface} mm² of surface", fp.face); + // The boundary: the sides of exactly one triangle. + let mut sides: HashMap<(u32, u32), u32> = HashMap::new(); + for t in &fp.triangles { + for k in 0..3 { + let (a, b) = (t[k], t[(k + 1) % 3]); + *sides.entry((a.min(b), a.max(b))).or_default() += 1; + } + } + let boundary: f64 = sides.iter().filter(|(_, n)| **n == 1).map(|((a, b), _)| at(*a).dist(at(*b))).sum(); + let sails = 2.0 / 3.0 * boundary * tol; + assert!( + (flat - surface).abs() <= 0.05 * surface + sails, + "{name}: face {} has {flat} mm² of triangles over {surface} mm² of surface (its boundary's sails {sails})", + fp.face + ); } } @@ -534,7 +553,7 @@ fn a_modelled_thread_in_a_bore_meshes_inside_its_block() { let m = closed_display_mesh("thread in a bore", &body, tol); let chord = max_chord(&body, &m); assert!(chord <= tol * 1.05, "thread in a bore at {tol}: chord {chord}"); - assert_faces_lie_flat("thread in a bore", &ok(body.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(crate::DISPLAY_ANGLE) }))); + assert_faces_lie_flat("thread in a bore", &ok(body.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(crate::DISPLAY_ANGLE) })), tol); } } @@ -560,7 +579,7 @@ fn a_thread_root_band_running_out_through_an_end_face_lies_on_its_surface() { let chord = max_chord(&body, &m); assert!(chord <= tol * 1.05, "thread run out at {tol}: chord {chord}"); assert!(m.triangles.len() < 60_000, "thread run out at {tol}: {} triangles", m.triangles.len()); - assert_faces_lie_flat("thread run out", &ok(body.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(crate::DISPLAY_ANGLE) }))); + assert_faces_lie_flat("thread run out", &ok(body.mesh_plan(&crate::MeshTolerance { chord: tol, angle: Some(crate::DISPLAY_ANGLE) })), tol); } } @@ -650,6 +669,39 @@ fn loops_touching_at_a_shared_vertex_bound_the_face() { assert!(closed_boundary(&ranges, &fixed, &uvs, &triangles), "the triangles follow both holes through their shared vertex"); } +/// A face meeting itself along a line (a hole's wall tangent inside the wall round it, cut from +/// the boss side's top rim down to the hole's bottom): its loop runs up the slit and back down +/// it, with the face on both sides. The iso-line grid's band beside the slit is the face on +/// either side of it, and the triangles follow the slit both ways and cover the whole square. +#[test] +fn a_slit_in_a_trimmed_face_has_the_face_on_both_sides() { + // The square [0, 8] × [0, 4], its loop starting at the slit's tip (3, 1) up to the top, round + // the square and back down the slit. + let mut uvs: Vec<[f64; 2]> = (1..=4).map(|k| [3.0, k as f64]).collect(); + uvs.extend((0..3).rev().map(|k| [k as f64, 4.0])); + uvs.extend((0..4).rev().map(|k| [0.0, k as f64])); + uvs.extend((1..=8).map(|k| [k as f64, 0.0])); + uvs.extend((1..=4).map(|k| [8.0, k as f64])); + uvs.extend((3..8).rev().map(|k| [k as f64, 4.0])); + uvs.extend((2..4).rev().map(|k| [3.0, k as f64])); + let fixed: Vec = uvs.iter().map(|q| Vec3::new(q[0], q[1], 0.0)).collect(); + let ranges = [std::ops::Range { start: 0, end: uvs.len() }]; + let traces = motorcycle::traces(&uvs, &ranges, [1.0, 1.0], 0.0); + let lines = |n: usize, top: f64| (0..=n).map(|k| top * k as f64 / n as f64).collect::>(); + let Some((extra, triangles)) = cutgrid::cut_grid(&uvs, &ranges, &lines(16, 8.0), &lines(8, 4.0), &traces, [1.0, 1.0]) else { panic!("meshes") }; + assert!(closed_boundary(&ranges, &fixed, &uvs, &triangles), "the triangles follow the slit both ways"); + let mut all = uvs.clone(); + all.extend(extra); + let area: f64 = triangles + .iter() + .map(|t| { + let [a, b, c] = t.map(|i| all[i as usize]); + 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) + }) + .sum(); + assert!((area - 32.0).abs() < 1e-12, "area {area}"); +} + /// A face whose loop is a thin lune meshes: a half disc of radius 2.5 less a circle through the /// same ends 0.03 mm inside it at the middle, its inner side split at 11.25°. Each edge is /// sampled to the 0.1 mm chord on its own: the outer arc's chords (every 22.5°) sag 0.048 mm, @@ -784,11 +836,16 @@ fn a_face_bounded_by_two_short_arcs_keeps_an_area_to_mesh() { let sq = [[3000.0, 0.0, 0.0], [5000.0, 0.0, 0.0], [5000.0, 2000.0, 0.0], [3000.0, 2000.0, 0.0]]; let plane = Surface::Plane { origin: [0.0; 3], u_axis: [1.0, 0.0, 0.0], v_axis: [0.0, 1.0, 0.0] }; let mut edges = vec![ - PartEdge { curve: circle(-c), interval: [top, PI - top], vertices: [0, 1] }, - PartEdge { curve: circle(c), interval: [PI + top, TAU - top], vertices: [1, 0] }, + PartEdge { nurbs: None, curve: circle(-c), interval: [top, PI - top], vertices: [0, 1] }, + PartEdge { nurbs: None, curve: circle(c), interval: [PI + top, TAU - top], vertices: [1, 0] }, ]; for k in 0..4 { - edges.push(PartEdge { curve: line(sq[k], sq[(k + 1) % 4]), interval: [0.0, 1.0], vertices: [2 + k as u32, 2 + ((k + 1) % 4) as u32] }); + edges.push(PartEdge { + nurbs: None, + curve: line(sq[k], sq[(k + 1) % 4]), + interval: [0.0, 1.0], + vertices: [2 + k as u32, 2 + ((k + 1) % 4) as u32], + }); } let uses = |es: &[u32]| es.iter().map(|&edge| PartUse { edge, forward: true, given: None }).collect::>(); let mut vertices = vec![[half, 0.0, 0.0], [-half, 0.0, 0.0]]; @@ -864,3 +921,135 @@ fn a_loop_corner_within_its_tolerance_of_a_pole_is_a_pole() { let Err(e) = plan(&pyramid_past_a_near_pole(1e-8), 0.01, None) else { panic!("no pole without the tolerance") }; assert!(e.to_string().contains("winds around the surface"), "{e}"); } + +/// A whole sphere as one face (its seam the only edge) in a body many times its size: at the +/// body's chord the seam gets two segments, pole to equator to pole, and every node off the poles +/// follows a pole. The loop used to start at a pole and close across the other, which unwrapped +/// to a whole turn: "boundary winds around the surface", and the sphere was left out (a sealed +/// void r 2 in a 60 mm block). It meshes closed. +#[test] +fn a_small_sphere_void_in_a_large_block_meshes() { + let block = ok(crate::box_solid(Vec3::new(-30.0, -30.0, 0.0), Vec3::new(30.0, 30.0, 60.0))); + let ball = ok(crate::sphere(Vec3::new(0.0, 0.0, 30.0), 2.0)); + let hollow = cut(&block, &ball); + let tol = hollow.size() * 0.01; + let (m, stats) = match plan(&record(&hollow), tol, None) { + Ok((p, stats)) => (p.evaluate(), stats), + Err(e) => panic!("plan: {e}"), + }; + assert!(stats.unmeshed.is_empty(), "{:?}", stats.unmeshed.iter().map(|u| &u.reason).collect::>()); + assert_watertight(&m, "block with a sphere void"); + assert_eq!(hollow.unmeshed_faces(), 0); +} + +/// A sheet whose section is an S (a cubic 30 long, 1.5 off its chord each way, its middle on the +/// chord), straight across, meshed as fans with one triangle flat on the chord across its middle +/// (A, B at the sides, C a hair above the chord a third along). The chord's middle lies on the +/// surface while the triangle's short sides sag: splitting those left a child with the chord and +/// its vertex nearer to it, without end (a loft side of a bike frame refined to slivers until the +/// point budget ran out, its area counted three times). The flat triangle now splits the chord, +/// and refinement ends within its budget with no sliver. +#[test] +fn sag_refinement_across_an_inflection_ends_without_slivers() { + let mut ctrl = Vec::new(); + for j in 0..2 { + for (i, z) in [0.0, 4.0, -4.0, 0.0].into_iter().enumerate() { + ctrl.push([10.0 * i as f64, 10.0 * f64::from(j), z, 1.0]); + } + } + let s = EvalSurface::Nurbs { + degree: [3, 1], + knots: [vec![0., 0., 0., 0., 1., 1., 1., 1.], vec![0., 0., 1., 1.]], + count: [4, 2], + ctrl, + closed: [false, false], + }; + // Boundary: bottom and top rows of n + 1 nodes (their sides within the tolerance, 0.5), A and + // B halfway up the ends. Inside: C. Bottom fan from A, the triangle A B C, top fan from C. + let n = 6u32; + let mut uv: Vec<[f64; 2]> = Vec::new(); + for i in 0..=n { + uv.push([f64::from(i) / f64::from(n), 0.0]); + } + for i in 0..=n { + uv.push([f64::from(i) / f64::from(n), 1.0]); + } + let (bottom, top) = (0u32, n + 1); + let (a, b, c) = (2 * n + 2, 2 * n + 3, 2 * n + 4); + uv.extend([[0.0, 0.5], [1.0, 0.5], [1.0 / 3.0, 0.5 + 1e-3]]); + let mut tris: Vec<[u32; 3]> = vec![[a, bottom, bottom + 1]]; + tris.extend((1..n).map(|i| [a, bottom + i, bottom + i + 1])); + tris.push([a, bottom + n, b]); + tris.push([a, b, c]); + tris.push([c, b, top + n]); + tris.extend((0..n).rev().map(|i| [c, top + i + 1, top + i])); + tris.push([c, top, a]); + // The sides along the ends are straight. + let fixed: Vec = Vec::new(); + let tol = 0.5; + let start = uv.len(); + super::sag::refine(&s, tol, 1e-9, &fixed, &mut uv, &mut tris, 20_000); + assert!(uv.len() - start < 1_000, "{} points added: refinement ran to its budget", uv.len() - start); + for t in &tris { + let [p, q, r] = t.map(|i| uv[i as usize]); + let area = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + let longest = [(p, q), (q, r), (r, p)].iter().map(|(x, y)| (x[0] - y[0]).hypot(x[1] - y[1])).fold(0.0, f64::max); + assert!(area > 1e-6 * longest * longest, "a sliver {t:?}: {p:?} {q:?} {r:?}"); + } +} + +/// A sheet curved across (a parabola 20 wide, 3.2 high at a tenth in from either side) and two +/// triangles standing on a chord across the curve: their corners on the surface, their planes +/// across it, so they count far more than the area under them. The flip lays them along the +/// sheet, on the straight side along it. +#[test] +fn triangles_standing_across_a_curved_sheet_are_flipped_along_it() { + let mut ctrl = Vec::new(); + for j in 0..2 { + for (i, z) in [5.0, -5.0, 5.0].into_iter().enumerate() { + ctrl.push([10.0 * i as f64 - 10.0, 10.0 * f64::from(j), z, 1.0]); + } + } + let s = EvalSurface::Nurbs { + degree: [2, 1], + knots: [vec![0., 0., 0., 1., 1., 1.], vec![0., 0., 1., 1.]], + count: [3, 2], + ctrl, + closed: [false, false], + }; + let uv = vec![[0.1, 0.5], [0.9, 0.5], [0.5, 0.52], [0.5, 0.48]]; + let mut tris = vec![[0, 1, 2], [1, 0, 3]]; + let area = |tris: &[[u32; 3]]| -> f64 { + tris.iter() + .map(|t| { + let [a, b, c] = t.map(|i| s.eval(uv[i as usize][0], uv[i as usize][1]).0); + (b - a).cross(c - a).len() / 2.0 + }) + .sum() + }; + let before = area(&tris); + super::sag::flip(&s, 0.1, 1e-9, &[], &uv, &mut tris); + let after = area(&tris); + let sides: Vec<(u32, u32)> = tris.iter().flat_map(|t| (0..3).map(move |k| (t[k].min(t[(k + 1) % 3]), t[k].max(t[(k + 1) % 3])))).collect(); + assert!(sides.contains(&(2, 3)) && !sides.contains(&(0, 1)), "{tris:?}"); + assert!(after < 0.5 * before, "{before} -> {after}"); +} + +/// A disc with a boss standing on it tangent inside its rim: the disc's top is a ring whose inner +/// circle touches the outer one, one loop through the touching vertex. There both circles leave +/// along one tangent, and with the outer chord twice the inner (as their samplings fall) the inner +/// circle's first node lies on the outer's last chord: no triangulation keeps both. That chord is +/// halved, and the ring meshes strictly, to its area (300 pi), not the inner disc's. +#[test] +fn a_ring_touching_itself_at_a_vertex_meshes_strictly() { + use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; + let prism = |c: Vec2, r: f64, z0: f64, z1: f64| { + ok(crate::extrude(&Plane::XY, &[Region2 { outer: Loop2::circle(c, r), holes: vec![] }], z0, z1)).pop().unwrap() + }; + let stepped = + ok(crate::boolean(&prism(Vec2::ZERO, 20.0, 0.0, 5.0), &prism(Vec2::new(10.0, 0.0), 10.0, 5.0, 15.0), crate::BoolOp::Union)).unwrap(); + let (_, stats) = ok(plan(&record(&stepped), 1e-4, None)); + assert!(stats.lenient.is_empty(), "{:?}", stats.lenient.iter().map(|r| &r.reason).collect::>()); + let ring = ok(stepped.faces(1e-4)).into_iter().find(|f| (f.centroid.z - 5.0).abs() < 1e-6).unwrap(); + assert!((ring.area - 300.0 * PI).abs() < 0.05, "ring area {}", ring.area); +} diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index 592c36269..cf1718e34 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -31,7 +31,9 @@ fn cylinder_measures_match_analytic() { let a = 2.0 * PI * 225.0 + 2.0 * PI * 15.0 * 50.0; assert!(rel(m.volume, v) < 5e-4, "{} vs {v}", m.volume); assert!(rel(m.area, a) < 5e-4, "{} vs {a}", m.area); - assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (3, 2, 2), "{:?}", m.merged); + // Two closed circles and the side's seam (the ladder's count: each whole curve once, and each + // cylinder's seam); a vertex on each circle. + assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (3, 3, 2), "{:?}", m.merged); assert_eq!(m.merged.face_types.get("cylinder"), Some(&1)); } @@ -463,10 +465,27 @@ fn tapered_extrudes() { assert!(rel(m.volume, v) < 5e-4, "{} vs {v}", m.volume); assert!(m.bbox.max.z < 1e-6 && m.bbox.min.z > -10.0 - 1e-6, "{:?}", m.bbox); assert!(extrude_tapered(&Plane::XY, &c, 10.0, 1.0, -60f64.to_radians(), crate::DraftCorner::default()).is_err(), "closes the profile"); + // The square with a 10 × 10 square hole, 30 up, 5° inward: every wall leans in toward the + // material's outside, so the outer frustum narrows and the hole's widens; the solid is the + // one frustum less the other, with each wall a face of its own (four out, four in, two caps). + let t = 5f64.to_radians().tan(); + let hole = Loop2::polygon(&[Vec2::new(-5.0, -5.0), Vec2::new(-5.0, 5.0), Vec2::new(5.0, 5.0), Vec2::new(5.0, -5.0)]); + let ring = Region2 { outer: sq.outer.clone(), holes: vec![hole] }; + let b = extrude_tapered(&Plane::XY, &ring, 30.0, 1.0, -5f64.to_radians(), crate::DraftCorner::default()).unwrap(); + let frustum = |a0: f64, a1: f64| 30.0 / 3.0 * (a0 * a0 + a1 * a1 + a0 * a1); + let v = frustum(40.0, 40.0 - 60.0 * t) - frustum(10.0, 10.0 + 60.0 * t); + let m = measure(&b).unwrap(); + assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume); + assert_eq!(m.merged.faces, 10); + // At 30° the hole would grow past the outer wall: refused, saying why. + let e = extrude_tapered(&Plane::XY, &ring, 30.0, 1.0, -30f64.to_radians(), crate::DraftCorner::default()).unwrap_err(); + assert!(e.to_string().contains("hole"), "{e}"); } /// A slot (two lines and two half-circles, tangent) tapered inward: every edge moves in by -/// d = z · tan 8°, so A(d) = A₀ − P·d + π·d² (#546). An arc meeting a line at a corner is refused. +/// d = z · tan 8°, so A(d) = A₀ − P·d + π·d² (#546). A quarter disc, its arc meeting the lines at +/// corners, tapered outward: each wall continues as itself, so the section at d is the disc of +/// radius r + d over x ≥ −d, y ≥ −d. #[test] fn tapered_extrude_of_lines_and_arcs() { let (r, l, h, a) = (5.0, 20.0, 12.0, 8f64.to_radians()); @@ -492,8 +511,34 @@ fn tapered_extrude_of_lines_and_arcs() { Seg2::Line { a: Vec2::new(0.0, r), b: Vec2::ZERO }, ], }; - let e = extrude_tapered(&Plane::XY, &Region2 { outer: quarter, holes: vec![] }, h, 1.0, a, crate::DraftCorner::default()).unwrap_err(); - assert!(e.to_string().contains("arc meets another edge at a corner"), "{e}"); + let b = extrude_tapered(&Plane::XY, &Region2 { outer: quarter, holes: vec![] }, h, 1.0, a, crate::DraftCorner::default()).unwrap(); + // The section's area: under the circle of radius R = r + d down to y = −d from x = −d to + // x₁, where the circle meets y = −d, then the whole circle's width out to x = R; + // F(x) = ∫ √(R² − x²) dx. + let section = |d: f64| { + let big = r + d; + let f = |x: f64| 0.5 * (x * (big * big - x * x).max(0.0).sqrt() + big * big * (x / big).clamp(-1.0, 1.0).asin()); + let x1 = (big * big - d * d).sqrt(); + f(x1) - f(-d) + d * (x1 + d) + 2.0 * (f(big) - f(x1)) + }; + // Gauss–Legendre on 8 nodes over each of 16 pieces of the height: the area is smooth in d. + let (nodes, weights) = ( + [0.183_434_642_495_649_8, 0.525_532_409_916_329, 0.796_666_477_413_626_7, 0.960_289_856_497_536_3], + [0.362_683_783_378_362, 0.313_706_645_877_887_3, 0.222_381_034_453_374_5, 0.101_228_536_290_376_3], + ); + let pieces = 16; + let v: f64 = (0..pieces) + .map(|k| { + let (z0, dz) = (k as f64 * h / pieces as f64, h / pieces as f64); + let mid = z0 + 0.5 * dz; + nodes.iter().zip(weights).map(|(x, w)| w * (section((mid - 0.5 * dz * x) * t) + section((mid + 0.5 * dz * x) * t))).sum::() + * 0.5 + * dz + }) + .sum(); + let m = measure(&b).unwrap(); + assert!(rel(m.volume, v) < 1e-6, "quarter disc: {} vs {v}", m.volume); + assert_eq!(m.merged.faces, 5, "quarter disc: bottom, top, two flat walls and the cone"); } /// A circle with a lobe on each side (four arcs of three circles, meeting at corners: the outline of @@ -958,13 +1003,16 @@ fn sphere_booleans() { let s = sphere(Vec3::ZERO, 15.0).unwrap(); let m = measure(&s).unwrap(); assert!(rel(m.volume, 4.0 / 3.0 * PI * 3375.0) < 1e-3, "{}", m.volume); - assert_eq!((m.merged.faces, m.merged.edges), (1, 0)); + // One spherical face, closed along its seam from pole to pole. + assert_eq!((m.merged.faces, m.merged.edges), (1, 1)); // A ball cut out of the top face of a slab (oracle 14). let b = box_solid(Vec3::new(-25.0, -25.0, -20.0), Vec3::new(25.0, 25.0, 0.0)).unwrap(); let c = boolean(&b, &s, BoolOp::Cut).unwrap().unwrap(); let m = measure(&c).unwrap(); assert!(rel(m.volume, 50.0 * 50.0 * 20.0 - 2.0 / 3.0 * PI * 3375.0) < 1e-3, "{}", m.volume); - assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (7, 13, 9)); + // The box's 6 faces and the sphere's; its 12 edges, the rim circle and the sphere's seam down + // to its pole; its 8 corners, the rim's vertex and the pole. + assert_eq!((m.merged.faces, m.merged.edges, m.merged.vertices), (7, 14, 10)); } #[test] @@ -1575,7 +1623,9 @@ fn overlapping_holes_and_mirror_joins() { let both = boolean(&half, &other, BoolOp::Union).unwrap().unwrap(); let v = measure(&half).unwrap().volume; let mb = measure(&both).unwrap(); - assert!(rel(mb.volume, 2.0 * v) < 1e-9, "{} vs {}", mb.volume, 2.0 * v); + // Both volumes are SMLib's integrals, each good to its relative accuracy (1e-8, + // measure::ACCURACY): they agree to the two together. + assert!(rel(mb.volume, 2.0 * v) < 2e-8, "{} vs {}", mb.volume, 2.0 * v); // One body: the shared face is gone and the faces either side of it merged. assert_eq!(mb.merged.faces, 10, "{:?}", mb.merged); // Two equal cylinders on one axis, overlapping: one longer cylinder. @@ -1640,12 +1690,9 @@ fn fillet_an_open_curved_edge() { ], }; let b = extrude(&Plane::XY, &[Region2 { outer: d, holes: vec![] }], 0.0, 15.0).unwrap().pop().unwrap(); - let v0 = measure(&b).unwrap().volume; let f = fillet(&b, &[Vec3::new(0.0, 10.0, 15.0)], 2.0).unwrap(); - // (A fine tessellation: the difference of two measured volumes magnifies their error.) - let _ = v0; - let fine = |x: &Body| x.mesh(&crate::MeshTolerance::chord(0.002)).unwrap().measure().volume; - let removed = fine(&b) - fine(&f); + // Exact volumes (SMLib's, to 1e-8): the difference of two mesh volumes magnifies their sag. + let removed = measure(&b).unwrap().volume - measure(&f).unwrap().volume; // Pappus: the corner's cross-section r²(1 − π/4), its centroid 0.2234 r in from the wall. let r = 2.0; let want = r * r * (1.0 - PI / 4.0) * (10.0 - r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI))) * PI; @@ -1761,7 +1808,8 @@ fn fillet_sharp_arc_and_arc_loop() { (area(10.0) - area(10.0 - 0.5 * (1.0 - theta.cos()))) * 0.5 * theta.cos() * dt }) .sum(); - let removed = body.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume - mesh.measure().volume; + // Exact volumes (SMLib's, to 1e-8): the difference of two mesh volumes magnifies their sag. + let removed = measure(&body).unwrap().volume - measure(&blended).unwrap().volume; assert!(rel(removed, want) < 1e-3, "{removed} vs {want}"); } @@ -1877,9 +1925,9 @@ fn d_fillet_removed_reference(r: f64, steps: u32) -> f64 { #[test] fn fillet_mixed_arc_and_line_removed_volume_converges() { let body = mixed_arc_and_line_prism(); - let source_exact = PI * 100.0 * 15.0 / 2.0; let tolerances = [1e-4, 2.5e-5]; let source_volumes = tolerances.map(|tol| body.mesh(&crate::MeshTolerance::chord(tol)).unwrap().measure().volume); + let source = measure(&body).unwrap(); for r in [0.5, 0.25] { let want = d_fillet_removed_reference(r, 8192); assert!((want - d_fillet_removed_reference(r, 4096)).abs() < 1e-7, "reference quadrature must converge"); @@ -1887,23 +1935,18 @@ fn fillet_mixed_arc_and_line_removed_volume_converges() { assert!((want - 2.715578447526581).abs() < 1e-7, "{want}"); } let blended = fillet(&body, &[Vec3::new(0.0, 10.0, 15.0), Vec3::new(5.0, 0.0, 15.0)], r).unwrap(); - let mut previous = None; - for (tol, source) in tolerances.into_iter().zip(source_volumes) { - let volume = blended.mesh(&crate::MeshTolerance::chord(tol)).unwrap().measure().volume; - // Equal chord tolerances reduce (not necessarily cancel) the error from the - // unchanged walls. The convergence and exact-source checks below guard this. - let removed = source - volume; - assert!(rel(removed, want) < 1e-3, "r={r}, tol={tol}: removed {removed}, expected {want}"); - if let Some(coarser) = previous { - assert!(rel(removed, coarser) < 1e-3, "r={r}: removal has not converged: {coarser} -> {removed}"); - let exact_removed = source_exact - volume; - // The source's inscribed semicylinder loses at most pi*R*H*tol. - // Do not charge its chord error to the much smaller fillet volume. - let source_error = (source_exact - source).abs(); - assert!(source_error < PI * 10.0 * 15.0 * tol, "source chord error {source_error}"); - assert!((exact_removed - want).abs() < source_error + want * 1e-3, "r={r}: exact-source removal {exact_removed}, expected {want}"); - } - previous = Some(removed); + // The removal from the exact volumes (SMLib's, to 1e-8): the reference to a hundred + // thousandth (the blend's surfaces are SMLib's fits; their section error is + // fillet_mixed_arc_and_line_joint_preserves_both_section_radii's). + let done = measure(&blended).unwrap(); + let exact = source.volume - done.volume; + assert!(rel(exact, want) < 1e-5, "r={r}: removed {exact}, expected {want}"); + // From meshes, the removal converges on it: each mesh lies within its chord of its + // faces, so the two differ from the exact removal by at most their areas times it. + for (tol, source_mesh) in tolerances.into_iter().zip(source_volumes) { + let removed = source_mesh - blended.mesh(&crate::MeshTolerance::chord(tol)).unwrap().measure().volume; + let bound = (source.area + done.area) * tol; + assert!((removed - exact).abs() <= bound, "r={r}, tol={tol}: mesh removal {removed}, exact {exact} (within {bound})"); } } } @@ -1926,7 +1969,7 @@ fn fillet_mixed_arc_and_line_joint_preserves_both_section_radii() { if !mitres.insert(id) { continue; } - let curve = solidcraft_geom::brep::eval::CurveEval::new(&edge.curve).unwrap(); + let curve = solidcraft_geom::brep::eval::CurveEval::new(edge.parameters()).unwrap(); let [lo, hi] = edge.interval; for i in 0..=257 { let p = curve.point(lo + (hi - lo) * f64::from(i) / 257.0).unwrap(); diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs index a365f25a2..cdbcb2269 100644 --- a/crates/kernel/src/thin_face_tests.rs +++ b/crates/kernel/src/thin_face_tests.rs @@ -61,11 +61,13 @@ fn a_face_touching_its_own_edge_meshes() { let (h, dip) = (0.3175, 2.8e-7); let vertices = vec![[0.0, 0.0, 0.0], [5.0, 0.0, 0.0], [5.0, h, 0.0], [0.0, h, 0.0]]; let line = |a: usize, b: usize| PartEdge { + nurbs: None, curve: Curve::Line { start: vertices[a], end: vertices[b] }, interval: [0.0, 1.0], vertices: [a as u32, b as u32], }; let arch = PartEdge { + nurbs: None, curve: Curve::Spline { knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], points: vec![[5.0, h, 0.0], [2.5, -h - 2.0 * dip, 0.0], [0.0, h, 0.0]] }, interval: [0.0, 1.0], vertices: [2, 3], diff --git a/crates/kernel/src/thread_display_tests.rs b/crates/kernel/src/thread_display_tests.rs index 40a845d67..63f5f3cf8 100644 --- a/crates/kernel/src/thread_display_tests.rs +++ b/crates/kernel/src/thread_display_tests.rs @@ -4,114 +4,31 @@ use solidcraft_geom::tess::TessPlan; use solidcraft_geom::{Mesh, Vec3}; use std::f64::consts::{PI, TAU}; -use std::sync::Arc; -use crate::{Body, DISPLAY_ANGLE, EdgeSpec, FaceSpec, SurfSpec, sew}; +use crate::{Body, DISPLAY_ANGLE}; -/// A helix about Z of radius `r` from angle `a0` to `a1`, rising `pitch` per turn from `z0` at -/// angle 0, as cubic Bézier pieces of at most `TAU / 16`. -fn helix(r: f64, z0: f64, pitch: f64, a0: f64, a1: f64) -> EdgeSpec { - let n = (((a1 - a0).abs() / (TAU / 16.0)).ceil() as usize).max(1); - let h = (a1 - a0) / n as f64; - let k = 4.0 / 3.0 * (h / 4.0).tan(); - let at = |a: f64| Vec3::new(r * a.cos(), r * a.sin(), z0 + pitch * a / TAU); - let rise = Vec3::new(0.0, 0.0, pitch * h / TAU / 3.0); - let turn = |a: f64| Vec3::new(-a.sin(), a.cos(), 0.0) * (r * k); - let mut ctrl = vec![at(a0)]; - for i in 0..n { - let (s, e) = (a0 + h * i as f64, a0 + h * (i + 1) as f64); - ctrl.extend([at(s) + turn(s) + rise, at(e) - turn(e) - rise, at(e)]); - } - EdgeSpec::Chain { degree: 3, ctrl: ctrl.into() } -} - -fn rev(e: &EdgeSpec) -> EdgeSpec { - match e { - EdgeSpec::Chain { degree, ctrl } => EdgeSpec::Chain { degree: *degree, ctrl: ctrl.iter().rev().copied().collect::>() }, - EdgeSpec::Line { a, b } => EdgeSpec::Line { a: *b, b: *a }, - EdgeSpec::Arc { a, b, mid } => EdgeSpec::Arc { a: *b, b: *a, mid: *mid }, - } -} - -fn line(a: Vec3, b: Vec3) -> EdgeSpec { - EdgeSpec::Line { a, b } -} - -fn ends(e: &EdgeSpec) -> (Vec3, Vec3) { - match e { - EdgeSpec::Chain { ctrl, .. } => (ctrl[0], ctrl[ctrl.len() - 1]), - EdgeSpec::Line { a, b } | EdgeSpec::Arc { a, b, .. } => (*a, *b), - } -} - -/// A full circle about Z at height `z`, as two arcs. -fn circle(r: f64, z: f64) -> Vec { - let p = |a: f64| Vec3::new(r * a.cos(), r * a.sin(), z); - vec![EdgeSpec::Arc { a: p(0.3), b: p(0.3 + PI), mid: p(0.3 + PI / 2.0) }, EdgeSpec::Arc { a: p(0.3 + PI), b: p(0.3), mid: p(0.3 + 1.5 * PI) }] -} - -/// A threaded shaft the way a modelled thread usually comes out of a CAD system: an ISO metric -/// ridge (60° flanks, P/8 crest) of `turns` turns wound on a core of the minor diameter, the -/// flanks ruled B-spline surfaces between helices, the crest and the core cylinders trimmed by -/// those helices. +/// A threaded shaft the way the thread feature makes one: an ISO metric ridge (60° flanks, P/8 +/// crest) of `turns` turns wound on a core of the minor diameter, the ridge SMLib's screw sweep +/// of its section (exact helices, the flanks and crest its screw walls, flat ends in the planes +/// through the axis where it starts and stops) joined to the core cylinder, which the flanks then +/// trim along helices. The section reaches a tenth of a pitch into the core along its flanks, so +/// the join cuts it at the core rather than meeting it face to face. fn ridge_thread(major: f64, pitch: f64, turns: f64) -> Body { + use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; let h = pitch * 3f64.sqrt() / 2.0; let (rc, rm) = (major / 2.0 - 5.0 * h / 8.0, major / 2.0); let (foot, crest) = ((pitch - pitch / 4.0) / 2.0, pitch / 16.0); let z0 = pitch; let len = z0 + pitch * turns + pitch; - let end = TAU * turns; - let fl = helix(rc, z0 - foot, pitch, 0.0, end); - let fu = helix(rc, z0 + foot, pitch, 0.0, end); - let cl = helix(rm, z0 - crest, pitch, 0.0, end); - let cu = helix(rm, z0 + crest, pitch, 0.0, end); - let (fl0, fl1) = ends(&fl); - let (fu0, fu1) = ends(&fu); - let (cl0, cl1) = ends(&cl); - let (cu0, cu1) = ends(&cu); - let at = |r: f64, a: f64, z: f64| Vec3::new(r * a.cos(), r * a.sin(), z); - let mid = z0 + pitch / 2.0; - let out = |a: f64| Vec3::new(a.cos(), a.sin(), 0.0); - let flank = 0.5f64; - let faces = vec![ - FaceSpec { loops: vec![circle(rc, 0.0).iter().rev().map(rev).collect()], surface: SurfSpec::Plane, probe: None }, - FaceSpec { loops: vec![circle(rc, len)], surface: SurfSpec::Plane, probe: None }, - FaceSpec { - loops: vec![circle(rc, 0.0), circle(rc, len).iter().rev().map(rev).collect(), vec![line(fl0, fu0), fu.clone(), line(fu1, fl1), rev(&fl)]], - surface: SurfSpec::Revolved { - a: Vec3::new(rc, 0.0, -1.0), - b: Vec3::new(rc, 0.0, len + 1.0), - axis_origin: Vec3::ZERO, - axis: Vec3::Z, - angle: TAU, - }, - probe: Some((at(rc, PI, z0 * 0.5), out(PI))), - }, - FaceSpec { - loops: vec![vec![fl.clone(), line(fl1, cl1), rev(&cl), line(cl0, fl0)]], - surface: SurfSpec::Ruled { a: fl.clone(), b: cl.clone() }, - probe: Some((at((rc + rm) / 2.0, PI, mid - (foot + crest) / 2.0), out(PI) * flank - Vec3::Z * 0.866)), - }, - FaceSpec { - loops: vec![vec![cu.clone(), line(cu1, fu1), rev(&fu), line(fu0, cu0)]], - surface: SurfSpec::Ruled { a: fu.clone(), b: cu.clone() }, - probe: Some((at((rc + rm) / 2.0, PI, mid + (foot + crest) / 2.0), out(PI) * flank + Vec3::Z * 0.866)), - }, - FaceSpec { - loops: vec![vec![cl.clone(), line(cl1, cu1), rev(&cu), line(cu0, cl0)]], - surface: SurfSpec::Revolved { - a: Vec3::new(rm, 0.0, -1.0), - b: Vec3::new(rm, 0.0, len + 1.0), - axis_origin: Vec3::ZERO, - axis: Vec3::Z, - angle: TAU, - }, - probe: Some((at(rm, PI, mid), out(PI))), - }, - FaceSpec { loops: vec![vec![line(fl0, cl0), line(cl0, cu0), line(cu0, fu0), line(fu0, fl0)]], surface: SurfSpec::Plane, probe: None }, - FaceSpec { loops: vec![vec![line(fl1, fu1), line(fu1, cu1), line(cu1, cl1), line(cl1, fl1)]], surface: SurfSpec::Plane, probe: None }, - ]; - sew(&faces).unwrap() + // The ridge's half width at radius r, along its flanks. + let half = |r: f64| foot + (crest - foot) * (r - rc) / (rm - rc); + let r0 = rc - 0.1 * pitch; + let section = Loop2::polygon(&[Vec2::new(r0, -half(r0)), Vec2::new(rm, -crest), Vec2::new(rm, crest), Vec2::new(r0, half(r0))]); + let plane = Plane { origin: Vec3::new(0.0, 0.0, z0), x: Vec3::X, y: Vec3::Z }; + let ridge = crate::sweep_helix(&plane, &Region2 { outer: section, holes: Vec::new() }, Vec3::ZERO, Vec3::Z, pitch, turns).unwrap(); + let core = Region2 { outer: Loop2::circle(Vec2::ZERO, rc), holes: Vec::new() }; + let core = crate::extrude(&Plane::XY, &[core], 0.0, len).unwrap().pop().unwrap(); + crate::boolean(&core, &ridge, crate::BoolOp::Union).unwrap().unwrap() } fn tol(b: &Body) -> f64 { @@ -127,8 +44,10 @@ struct Quality { } /// Triangles thinner than 1e-3 of their longest side; triangles whose winding disagrees with -/// their vertex normals; the largest gap between a triangle's centre and the surface at the -/// centre's parameters. +/// their vertex normals; the largest gap between a triangle's centre and the surface, at the +/// surface point nearest the centre (a few Newton steps from a corner's parameters: a closed +/// surface's parameters are kept within one period, so a triangle across its seam has corners +/// whose parameters lie a period apart, and their mean is nowhere near the triangle). fn quality(plan: &TessPlan, mesh: &Mesh) -> Quality { let mut q = Quality { tris: mesh.triangles.len(), slivers: 0, flipped: 0, worst_sag: 0.0, min_angle: 180.0 }; for t in &mesh.triangles { @@ -155,8 +74,19 @@ fn quality(plan: &TessPlan, mesh: &Mesh) -> Quality { let Some(s) = f.surface.and_then(|i| plan.surfaces.get(i as usize)) else { continue }; let pos = |k: u32| f.fixed.get(k as usize).copied().unwrap_or_else(|| s.eval(f.uv[k as usize][0], f.uv[k as usize][1]).0); for t in &f.triangles { - let uv = t.iter().fold([0.0, 0.0], |m, &k| [m[0] + f.uv[k as usize][0] / 3.0, m[1] + f.uv[k as usize][1] / 3.0]); let mid = (pos(t[0]) + pos(t[1]) + pos(t[2])) * (1.0 / 3.0); + let mut uv = f.uv[t[0] as usize]; + for _ in 0..8 { + let Some((p, su, sv)) = s.derivs(uv[0], uv[1]) else { break }; + let d = mid - p; + let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv)); + let det = a * c - b * b; + if det.abs() < 1e-300 { + break; + } + let (x, y) = (su.dot(d), sv.dot(d)); + uv = [uv[0] + (c * x - b * y) / det, uv[1] + (a * y - b * x) / det]; + } let (on, n) = s.eval(uv[0], uv[1]); let sag = (on - mid).dot(n).abs(); q.worst_sag = q.worst_sag.max(sag); @@ -193,9 +123,9 @@ fn threads() -> Vec<(String, Body, f64, f64, f64)> { } /// Issue 1289: a modelled thread's faces turn several times around the shaft. The core and the -/// crest cylinders, trimmed by helices (and the core bounded by two circles without a seam -/// edge), had no display plan, and the reference mesher drew them with triangles across the -/// solid. They are now cut along a seam: the display mesh stays on the surfaces. +/// crest cylinders, trimmed by helices, had no display plan, and the reference mesher drew them +/// with triangles across the solid. They are now cut along a seam: the display mesh stays on +/// the surfaces. #[test] fn thread_display_mesh_stays_on_its_surfaces() { for (name, b, d, p, turns) in threads() { diff --git a/crates/kernel/src/thread_tests.rs b/crates/kernel/src/thread_tests.rs index 659f502e1..4816ba298 100644 --- a/crates/kernel/src/thread_tests.rs +++ b/crates/kernel/src/thread_tests.rs @@ -18,7 +18,9 @@ fn faceted_cut_of_a_helical_groove() { let section = [Vec2::new(1.2, -0.06), Vec2::new(1.6, -0.06), Vec2::new(1.6, 0.06), Vec2::new(1.2, 0.06)]; let groove = sweep_helix_mesh(&plane, §ion, base, k, p, 5.0, 48).unwrap(); let cut = faceted_boolean(&shaft, &groove, BoolOp::Cut, 1e-3).unwrap().unwrap(); - let m = cut.mesh(&crate::MeshTolerance::chord(0.01)).unwrap().measure(); + // The cut's own volume (SMLib's, of its exact faces): a mesh's at 0.01 mm sags inside the + // shaft's round wall by 0.18 mm³, five times the 3 % the groove is held to. + let m = crate::measure(&cut).unwrap(); // In the shaft from z = 0: the section (r 1.2…1.5, 0.12 tall) for 4 turns, plus the part of // the first turn's section above z = 0 (its z range is ±0.06 about the turn's height). let per_turn = 2.0 * PI * 0.12 * (1.5f64.powi(2) - 1.2f64.powi(2)) / 2.0; diff --git a/crates/kernel/tests/chamfer_curved_holder.rs b/crates/kernel/tests/chamfer_curved_holder.rs index 7006535f0..96196bb20 100644 --- a/crates/kernel/tests/chamfer_curved_holder.rs +++ b/crates/kernel/tests/chamfer_curved_holder.rs @@ -4,7 +4,7 @@ //! against the round wall instead of extending that short seam outside the solid. use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; -use solidcraft_kernel::{Body, BoolOp, boolean, chamfer, cylinder, extrude}; +use solidcraft_kernel::{Body, BoolOp, boolean, chamfer, cylinder, extrude, tangent_chain}; use std::f64::consts::PI; fn holder() -> Body { @@ -54,12 +54,19 @@ fn expected_removed(distance: f64) -> f64 { #[test] fn chamfer_the_top_lip_at_a_tangent_wall_junction() { let body = holder(); - let made = chamfer(&body, &[Vec3::new(10.0, 10.0, 60.0)], 2.0).unwrap(); + // The pick's tangent chain, as a chamfer feature selects it (the kernel blends the edges it + // is given). + let made = chamfer(&body, &tangent_chain(&body, &[Vec3::new(10.0, 10.0, 60.0)]).unwrap(), 2.0).unwrap(); assert!(made.validity().is_empty(), "{:?}", made.validity()); assert_eq!(made.crossed_face_loops().unwrap(), 0); let history = made.history().expect("the chamfer retains exact face provenance"); assert!(history.faces.iter().any(|f| f.origins.iter().any(|o| matches!(o, solidcraft_kernel::history::FaceOrigin::Edge { operand: 0, .. })))); - let mesh = |body: &Body| body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.0005)).unwrap(); + // Fine enough that the meshes' chord error is below the tolerance: the removed volume + // measured on meshes is 37.404 at chord 0.002, 37.672 at 0.0005, 37.761 at 0.0001 and 37.759 + // at 0.00003, converged on the expected 37.762 (the chamfer as the chord between the contacts + // of a 2 mm ball). The planner's meshes of the two bodies differ, so their chord errors no + // longer cancel as truck's did. + let mesh = |body: &Body| body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.0001)).unwrap(); let before = mesh(&body).measure().volume; let after = mesh(&made); let removed = before - after.measure().volume; @@ -110,7 +117,7 @@ fn plate_with_stadium(plate: f64) -> Body { fn one_chamfer_pick_follows_the_tangent_chain_at_any_part_size() { for plate in [140.0, 145.0, 250.0] { let body = plate_with_stadium(plate); - let made = chamfer(&body, &[Vec3::new(0.0, 5.0, 20.0)], 1.0).unwrap(); + let made = chamfer(&body, &tangent_chain(&body, &[Vec3::new(0.0, 5.0, 20.0)]).unwrap(), 1.0).unwrap(); assert!(made.validity().is_empty(), "{:?}", made.validity()); // Two straight edges (c^2/2 * 40 each) and both end arcs (Pappus, c^2/2 * 2 pi (R - c/3)). let expected = 40.0 + 0.5 * 2.0 * PI * (5.0 - 1.0 / 3.0); diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index d426826c4..29190e515 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1716,9 +1716,29 @@ impl Sketch { } } - /// Axis-aligned bounds of all geometry (for views). + /// Axis-aligned bounds of all geometry (for views). An arc's are exact: its polyline's points + /// need not reach the circle's extremes (a whole circle is one arc, whose chords start at its + /// start angle), so the quarter points it sweeps through are added. pub fn bounds(&self) -> Option<(Vec2, Vec2)> { - let b: Aabb2 = (0..self.curves.len()).flat_map(|i| self.segs(i)).flat_map(|s| s.polyline(0.5)).collect(); + let extremes = |s: &Seg2| -> Vec { + let Seg2::Arc { center, radius, start, sweep } = *s else { return Vec::new() }; + let (lo, hi) = if sweep >= 0.0 { (start, start + sweep) } else { (start + sweep, start) }; + let quarter = std::f64::consts::FRAC_PI_2; + let first = (lo / quarter).ceil() as i64; + let last = (hi / quarter).floor() as i64; + if !(lo.is_finite() && hi.is_finite()) || last - first > 4 { + return Vec::new(); + } + (first..=last).map(|k| center + Vec2::from_angle(k as f64 * quarter) * radius).collect() + }; + let b: Aabb2 = (0..self.curves.len()) + .flat_map(|i| self.segs(i)) + .flat_map(|s| { + let mut pts = s.polyline(0.5); + pts.extend(extremes(&s)); + pts + }) + .collect(); (!b.is_empty()).then_some((b.min, b.max)) } } diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index 29a58496e..1e5e61f09 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -1279,3 +1279,19 @@ fn a_fillet_folded_through_flat_is_refused_like_a_fold() { } assert!(refused.is_some_and(|s| (7..=9).contains(&s)), "refused at {refused:?}"); } + +/// A sketch's bounds reach a circle's and an arc's extremes, not only the points of their +/// polylines: a whole circle is one arc whose chords start at its start angle, and a circle of +/// radius 5 at (-300, 0) spans x from -305 exactly. +#[test] +fn bounds_reach_the_extremes_of_circles_and_arcs() { + let mut sk = Sketch::new(); + sk.add_circle(v(-300.0, 0.0), 5.0, None, None).unwrap(); + let (lo, hi) = sk.bounds().unwrap(); + assert!(lo.dist(v(-305.0, -5.0)) < 1e-9 && hi.dist(v(-295.0, 5.0)) < 1e-9, "{lo:?} {hi:?}"); + // A quarter arc from (10, 0) to (0, 10) about the origin: its corners, no more. + let mut sk = Sketch::new(); + sk.add_arc(v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0), [None; 3], None).unwrap(); + let (lo, hi) = sk.bounds().unwrap(); + assert!(lo.dist(v(0.0, 0.0)) < 1e-9 && hi.dist(v(10.0, 10.0)) < 1e-9, "{lo:?} {hi:?}"); +} diff --git a/crates/smlib/SMLIB_PREBUILT b/crates/smlib/SMLIB_PREBUILT index b6eb09951..207dd839f 100644 --- a/crates/smlib/SMLIB_PREBUILT +++ b/crates/smlib/SMLIB_PREBUILT @@ -1,10 +1,10 @@ # Rust target, SHA-256 of smlib-.tar.gz in the release prebuilt- of # tangency-labs/smlib. Written by scripts/fetch-smlib.sh --pin; never edited by hand. -aarch64-apple-darwin 5d58858aa07df01802bbda6349d706f0325b5a2cab32ae61b97e46fc7931be20 -aarch64-pc-windows-msvc a888acec73e95960c1bafb82f4436ae3690a3ad6cca53fa11df612ba783202c7 -aarch64-unknown-linux-gnu fb840ddc12ce2e20b3d8a986c4481919b80b401bf49601479feabc09f5bcacd1 -i686-pc-windows-msvc b45081e2daf5770204e8adc60ff9c30f782351b01ef36448a7188549efd9e5f2 -wasm32-unknown-unknown a8b9ccd974894f3986d6690765bad788b8b5b119433b74c219c0387a10a8ef33 -x86_64-apple-darwin 2bc0eddedc9905a8a2217419da9e2b6c2ef73ff745ae428f117ae0c9588b83d5 -x86_64-pc-windows-msvc e65325a734e2d16232b4ec976f676e1d50a5a6bbdd1423266547e9fa35623a8f -x86_64-unknown-linux-gnu 9a0d125698d83bd58ded8c95c4c19f6002fe9a8751031b5df5f6b1bb5633442f +aarch64-apple-darwin d5f9ee5b49f2b1b9777a27942401516a59384105c2dce58a6bd571efe7d77aa8 +aarch64-pc-windows-msvc d5df522ed4459dad9ffba4d5b22c05f8bebcf4d5ba217f62395c2ea689492f14 +aarch64-unknown-linux-gnu b7849d6dbdb358380b7352742dccfd33a71bc423e1fda18566fcd58a0b406ff3 +i686-pc-windows-msvc 6b7cb77f7fd05f5f458689e49547ec9d9d4920f28cd79f5c16ae44fa8682bc46 +wasm32-unknown-unknown 63f9c65ae041d1db4b8ffb7306bd6a4f4b7f125f6fb1772ca5dcc14763c76bd6 +x86_64-apple-darwin 99a5e32ae73c82f9020a046245312cb5352974069a464af3ac9da1f624800ad1 +x86_64-pc-windows-msvc 828211a338c42be882eb9084fef89087479b713dd641bb3aa0b3b2b70a2b3bfa +x86_64-unknown-linux-gnu f69203a49aa1c1a4272364cb13585c84557c466f4863adc66cb1a5f623462289 diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV index af859a2f5..4ae676f19 100644 --- a/crates/smlib/SMLIB_REV +++ b/crates/smlib/SMLIB_REV @@ -1 +1 @@ -5afca53ff480524e5afd33c0c4f413904a01de69 +7e917f0a308d620491fdbc07c5e07fb29a2b8300 diff --git a/crates/smlib/src/check.rs b/crates/smlib/src/check.rs index 09f3c24fa..fd714ee58 100644 --- a/crates/smlib/src/check.rs +++ b/crates/smlib/src/check.rs @@ -28,6 +28,19 @@ impl CheckReport { pub fn is_valid(&self) -> bool { self.failures == 0 } + + /// The number of each failed test, line by line (`SmBrep::Test #82 …` is 82); a line without + /// one is left out. + pub fn failed_tests(&self) -> Vec { + self.text + .lines() + .filter_map(|l| { + let rest = l.split_once("Test #")?.1; + let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); + digits.parse().ok() + }) + .collect() + } } impl std::fmt::Display for CheckReport { diff --git a/crates/smlib/src/export.rs b/crates/smlib/src/export.rs index f394aa115..75d417dbd 100644 --- a/crates/smlib/src/export.rs +++ b/crates/smlib/src/export.rs @@ -313,8 +313,9 @@ fn surfaces(flat: View, n_faces: usize) -> Res Res<(Vec<(b::Curve, Option, [ } } CURVE_NURBS => { - let c = next_nurbs()?; + let c = next_nurbs()?.record(); // A NURBS edge stays the NURBS SMLib holds, its trims on its own parameter: SMLib // gives lines, circles and ellipses as their own kinds, and nothing is recognised here. + // SMLib's interval may start or end a rounding past its knots (a variable round's + // end trimmed by a cylinder, ladder 07-fillets/012: 7e-15 before the first knot). kept += 1; - (c.record(), None, r, Some([1.0, 0.0])) + let r = onto(r, c.natural()); + (c, None, r, Some([1.0, 0.0])) } other => return Err(unsupported(format!("SMLib curve kind {other}"))), }); @@ -564,8 +568,8 @@ fn mapped(trim: &b::Curve2, same: bool, [scale, offset]: [f64; 2], [t0, t1]: [f6 }) } -/// A domain side moved onto the natural range where it overshoots it by rounding (a sphere's -/// latitudes, a cone's apex). +/// A domain side or an edge's interval moved onto the natural range where it overshoots it by +/// rounding (a sphere's latitudes, a cone's apex, a NURBS edge's end knots). fn onto(r: [f64; 2], natural: b::Natural) -> [f64; 2] { match natural { b::Natural::Range(lo, hi) => { diff --git a/crates/smlib/src/export/tests.rs b/crates/smlib/src/export/tests.rs index 867543589..ff22d1832 100644 --- a/crates/smlib/src/export/tests.rs +++ b/crates/smlib/src/export/tests.rs @@ -82,10 +82,19 @@ mod native_tests { fn edges_are_on_smlibs_curves() { let cyl = Brep::make_cylinder([0.0; 3], 5.0, 10.0).unwrap().to_native().unwrap(); let side = cyl.faces.iter().find(|f| matches!(f.surface, b::Surface::Cylinder { .. })).unwrap(); - assert!((side.domain[0][1] - side.domain[0][0] - TAU).abs() < 1e-12); - assert_eq!(side.domain[1], [0.0, 10.0]); + // The side is on SMLib's NURBS form of the cylinder (its domain is the form's): the whole + // turn, so its domain's two u ends meet, from the base to the top. + let form = b::eval::SurfaceEval::new(side.parameters()).unwrap(); + let [[u0, u1], [v0, v1]] = side.domain; + for v in [v0, v1] { + let (a, z) = (form.point([u0, v]).unwrap(), form.point([u1, v]).unwrap()); + assert!(a.dist(z) < 1e-9, "{a:?} {z:?}"); + } + let heights = [form.point([u0, v0]).unwrap().z, form.point([u0, v1]).unwrap().z]; + assert!(heights.iter().any(|h| h.abs() < 1e-9) && heights.iter().any(|h| (h - 10.0).abs() < 1e-9), "{heights:?}"); for e in &cyl.edges { - let eval = b::eval::CurveEval::new(&e.curve).unwrap(); + // Evaluated on the curve its interval is on (a circle's NURBS form). + let eval = b::eval::CurveEval::new(e.parameters()).unwrap(); let [a, z] = e.interval; // Ends on the edge's vertices. for (t, v) in [(a, e.vertices[0]), (z, e.vertices[1])] { @@ -94,6 +103,7 @@ mod native_tests { assert!((p - Vec3::new(q[0], q[1], q[2])).len() < 1e-9, "{:?} at {t}", e.curve); } if let b::Curve::Circle { radius, .. } = e.curve { + let [a, z] = e.curve_interval().unwrap(); assert!((radius - 5.0).abs() < 1e-12 && (z - a - TAU).abs() < 1e-9); } } @@ -103,6 +113,16 @@ mod native_tests { assert!((half.unwrap() + 0.5f64.atan()).abs() < 1e-12); } + /// A cone whose half angle is within rounding of zero (a52's thread bosses: 1e-13) is exported as + /// a cylinder; as a cone the portable record's validation refuses it. + #[test] + fn a_cone_of_rounding_angle_is_exported_as_a_cylinder() { + let near = Brep::make_cone([0.0; 3], 4.0, 4.0 - 1e-12, 10.0).unwrap().to_native().unwrap(); + assert!(near.faces.iter().any(|f| matches!(f.surface, b::Surface::Cylinder { .. }))); + assert!(!near.faces.iter().any(|f| matches!(f.surface, b::Surface::Cone { .. }))); + near.validate().unwrap(); + } + /// A hole tangent to the block's outline from inside: the material touches itself along the /// tangent line, where SMLib's one shell uses the edge four times. The record has two copies /// of that edge, each bounding one wedge of material (a face of the side and the half of the @@ -126,7 +146,8 @@ mod native_tests { p[0].abs() < 1e-9 && (p[1] - 14.5).abs() < 1e-9 }) }; - let middle = |e: &b::Edge| b::eval::CurveEval::new(&e.curve).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap(); + // On the curve the interval is on (a circle's NURBS form). + let middle = |e: &b::Edge| b::eval::CurveEval::new(e.parameters()).unwrap().point(0.5 * (e.interval[0] + e.interval[1])).unwrap(); let copies: Vec<&b::Edge> = record.edges.iter().filter(|e| on_line(e)).collect(); assert_eq!(copies.len(), 2); for copy in copies { @@ -227,6 +248,49 @@ mod native_tests { assert!((got - want).abs() < 1e-6 * want, "volume {got} vs {want}"); } + /// The variable round r1 -> r5 along a box's top back edge run on into the R5 round of its + /// corner (ladder 07-fillets/012): its end trimmed by the R5 cylinder is a NURBS edge, whose + /// interval SMLib gave 7e-15 before the first knot. The record's interval is the NURBS's own + /// where it overshoots it by rounding, and the record validates; farther past it stays an error. + #[test] + fn a_nurbs_edge_interval_a_rounding_past_its_knots_is_moved_onto_them() { + let block = Brep::make_box([0.0; 3], [60.0, 40.0, 20.0]).unwrap(); + let rounded = block.fillet(&[[60.0, 40.0, 10.0]], 0.1, 5.0).unwrap(); + let r = rounded.fillet_variable([27.5, 40.0, 20.0], 0.1, [0.0, 40.0, 20.0], 1, &[0.0, 0.0, 1.0, 1.0], &[1.0, 5.0]).unwrap(); + let arrays = r.arrays().unwrap(); + let kinds = arrays.ints.get(&EDGE_CURVE_TYPE).cloned().unwrap_or_default(); + let counts = arrays.ints.get(&EDGE_NURBS_VERTEX_COUNT).cloned().unwrap_or_default(); + let orders = arrays.ints.get(&EDGE_NURBS_ORDER).cloned().unwrap_or_default(); + let forms = arrays.ints.get(&EDGE_NURBS_FORM).cloned().unwrap_or_default(); + let knots = arrays.reals.get(&EDGE_NURBS_KNOTS).cloned().unwrap_or_default(); + // Each NURBS block's first and last knots of its domain, in edge order. + let (mut at, mut block_of) = (0usize, Vec::new()); + for (n, o) in counts.iter().zip(&orders) { + let (n, o) = (*n as usize, *o as usize); + block_of.push((knots[at + o - 1], knots[at + n])); + at += n + o; + } + let mut nurbs = 0usize; + let mut edge = None; + for (e, kind) in kinds.iter().enumerate() { + let has_block = *kind == CURVE_NURBS || forms.get(e) == Some(&1); + if *kind == CURVE_NURBS && edge.is_none() { + edge = Some((e, block_of[nurbs])); + } + nurbs += usize::from(has_block); + } + let (e, (first, last)) = edge.expect("the round's end on the cylinder is a NURBS edge"); + let shifted = |by: f64| { + let mut a = arrays.clone(); + a.reals.get_mut(&EDGE_RANGE).unwrap()[2 * e] = first - by; + a + }; + let (record, _) = native(&shifted(7e-15)).unwrap(); + record.validate().unwrap(); + assert!(record.edges.iter().any(|x| x.interval[0] == first && x.interval[1] <= last), "an interval on the NURBS's first knot"); + assert!(native(&shifted(1e-3)).map(|(r, _)| r.validate()).map_or(true, |v| v.is_err()), "a real overshoot is not moved"); + } + #[test] fn hostile_arrays_are_errors_never_panics() { let good = Brep::make_box([0.0; 3], [1.0, 2.0, 3.0]).unwrap().arrays().unwrap(); diff --git a/crates/smlib/src/ffi/ops.rs b/crates/smlib/src/ffi/ops.rs index 9f6c2303e..22ac7ca9f 100644 --- a/crates/smlib/src/ffi/ops.rs +++ b/crates/smlib/src/ffi/ops.rs @@ -20,6 +20,7 @@ pub const ERR_NO_CUT: i32 = -1104; pub const ERR_UNSUPPORTED: i32 = -1105; pub const ERR_NO_EFFECT: i32 = -1107; pub const ERR_WALLS_TOUCH: i32 = -1110; +pub const ERR_CORNER_UNSUPPORTED: i32 = -1111; pub const BOOLEAN_UNION: i32 = 0; pub const BOOLEAN_SUBTRACT: i32 = 1; diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs index 7243f2801..76fdc5f7a 100644 --- a/crates/smlib/src/lib.rs +++ b/crates/smlib/src/lib.rs @@ -60,6 +60,8 @@ pub enum Error { WallsTouch, /// SMLib cannot build this exactly yet (a variable radius whose law has a corner). Unsupported, + /// A blend's edges meet at a vertex of a kind no SMLib blend corner handles yet. + CornerUnsupported, /// SMLib does not set back the corner of corner point `corner`: SMLib sets back a corner /// only where every edge meeting it is blended and they are all convex or all concave. CornerRefused { corner: usize }, @@ -98,6 +100,7 @@ impl std::fmt::Display for Error { Error::NoRoom => write!(f, "there is no room for it: an offset leaves none inside the body, or a blend is larger than its faces allow"), Error::WallsTouch => write!(f, "the offset's walls would meet along a line, which leaves no solid there"), Error::Unsupported => write!(f, "not supported yet: SMLib cannot build this exactly"), + Error::CornerUnsupported => write!(f, "not supported yet: a corner of this kind is not supported yet by SMLib's blends"), Error::CornerRefused { corner } => write!( f, "not supported yet: SMLib does not set back corner {}: it sets back a corner only where every edge meeting it is blended, all convex or all concave", @@ -137,6 +140,7 @@ fn error(s: i32) -> Error { ffi::ops::ERR_NO_ROOM => Error::NoRoom, ffi::ops::ERR_WALLS_TOUCH => Error::WallsTouch, ffi::ops::ERR_UNSUPPORTED => Error::Unsupported, + ffi::ops::ERR_CORNER_UNSUPPORTED => Error::CornerUnsupported, ffi::ops::ERR_NO_EFFECT => Error::NoEffect, ffi::trim::ERR_NOT_EXACT => Error::NotExact, ffi::ERR_EXCEPTION => Error::Exception, diff --git a/crates/smlib/src/ops_tests.rs b/crates/smlib/src/ops_tests.rs index 8e75bf6c4..85e3ab4b6 100644 --- a/crates/smlib/src/ops_tests.rs +++ b/crates/smlib/src/ops_tests.rs @@ -206,11 +206,15 @@ fn hostile_inputs_are_errors() { for t in [0.0, f64::NAN, -1e7] { assert_eq!(c.shell(&[[10.0, 10.0, 20.0]], 0.1, t).unwrap_err(), Error::Argument, "thickness {t}"); } - // Sizes SMLib cannot build fail as errors, whatever SMLib says. - match c.fillet(&mid, 0.1, 50.0) { - Ok(b) => panic!("radius larger than the cube: SMLib built a body of volume {:?}, counts {:?}", b.volume(ACC), b.counts()), - Err(e) => eprintln!("radius larger than the cube: {e:?}"), - } + // A round larger than the cube overflows its faces' far edges, convex, so it is cut as if the + // faces went on: the r50 cylinder about y = z = -30 uses up both faces of the edge and leaves + // the part of the cube's 20 x 20 section inside it, from (0, 10) to (10, 0), along x: 20 x + // that area, 20 (F(40) - F(30) - 300) with F(u) = (u sqrt(2500 - u^2) + 2500 asin(u / 50)) / 2. + let over = c.fillet(&mid, 0.1, 50.0).unwrap(); + let f = |u: f64| 0.5 * (u * (2500.0 - u * u).sqrt() + 2500.0 * (u / 50.0).asin()); + let want = 20.0 * (f(40.0) - f(30.0) - 300.0); + assert!((volume(&over) - want).abs() < 1e-6 * want, "radius larger than the cube: {} vs {want}", volume(&over)); + assert_eq!(over.counts().unwrap(), [5, 9, 6], "the two ends, the two far faces and the round"); // A chamfer past the faces runs over their far edges, cliffs: it is cut as if the faces went // on (the plane y + z = 10 through the setbacks 30 back from the edge y = z = 20), leaving the // triangle y + z <= 10 of the cube's section along x: 50 x 20. diff --git a/crates/step/src/p21.rs b/crates/step/src/p21.rs index add33a46c..fec135fec 100644 --- a/crates/step/src/p21.rs +++ b/crates/step/src/p21.rs @@ -122,6 +122,10 @@ pub struct Exchange { pub schemas: Vec, /// FILE_NAME originating system. pub originating_system: String, + /// FILE_NAME preprocessor version. + pub preprocessor: String, + /// FILE_DESCRIPTION text, its lines joined by a space. + pub description: String, pub entities: HashMap, /// Ids defined more than once (the first definition is kept). pub duplicates: Vec, @@ -441,7 +445,13 @@ pub fn parse_with(text: &str, watch: Option<&dyn Progress>) -> Result { + if let Some(Param::List(v)) = params.first() { + ex.description = v.iter().filter_map(|p| p.as_str()).collect::>().join(" "); + } + } "FILE_NAME" => { + ex.preprocessor = params.get(4).and_then(Param::as_str).unwrap_or("").to_string(); ex.originating_system = params.get(5).and_then(Param::as_str).unwrap_or("").to_string(); } _ => {} diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 05564e2d6..958d890b0 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -2293,12 +2293,17 @@ fn the_picks_go_with_the_next_message_once() { } /// Two clicks on two rims are two things, not four edges (a click on a rim selects both halves for -/// the commands; the chat counts and describes what was clicked). +/// the commands; the chat counts and describes what was clicked). The cylinder is a circle drawn +/// as two half arcs, extruded, so each rim is in two halves. #[test] fn a_rim_clicked_once_is_one_item_not_its_pieces() { use solidcraft_engine::Sel; let (mut app, script, ctx) = app_with_script(); - app.run("solid.cylinder", json!({"radius": 10, "height": 20})).expect("a cylinder"); + app.run("sketch.create", json!({"plane": "XY"})).expect("a sketch"); + app.run("sketch.arc.three_point", json!({"start": [10, 0], "end": [-10, 0], "through": [0, 10]})).expect("an arc"); + app.run("sketch.arc.three_point", json!({"start": [-10, 0], "end": [10, 0], "through": [0, -10]})).expect("an arc"); + app.run("sketch.finish", json!({})).expect("the sketch"); + app.run("solid.extrude", json!({"distance": 20})).expect("a cylinder"); let (name, top, bottom, mid_top, mid_bottom) = { let st = crate::open_meshing::session_world(&app.session); let body = &st.bodies[0]; diff --git a/crates/ui-egui/src/colour_tokens_tests.rs b/crates/ui-egui/src/colour_tokens_tests.rs index fe4343871..f315fe197 100644 --- a/crates/ui-egui/src/colour_tokens_tests.rs +++ b/crates/ui-egui/src/colour_tokens_tests.rs @@ -274,9 +274,10 @@ fn every_engine_colour_tag_is_placed() { "AXIS_Y", "AXIS_Z", ]; - // Bodies, edges, profiles, the grid and the background: the GPU viewport draws these from - // their own tokens; the engine's values are only the headless snapshot's. - const NEUTRAL: &[&str] = &["BODY", "BODY_SELECTED", "EDGE", "PROFILE", "GRID", "GRID_MAJOR", "BG_TOP", "BG_BOTTOM", "SECTION_CAP"]; + // Bodies, edges, profiles, the grid, the background and Isocurve Analysis curves (the accent): + // the GPU viewport draws these from their own tokens; the engine's values are only the + // headless snapshot's. + const NEUTRAL: &[&str] = &["BODY", "BODY_SELECTED", "EDGE", "PROFILE", "GRID", "GRID_MAJOR", "BG_TOP", "BG_BOTTOM", "SECTION_CAP", "ISOCURVE"]; let src = include_str!("../../engine/src/view.rs"); let start = src.find("pub mod colors {").unwrap_or(0); let block = &src[start..]; diff --git a/crates/ui-egui/src/dialogs_coupling_tests.rs b/crates/ui-egui/src/dialogs_coupling_tests.rs index f6c2f973a..b95f3bd35 100644 --- a/crates/ui-egui/src/dialogs_coupling_tests.rs +++ b/crates/ui-egui/src/dialogs_coupling_tests.rs @@ -54,8 +54,9 @@ fn picked_gear_faces_choose_their_joints_and_radii() { let mut app = discs(); app.start("joint.gear"); let mut d = app.dialog.take().unwrap(); - // G2 first, G1 second: the joints follow the picks, whatever the dialog started on. - for (i, p) in [Vec3::new(50.0, 0.0, 2.5), Vec3::new(10.0, 0.0, 2.5)].into_iter().enumerate() { + // G2 first, G1 second: the joints follow the picks, whatever the dialog started on. The + // discs touch at x = 10, on both walls, so G1 is picked on its far side. + for (i, p) in [Vec3::new(50.0, 0.0, 2.5), Vec3::new(-10.0, 0.0, 2.5)].into_iter().enumerate() { d.active = i; let pick = wall(&app, p); d.pick(&app.session, pick); diff --git a/crates/ui-egui/src/dialogs_frame_tests.rs b/crates/ui-egui/src/dialogs_frame_tests.rs index 4a825f55c..6cfdd64df 100644 --- a/crates/ui-egui/src/dialogs_frame_tests.rs +++ b/crates/ui-egui/src/dialogs_frame_tests.rs @@ -139,7 +139,11 @@ fn a_whole_sketch_section_stays_whole_through_an_edit() { let c = apply_commands(&app, &e).unwrap(); assert!(c[0].1["params"].get("profiles").is_none(), "{}", c[0].1); run_all(&mut app, c); - assert!((volume(&mut app) - before).abs() < 1e-6 * before, "still the ring, not the filled circle"); + // To the accuracy SMLib measures at (1e-4 relative, the finest it takes: kernel + // `measure::ACCURACY`); the ring's exact π (20² − 17²) 600 = 209230.07 mm³ came out + // 209229.86 before the turn and 209230.43 after it. The filled circle would be 3.6 times it. + let after = volume(&mut app); + assert!((after - before).abs() < 1e-4 * before, "still the ring, not the filled circle: {after} mm³, {before} before"); // Unticked, the section is a built-in profile again. let mut e = edit_dialog(&app, f, None).unwrap(); member(&mut e).whole = None; diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs index 47f697b42..10b7d1568 100644 --- a/crates/ui-egui/src/dialogs_motion.rs +++ b/crates/ui-egui/src/dialogs_motion.rs @@ -1103,10 +1103,11 @@ mod tests { assert!(matches!(&target.certificate, Some(solidcraft_engine::doc::config::FaceCertificate::ExtrudeSide { curve, .. }) if curve == "outer")); let state = h.app.session.model.state(); let body = state.body("Ring").unwrap(); + // The outer circle, one closed curve, is one wall face. let indices = h.app.session.doc.configuration_face_indices(body, target).unwrap(); - assert_eq!(indices.len(), 2); + assert_eq!(indices.len(), 1); let painted = h.app.session.doc.face_colors(body); - assert_eq!(painted.len(), 2); + assert_eq!(painted.len(), 1); assert!(painted.iter().all(|(index, _)| indices.contains(index))); } diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index b2b75dd13..b5678aa22 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -144,6 +144,13 @@ fn patch_orders() -> Vec { Construction::Patch.offered() } +/// The patch's hover text: each order's line, then what the patch reaches at a corner whose +/// faces meet each other with different curvatures (tangent only: no surface smooth at the corner +/// has both curvatures there). +fn patch_continuity_tip() -> String { + format!("{}\n{}", ui_kit::continuity_tip(&patch_orders()), crate::i18n::tr("ui.patch_continuity_corner_tip")) +} + fn blend_orders() -> Vec { Construction::Bridge.offered() } @@ -284,7 +291,7 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool { ui_kit::options(ui, "untrim_options", &mut [("Restore outer boundary", outer), ("In place (surfaces)", in_place)]); } Surf::Patch { continuity } => { - ui_kit::continuity_row(ui, "Continuity", "pa_cont", continuity, &patch_orders()); + ui_kit::continuity_row_explained(ui, "Continuity", "pa_cont", continuity, &patch_orders(), &patch_continuity_tip()); } Surf::Blend { continuity, bulge, stitch } => { let [from, to] = continuity; @@ -1116,5 +1123,9 @@ mod tests { } } assert_eq!(ui_kit::continuity_tip(&blend_orders()).lines().count(), 4); + // The patch's hover text adds what it does at a corner whose faces' curvatures differ. + let tip = patch_continuity_tip(); + assert_eq!(tip.lines().count(), patch_orders().len() + 1, "{tip}"); + assert!(tip.lines().last().is_some_and(|l| l.contains("corner") && l.contains("G1")), "{tip}"); } } diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs index ad5d749db..79819bd3c 100644 --- a/crates/ui-egui/src/dimension_create_ui_tests.rs +++ b/crates/ui-egui/src/dimension_create_ui_tests.rs @@ -1248,15 +1248,17 @@ fn a_driven_shown_dimension_is_read_only() { assert_eq!(h.app.session.doc.to_json(), doc); } -/// The value applies like any other change: the fillet it breaks reports its error on the -/// timeline, and Undo brings back the value and the fillet. +/// The value applies like any other change: the shell it breaks reports its error on the +/// timeline, and Undo brings back the value and the shell. The plate's 10 width taken to 3 leaves +/// no room inside two 2 thick walls. (A round wider than its face no longer breaks: a convex +/// round runs over the face's far edge, cut as if the face went on.) #[test] fn a_shown_dimension_that_breaks_a_later_feature_reports_it_and_undoes() { let (mut h, _) = shown_dimensions(); - h.app.run("solid.fillet", json!({"edges":[[10,10,5]],"radius":4,"name":"Round"})).unwrap(); + h.app.run("solid.shell", json!({"faces":[[10,1,5]],"thickness":2,"name":"Hollow"})).unwrap(); h.settle(); - let round = h.app.session.doc.features.iter().find(|f| f.name == "Round").unwrap().id; - let failed = |h: &Harness| h.app.session.model.result(round).is_some_and(|r| r.error.is_some()); + let hollow = h.app.session.doc.features.iter().find(|f| f.name == "Hollow").unwrap().id; + let failed = |h: &Harness| h.app.session.model.result(hollow).is_some_and(|r| r.error.is_some()); assert!(!failed(&h)); let before = h.app.session.doc.to_json(); let at = model_text(&h, "d2"); @@ -1265,10 +1267,10 @@ fn a_shown_dimension_that_breaks_a_later_feature_reports_it_and_undoes() { h.step(&json!({"key":"Enter"})).unwrap(); h.settle(); assert_eq!(h.app.session.doc.param("d2").unwrap().expr, "3"); - assert!(failed(&h), "the fillet no longer fits and says so"); + assert!(failed(&h), "the shell no longer has room and says so"); assert_eq!(h.app.session.active_sketch, None); h.app.run("edit.undo", json!({})).unwrap(); h.settle(); assert_eq!(h.app.session.doc.to_json(), before); - assert!(!failed(&h), "undo brings the fillet back"); + assert!(!failed(&h), "undo brings the shell back"); } diff --git a/crates/ui-egui/src/hole_place_ui_tests.rs b/crates/ui-egui/src/hole_place_ui_tests.rs index edf780914..58254ed2f 100644 --- a/crates/ui-egui/src/hole_place_ui_tests.rs +++ b/crates/ui-egui/src/hole_place_ui_tests.rs @@ -304,6 +304,9 @@ fn the_dialog_shows_the_sizes_beside_a_section_of_the_hole() { #[test] fn tapped_thread_depth_field_keeps_focus_and_typing_separate_from_acceptance() { let mut h = Harness::new(); + // Tall enough for the tapped hole's rows and its section, so the partial depth field shows + // above the dialog's footer (at 1000 px it scrolls under OK, and has no handle). + h.call("ui.resize", json!({"width": 1600, "height": 1400})); h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); let hole = h.app.run("solid.hole", json!({"position":[20,15,20],"thread":"M6","depth":12})).unwrap()["feature"].as_u64().unwrap(); let original = h.app.session.doc.to_json(); diff --git a/crates/ui-egui/src/hole_placement_ui_tests.rs b/crates/ui-egui/src/hole_placement_ui_tests.rs index 954972419..7baa15c37 100644 --- a/crates/ui-egui/src/hole_placement_ui_tests.rs +++ b/crates/ui-egui/src/hole_placement_ui_tests.rs @@ -796,7 +796,9 @@ fn select_other_over_a_dense_cluster_looks_the_face_up_once() { // not the face's or the body's; every point on the face is still counted. let mut c = cylinder_with_cluster(json!({"plane": {"face": [0, 0, 20]}}), [5.0, 4.0], "top"); let (many, body, face, near) = (c.many, c.body_tris, c.face_tris, c.near_tris); - assert!(body >= 4 * face && 4 * near <= face, "{body} triangles in the body, {face} in the face, {near} of them near the points"); + // The top cap is one of the cylinder's three faces (the planner meshes both caps alike), under + // a third of its triangles; the points lie on a small part of it. + assert!(body >= 3 * face && 4 * near <= face, "{body} triangles in the body, {face} in the face, {near} of them near the points"); let (list, (lookups, tested)) = c.select_other(); assert_eq!((rows_named(&list, "Point"), rows_named(&list, "Face")), (crate::select_other::MAX_PER_KIND, 1), "{list}"); assert_eq!(list["total"], json!(many + 1), "every point on the face is counted: {list}"); diff --git a/crates/ui-egui/src/refused_part.rs b/crates/ui-egui/src/refused_part.rs index ee5b2c2db..98c45b6ae 100644 --- a/crates/ui-egui/src/refused_part.rs +++ b/crates/ui-egui/src/refused_part.rs @@ -9,7 +9,7 @@ use solidcraft_engine::doc::{FeatureKind, ModelState, PlaneRef}; use crate::SolveApp; -/// The command that repairs a part (planned). +/// The command that repairs a part (Repair Part). pub(crate) const REPAIR: &str = "body.repair"; /// A part an operation uses that the kernel refuses. @@ -102,7 +102,7 @@ pub(crate) fn next_frame(app: &mut SolveApp, ctx: &egui::Context) { } } -/// Repair the part (the command says when it cannot yet). +/// Repair the part with the command's defaults (it says why when nothing applies). pub(crate) fn repair(app: &mut SolveApp, body: &str) { if let Err(e) = app.run(REPAIR, json!({ "body": body })) { app.set_status(e, true); diff --git a/crates/ui-egui/src/round_pick_tests.rs b/crates/ui-egui/src/round_pick_tests.rs index 00bb3efac..f48c62663 100644 --- a/crates/ui-egui/src/round_pick_tests.rs +++ b/crates/ui-egui/src/round_pick_tests.rs @@ -24,7 +24,9 @@ fn shaft() -> Harness { h } -/// The shaft's wall, top rim and top cap, as picks. +/// The shaft's wall, top rim and top cap, as picks. The rim is picked at the middle of its +/// polyline: its first point is the vertex where the wall's seam meets it, as near the seam as +/// the rim. fn picks(h: &Harness) -> (Sel, Sel, Sel) { use solidcraft_engine::kernel::{FaceSurface, face_surface}; let st = h.app.session.world_state().unwrap(); @@ -42,7 +44,7 @@ fn picks(h: &Harness) -> (Sel, Sel, Sel) { .enumerate() .find_map(|(index, e)| { let c = solidcraft_engine::kernel::edge_circle(&b.body, index)?; - (c.center.z > 9.0).then(|| Sel::Edge { body: "Shaft".into(), index, point: e[0] }) + (c.center.z > 9.0).then(|| Sel::Edge { body: "Shaft".into(), index, point: crate::viewport::polyline_mid(e) }) }) .unwrap(); (wall, rim, cap) diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index faa4ea936..396ebf9b0 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -3,6 +3,7 @@ use super::*; use crate::ui_kit::{Container, Surface}; use crate::{scenario, theme::Tokens}; use egui::{Ui, vec2}; +use solidcraft_engine::kernel::Continuity; struct Sample { value: String, @@ -839,6 +840,35 @@ const ELEMENTS: &[Element] = &[ hint_field(ui, &mut s.value, "Length"); }); }), + element!("checked_field", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| { + row(ui, "Gallery", |ui| { + checked_field(ui, &mut s.value, "Length", s.checked); + }); + }), + element!("checked_row", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| { + checked_row(ui, "Gallery", &mut s.value, "Length", Some("Too small")); + }), + element!("warning_caption", "dialog:caption:Gallery", None, |ui, _| { + warning_caption(ui, "Gallery", "Too small"); + }), + element!("text_field_tip", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| { + row(ui, "Gallery", |ui| { + text_field_tip(ui, &mut s.value, "Name", "What it is called"); + }); + }), + element!("continuity_row", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, _| { + let mut order = Continuity::G1; + continuity_row(ui, "Gallery", "gallery_continuity", &mut order, &[Continuity::G0, Continuity::G1, Continuity::G2]); + }), + element!("continuity_row_explained", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, _| { + let mut order = Continuity::G2; + let allowed = [Continuity::G1, Continuity::G2]; + continuity_row_explained(ui, "Gallery", "gallery_continuity", &mut order, &allowed, &continuity_tip(&allowed)); + }), + element!("continuity_tip", "dialog:row:Gallery", None, |ui, _| { + let tip = continuity_tip(&[Continuity::G0, Continuity::G1]); + row(ui, "Gallery", |ui| ui.label(tip)); + }), element!("text_field", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| { row(ui, "Gallery", |ui| { text_field(ui, &mut s.value, "Name"); @@ -1021,6 +1051,9 @@ const ELEMENTS: &[Element] = &[ element!("progress", "dialog:progress:gallery", None, |ui, _| { progress(ui, "gallery", 0.4); }), + element!("steps", "dialog:step:gallery:0:done", None, |ui, _| { + steps(ui, "gallery", &["Read", "Mesh", "Show"], 1, Some("40%")); + }), element!("hint", "dialog:hint:gallery", Some("dialog:hint:gallery"), |ui, _| { text(ui, "Pick a point", Text::Hint("gallery")); }), diff --git a/crates/ui-egui/src/ui_kit/layout.rs b/crates/ui-egui/src/ui_kit/layout.rs index 97152d656..638137b73 100644 --- a/crates/ui-egui/src/ui_kit/layout.rs +++ b/crates/ui-egui/src/ui_kit/layout.rs @@ -351,7 +351,13 @@ pub(super) fn named_control(ui: &mut Ui, label: &str, add: impl FnOnce(&mut U /// Publish geometry without replacing native accessibility. Tokens: `none`. pub(super) fn publish_geometry(ui: &Ui, response: &Response) { let label = label(ui); - scenario::publish_target_as(&format!("dialog:{label}"), &format!("dialog:widget:{label}"), response.rect); + scenario::publish_rect(&format!("dialog:widget:{label}"), response.rect); + // A click lands where the field shows: a field scrolled out of a dialog's field area, under + // its footer, has no handle (a click at its centre would press the button over it). + let shown = response.rect.intersect(ui.clip_rect()); + if shown.is_positive() { + scenario::publish_handle(&format!("dialog:{label}"), shown.center()); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index b796e7011..4a59d6adf 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2642,9 +2642,6 @@ fn analysis_uniform(app: &SolveApp) -> [f32; 8] { solidcraft_gpu::view::analysis_uniform(app.session.analysis.map(|a| a.mode()), crate::access::map(app).as_ref()) } -/// While Draft, Accessibility or Curvature Map analysis is on, what each of its colours means and -/// the values it stands for, at the bottom left of the viewport (#973). The colours alone don't -/// say, and with colour vision loss they can be hard to tell apart. /// Why the model cannot be placed, across the bottom of the viewport, while it cannot: the /// viewport then shows no placed bodies (see `open_meshing::session_world`). fn placement_note(app: &SolveApp, painter: &egui::Painter, rect: Rect) { @@ -2654,6 +2651,9 @@ fn placement_note(app: &SolveApp, painter: &egui::Painter, rect: Rect) { painter.text(pos2(rect.center().x, rect.bottom() - 24.0), Align2::CENTER_BOTTOM, text, FontId::proportional(t.font_button), t.error); } +/// While Draft, Accessibility or Curvature Map analysis is on, what each of its colours means and +/// the values it stands for, at the bottom left of the viewport (#973). The colours alone don't +/// say, and with colour vision loss they can be hard to tell apart. fn analysis_legend(app: &SolveApp, painter: &egui::Painter, rect: Rect) { use solidcraft_engine::SurfaceAnalysis as A; let t = Tokens::get(); @@ -3967,7 +3967,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); } let overlay_rect = crate::shell::bottom_overlay_rect(app, rect); - analysis_legend(app, &painter, rect); + analysis_legend(app, &painter, overlay_rect); placement_note(app, &painter, overlay_rect); crate::frame_rate::paint(app, ui, &painter, overlay_rect); @@ -6063,10 +6063,12 @@ mod tests { fn isocurves_of_a_split_face_run_on_across_the_split() { let mut h = crate::scenario::Harness::new(); h.app.run("solid.box", json!({"length": 60, "width": 40, "height": 30, "center": [0, 0, 15]})).unwrap(); - // Through the front face from bottom to top: the face is left in two pieces, x < -2 and x > 22. - h.app.run("solid.cylinder", json!({"radius": 12, "height": 50, "base": [10, -20, 0], "operation": "join"})).unwrap(); + // Through the front face from bottom to top: the face is left in two pieces, x < -6 and + // x > 18, wide enough for two and one of the lines (10 apart: the body with the boss is + // 60 x 52 x 50). + h.app.run("solid.cylinder", json!({"radius": 12, "height": 50, "base": [6, -20, 0], "operation": "join"})).unwrap(); h.settle(); - h.app.run("inspect.isocurve", json!({"faces": [[-16, -20, 15], [26, -20, 15]]})).unwrap(); + h.app.run("inspect.isocurve", json!({"faces": [[-18, -20, 15], [24, -20, 15]]})).unwrap(); let faces = h.app.session.isocurve_lines(); assert_eq!(faces.len(), 2, "{:?}", h.app.status); // Each piece's lines up the face (x held) and across it (z held), by where they are held. @@ -6997,7 +6999,10 @@ mod tests { for style in 0..4 { app.ui.visual_style = style; let scene = build_scene(&app).merged(); - let lines = if style == 1 { 0 } else { 24 * crate::gpu::LINE_SIZE }; + // Twelve edges per placed box, in the saved mesh's pieces: no side longer than a fifth + // of the 30 mm diagonal, so the eight 20 mm edges in four and the four 10 mm ones in + // two, 40 segments. + let lines = if style == 1 { 0 } else { 2 * 40 * crate::gpu::LINE_SIZE }; assert_eq!(scene.lines.len(), lines, "style {style}: twelve edges per placed box"); assert_eq!(scene.hidden.len(), if style == 3 { lines } else { 0 }); assert_eq!(scene.tris.is_empty(), style == 2, "wireframe draws only the edges"); @@ -8299,6 +8304,21 @@ mod tests { app } + /// A Ø20 × 20 cylinder whose wall and rims are each in two halves: a circle drawn as two + /// half arcs, extruded (one wall face per arc). SMLib's own cylinder has one wall and one + /// edge per rim; a rim or wall in pieces comes from a profile like this one or an import. + fn split_cylinder_app() -> SolveApp { + let mut s = solidcraft_engine::Session::default(); + s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); + s.execute("sketch.arc.three_point", &json!({"start": [10, 0], "end": [-10, 0], "through": [0, 10]})).unwrap(); + s.execute("sketch.arc.three_point", &json!({"start": [-10, 0], "end": [10, 0], "through": [0, -10]})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("solid.extrude", &json!({"distance": 20})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.set_origin_shown(false); + app + } + /// Moving the pointer across a face keeps its highlight (a scanned mesh is one face of /// millions of triangles): only another face, edge or plane builds it again. #[test] @@ -8637,9 +8657,13 @@ mod tests { }) }) .unwrap(); - assert!(mesh.seams[crease], "the fixture must exercise the coarse seam false positive"); + // Truck's coarse seam fit took this crease for a seam between pieces of one surface; + // the seam flags now compare the exact surfaces (`topo::seam_flags`). Either way the + // certified crease is sharp, drawn in wireframe and picked. Its kink of a millionth is + // too close to tangent to show in the shading (`smooth_edges::Join`: smooth and a + // measured crease at once), so the shaded view leaves it out. assert!(mesh.sharp_edges[crease]); - assert!(mesh.shaded_edge_visible(crease)); + assert!(mesh.edge_visible(crease) && !mesh.shaded_edge_visible(crease)); assert!(mesh.edge_pickable(crease)); assert!(mesh.edge_faces[crease].iter().any(|f| mesh.surface_patch(*f as usize).len() == 1)); let mid = polyline_mid(&mesh.edges[crease]); @@ -8655,7 +8679,7 @@ mod tests { #[test] fn circular_items_measure_as_whole_rims_and_surfaces() { - let mut app = cylinder_app(); + let mut app = split_cylinder_app(); let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); @@ -8736,7 +8760,7 @@ mod tests { #[test] fn circular_rim_hover_click_and_dialog_pick_include_both_halves() { - let mut app = cylinder_app(); + let mut app = split_cylinder_app(); let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); @@ -8783,7 +8807,7 @@ mod tests { #[test] fn curved_face_hover_selection_and_dialogs_cross_the_seam() { - let mut app = cylinder_app(); + let mut app = split_cylinder_app(); let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); @@ -9468,7 +9492,8 @@ mod tests { fn cosmetic_threads_use_depth_tested_lines_and_keep_selection_and_wireframe() { let mut s = solidcraft_engine::Session::default(); s.execute("solid.cylinder", &json!({"radius":3,"height":10})).unwrap(); - s.execute("solid.thread", &json!({"face":[3,0,5],"designation":"M6","length":5})).unwrap(); + // A pick in the middle of a face free at both ends names the end the thread starts from. + s.execute("solid.thread", &json!({"face":[3,0,5],"designation":"M6","length":5,"from":[3,0,0]})).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); let count = |sc: GpuScene| { sc.merged() diff --git a/crates/ui-egui/src/viewport_appearance_tests.rs b/crates/ui-egui/src/viewport_appearance_tests.rs index d7842aaeb..f3d75b41d 100644 --- a/crates/ui-egui/src/viewport_appearance_tests.rs +++ b/crates/ui-egui/src/viewport_appearance_tests.rs @@ -219,7 +219,9 @@ fn an_opacity_class_change_keeps_vertices_and_rewrites_only_the_runs() { assert!(block.bytes.opaque.is_empty() && !block.bytes.glass.is_empty(), "the triangles moved to the glass runs"); let triangles: u32 = block.bytes.glass.iter().map(|r| r.len() as u32).sum::() / 3; assert_eq!(block.bytes.glass.len(), 1, "one body of one class is one run, drawn with no index buffer"); - assert_eq!(triangles, 12, "every triangle of the box"); + // The planner's grids, no side longer than a fifth of the box's 26.9 mm diagonal: edges in + // 4, 3 and 2 pieces, faces of 4 × 3, 4 × 2 and 3 × 2 cells, 2 · (12 + 8 + 6) · 2 triangles. + assert_eq!(triangles, 104, "every triangle of the box"); let vertex = block.bytes.glass.first().map_or(0, |r| r.start) as usize; let at = vertex * crate::gpu::TRI_SIZE; let colour = first_vertex(&second, block.bytes.vertices.get(at..).unwrap_or_default()).1; diff --git a/docs/compatibility.md b/docs/compatibility.md index 9ecc3a6f0..099cbdb4d 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -170,3 +170,12 @@ The #303 draft used `solvecraft-container/1`. `crates/io/src/design.rs` accepts marker alongside `solidcraft-container/1`, and writes only the new marker. Optional old previews are discarded; required document/blob validation is unchanged. The `draft_container_marker_remains_readable` regression covers this shim. + +## Split pieces in designs saved before format 14 + +Builds before format 14 named the pieces a cut splits a body into in the old kernel's shell +order, and the design's later features name the piece they work on by that name (`Body1`, +`Body1 (1)`). SMLib orders pieces otherwise. Such a feature (`shell_piece_order` in the file) +names its pieces so its later features find them: each name goes to the piece the points those +features picked lie on. A name no later feature uses keeps SMLib's order. Designs saved since +format 14 name pieces after their faces and are not affected. diff --git a/examples/clean-up/round-into-boss-wall.json b/examples/clean-up/round-into-boss-wall.json new file mode 100644 index 000000000..876962978 --- /dev/null +++ b/examples/clean-up/round-into-boss-wall.json @@ -0,0 +1,12 @@ +{ + "description": "A round along a plate's edge running into a boss wall: an 80 x 60 x 10 plate with an R12 boss through its back edge, the left part of the back edge rounded R2, then the boss's foot rounded R2 (a tangent chain up the wall and round the foot). Where the two rounds meet, the rolling ball leaves one small face between them against the wall. It is taken off (face.delete with heal false leaves the hole open, the plate a surface) and the hole patched twice from its four edges: with Curvature (g2) and, beside it, with Curvature change (g3). Both meet the rounds and the wall in tangent plane and curvature; the g3 patch also meets the curvature's rate of change in the middle of each seam (within 1e-4 /mm^2 against 1.4 to 9.6 for g2). Near the hole's corners, where the rounds themselves meet only tangent, no patch can do better than tangent. The g3 patch needs surface.patch to take g3.", + "commands": [ + {"command": "solid.box", "params": {"corner": [-40, -30, 0], "length": 80, "width": 60, "height": 10, "body_name": "Plate"}}, + {"command": "solid.cylinder", "params": {"base": [0, 26, 0], "radius": 12, "height": 30, "operation": "join", "targets": ["Plate"]}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[-25, 30, 10]], "radius": 2}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[-11.313708498984761, 30, 5]], "radius": 2}}, + {"command": "face.delete", "params": {"body": "Plate", "faces": [[-11.009162323954376, 30.87189136872293, 8.21538797128807]], "heal": false}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[-11.239, 30.199, 10.718], [-12.457, 27.798, 10.586], [-13.159, 29.381, 9.431], [-11.58, 30.31, 8.0]], "continuity": "g2", "body_name": "Patch G2"}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[-11.239, 30.199, 10.718], [-12.457, 27.798, 10.586], [-13.159, 29.381, 9.431], [-11.58, 30.31, 8.0]], "continuity": "g3", "body_name": "Patch G3"}} + ] +} diff --git a/examples/clean-up/three-round-corner.json b/examples/clean-up/three-round-corner.json new file mode 100644 index 000000000..f67b999e9 --- /dev/null +++ b/examples/clean-up/three-round-corner.json @@ -0,0 +1,11 @@ +{ + "description": "A corner where three rounds meet: a 40 x 40 x 30 box with its vertical edge rounded R8, then its two top edges and the arc between them over that round rounded R4 (one tangent chain). The top round rolls over the vertical one in one blend face at the corner, which meets its neighbours tangent but jumps in curvature. It is taken off (face.delete with heal false) and the hole patched from its four edges with Curvature (g2) and, beside it, with Curvature change (g3). Both meet the rounds and the top in tangent plane and curvature; the g3 patch also meets the curvature's rate of change in the middle of each seam (below 1e-4 /mm^2, against 0.27 to 0.63 for g2).", + "commands": [ + {"command": "solid.box", "params": {"corner": [0, 0, 0], "length": 40, "width": 40, "height": 30, "body_name": "Plate"}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[40, 40, 15]], "radius": 8}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[40, 20, 30], [20, 40, 30]], "radius": 4}}, + {"command": "face.delete", "params": {"body": "Plate", "faces": [[37.79, 36.155, 28.43]], "heal": false}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[34.828, 34.828, 30.0], [37.657, 37.657, 26.0], [38.828, 32.0, 28.828], [32.0, 38.828, 28.828]], "continuity": "g2", "body_name": "Patch G2"}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[34.828, 34.828, 30.0], [37.657, 37.657, 26.0], [38.828, 32.0, 28.828], [32.0, 38.828, 28.828]], "continuity": "g3", "body_name": "Patch G3"}} + ] +} diff --git a/tests/kernel-cases/continuity/g1-patch-g2-at-a-corner-whose-rounds-clash/expected.json b/tests/kernel-cases/continuity/g1-patch-g2-at-a-corner-whose-rounds-clash/expected.json new file mode 100644 index 000000000..96dc1b353 --- /dev/null +++ b/tests/kernel-cases/continuity/g1-patch-g2-at-a-corner-whose-rounds-clash/expected.json @@ -0,0 +1,33 @@ +{ + "sources": [], + "body_count": 1, + "what": "the hole a three-round corner's blend face leaves, patched g2 (Curvature): G1 and not G2 over each whole seam, since the faces round the hole meet each other G1 at its corners", + "source": "analytic", + "method": "box 40x40x30, its vertical edge at (40,40) rounded r8, then the top edges and the arc between them rounded r4; the blend face at the corner deleted (heal false), the four-sided hole patched g2 and stitched in. At each corner of the hole two of its neighbours (the r4 rounds, the r8 round) meet along their own G1 seam, their normal curvatures there differing by 1/4 or 1/8 per mm; a patch smooth at the corner has one curvature there, so it cannot meet both, and the fill asks no more than G1 near such a corner. Each seam's worst G2 station is its end: 0.125 or 0.25 per mm. In the middle of each seam (30-70 %) the patch reaches g2 (kernel test a_corner_of_three_rounds_patched_g3_holds_the_curvature_change_a_g2_patch_does_not).", + "continuity": { + "order": "g1", + "exact": true, + "edges": [ + [ + 34.828, + 34.828, + 30.0 + ], + [ + 37.657, + 37.657, + 26.0 + ], + [ + 38.828, + 32.0, + 28.828 + ], + [ + 32.0, + 38.828, + 28.828 + ] + ] + } +} \ No newline at end of file diff --git a/tests/kernel-cases/continuity/g1-patch-g2-at-a-corner-whose-rounds-clash/recipe.json b/tests/kernel-cases/continuity/g1-patch-g2-at-a-corner-whose-rounds-clash/recipe.json new file mode 100644 index 000000000..fcc58d61e --- /dev/null +++ b/tests/kernel-cases/continuity/g1-patch-g2-at-a-corner-whose-rounds-clash/recipe.json @@ -0,0 +1,104 @@ +{ + "commands": [ + { + "command": "solid.box", + "params": { + "corner": [ + 0, + 0, + 0 + ], + "length": 40, + "width": 40, + "height": 30, + "body_name": "Plate" + } + }, + { + "command": "solid.fillet", + "params": { + "body": "Plate", + "edges": [ + [ + 40, + 40, + 15 + ] + ], + "radius": 8 + } + }, + { + "command": "solid.fillet", + "params": { + "body": "Plate", + "edges": [ + [ + 40, + 20, + 30 + ], + [ + 20, + 40, + 30 + ] + ], + "radius": 4 + } + }, + { + "command": "face.delete", + "params": { + "body": "Plate", + "faces": [ + [ + 37.79, + 36.155, + 28.43 + ] + ], + "heal": false + } + }, + { + "command": "surface.patch", + "params": { + "body": "Plate", + "edges": [ + [ + 34.828, + 34.828, + 30.0 + ], + [ + 37.657, + 37.657, + 26.0 + ], + [ + 38.828, + 32.0, + 28.828 + ], + [ + 32.0, + 38.828, + 28.828 + ] + ], + "continuity": "g2", + "body_name": "Patch" + } + }, + { + "command": "surface.stitch", + "params": { + "bodies": [ + "Plate", + "Patch" + ] + } + } + ] +} \ No newline at end of file diff --git a/tests/kernel-cases/continuity/g1-patch-g3-at-a-corner-whose-rounds-clash/expected.json b/tests/kernel-cases/continuity/g1-patch-g3-at-a-corner-whose-rounds-clash/expected.json new file mode 100644 index 000000000..2d9482c32 --- /dev/null +++ b/tests/kernel-cases/continuity/g1-patch-g3-at-a-corner-whose-rounds-clash/expected.json @@ -0,0 +1,33 @@ +{ + "sources": [], + "body_count": 1, + "what": "the hole a three-round corner's blend face leaves, patched g3 (Curvature change): G1 and not G2 over each whole seam, since the faces round the hole meet each other G1 at its corners", + "source": "analytic", + "method": "box 40x40x30, its vertical edge at (40,40) rounded r8, then the top edges and the arc between them rounded r4; the blend face at the corner deleted (heal false), the four-sided hole patched g3 and stitched in. At each corner of the hole two of its neighbours (the r4 rounds, the r8 round) meet along their own G1 seam, their normal curvatures there differing by 1/4 or 1/8 per mm; a patch smooth at the corner has one curvature there, so it cannot meet both, and the fill asks no more than G1 near such a corner. Each seam's worst G2 station is its end: 0.125 or 0.25 per mm. In the middle of each seam (30-70 %) the patch reaches g3 (kernel test a_corner_of_three_rounds_patched_g3_holds_the_curvature_change_a_g2_patch_does_not).", + "continuity": { + "order": "g1", + "exact": true, + "edges": [ + [ + 34.828, + 34.828, + 30.0 + ], + [ + 37.657, + 37.657, + 26.0 + ], + [ + 38.828, + 32.0, + 28.828 + ], + [ + 32.0, + 38.828, + 28.828 + ] + ] + } +} \ No newline at end of file diff --git a/tests/kernel-cases/continuity/g1-patch-g3-at-a-corner-whose-rounds-clash/recipe.json b/tests/kernel-cases/continuity/g1-patch-g3-at-a-corner-whose-rounds-clash/recipe.json new file mode 100644 index 000000000..b2ea368fc --- /dev/null +++ b/tests/kernel-cases/continuity/g1-patch-g3-at-a-corner-whose-rounds-clash/recipe.json @@ -0,0 +1,104 @@ +{ + "commands": [ + { + "command": "solid.box", + "params": { + "corner": [ + 0, + 0, + 0 + ], + "length": 40, + "width": 40, + "height": 30, + "body_name": "Plate" + } + }, + { + "command": "solid.fillet", + "params": { + "body": "Plate", + "edges": [ + [ + 40, + 40, + 15 + ] + ], + "radius": 8 + } + }, + { + "command": "solid.fillet", + "params": { + "body": "Plate", + "edges": [ + [ + 40, + 20, + 30 + ], + [ + 20, + 40, + 30 + ] + ], + "radius": 4 + } + }, + { + "command": "face.delete", + "params": { + "body": "Plate", + "faces": [ + [ + 37.79, + 36.155, + 28.43 + ] + ], + "heal": false + } + }, + { + "command": "surface.patch", + "params": { + "body": "Plate", + "edges": [ + [ + 34.828, + 34.828, + 30.0 + ], + [ + 37.657, + 37.657, + 26.0 + ], + [ + 38.828, + 32.0, + 28.828 + ], + [ + 32.0, + 38.828, + 28.828 + ] + ], + "continuity": "g3", + "body_name": "Patch" + } + }, + { + "command": "surface.stitch", + "params": { + "bodies": [ + "Plate", + "Patch" + ] + } + } + ] +} \ No newline at end of file diff --git a/tests/kernel-cases/continuity/g2-patch-g2-on-a-hole-in-one-sheet/expected.json b/tests/kernel-cases/continuity/g2-patch-g2-on-a-hole-in-one-sheet/expected.json new file mode 100644 index 000000000..056ca57ae --- /dev/null +++ b/tests/kernel-cases/continuity/g2-patch-g2-on-a-hole-in-one-sheet/expected.json @@ -0,0 +1,32 @@ +{ + "sources": [], + "body_count": 1, + "what": "a square hole in one smooth sheet, patched g2 (Curvature): every seam reaches g2, corners included, since round the hole there is only the one surface and its corners ask nothing it cannot give", + "source": "invariants", + "method": "the sheet: a single-span cubic Bezier through control points (0,0), (13,8), (27,-8), (40,0) on XZ, extruded 40 as a surface; trimmed by the square x, y 12..28 swept along Z, keeping the outside. The hole's sides are two copies of the profile's middle (at y = 12 and 28) and two straight rulings (x = 12 and 28), all on the one face. Patched g2 from its four edges and stitched in. Each corner's two sides lie on the same surface, so they agree to every order and the fill holds the order asked up to the corners. Not exact: a fill may read higher where it happens to.", + "continuity": { + "order": "g2", + "edges": [ + [ + 20, + 12, + 0.0 + ], + [ + 28, + 20, + 2.002857 + ], + [ + 20, + 28, + 0.0 + ], + [ + 12, + 20, + -2.002857 + ] + ] + } +} \ No newline at end of file diff --git a/tests/kernel-cases/continuity/g2-patch-g2-on-a-hole-in-one-sheet/recipe.json b/tests/kernel-cases/continuity/g2-patch-g2-on-a-hole-in-one-sheet/recipe.json new file mode 100644 index 000000000..62a8c9afd --- /dev/null +++ b/tests/kernel-cases/continuity/g2-patch-g2-on-a-hole-in-one-sheet/recipe.json @@ -0,0 +1,138 @@ +{ + "commands": [ + { + "command": "sketch.create", + "params": { + "plane": "XZ" + } + }, + { + "command": "sketch.spline.control_point", + "params": { + "points": [ + [ + 0, + 0 + ], + [ + 13, + 8 + ], + [ + 27, + -8 + ], + [ + 40, + 0 + ] + ] + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "surface.extrude", + "params": { + "sketch": "Sketch1", + "curves": [ + "s1" + ], + "distance": 40, + "body_name": "Sheet" + } + }, + { + "command": "sketch.create", + "params": { + "plane": "XY" + } + }, + { + "command": "sketch.line", + "params": { + "points": [ + [ + 12, + 12 + ], + [ + 28, + 12 + ], + [ + 28, + 28 + ], + [ + 12, + 28 + ], + [ + 12, + 12 + ] + ] + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "surface.trim", + "params": { + "body": "Sheet", + "curves": { + "sketch": "Sketch2" + }, + "keep": [ + 2, + 2, + -1.044595 + ] + } + }, + { + "command": "surface.patch", + "params": { + "body": "Sheet", + "edges": [ + [ + 20, + 12, + 0.0 + ], + [ + 28, + 20, + 2.002857 + ], + [ + 20, + 28, + 0.0 + ], + [ + 12, + 20, + -2.002857 + ] + ], + "continuity": "g2", + "body_name": "Patch" + } + }, + { + "command": "surface.stitch", + "params": { + "bodies": [ + "Sheet", + "Patch" + ] + } + } + ] +} \ No newline at end of file diff --git a/tests/kernel-cases/continuity/g3-patch-g3-on-a-hole-in-one-sheet/expected.json b/tests/kernel-cases/continuity/g3-patch-g3-on-a-hole-in-one-sheet/expected.json new file mode 100644 index 000000000..cc0354bcc --- /dev/null +++ b/tests/kernel-cases/continuity/g3-patch-g3-on-a-hole-in-one-sheet/expected.json @@ -0,0 +1,32 @@ +{ + "sources": [], + "body_count": 1, + "what": "a square hole in one smooth sheet, patched g3 (Curvature change): every seam reaches g3, corners included, since round the hole there is only the one surface and its corners ask nothing it cannot give", + "source": "invariants", + "method": "the sheet: a single-span cubic Bezier through control points (0,0), (13,8), (27,-8), (40,0) on XZ, extruded 40 as a surface; trimmed by the square x, y 12..28 swept along Z, keeping the outside. The hole's sides are two copies of the profile's middle (at y = 12 and 28) and two straight rulings (x = 12 and 28), all on the one face. Patched g3 from its four edges and stitched in. Each corner's two sides lie on the same surface, so they agree to every order and the fill holds the order asked up to the corners. Not exact: a fill may read higher where it happens to.", + "continuity": { + "order": "g3", + "edges": [ + [ + 20, + 12, + 0.0 + ], + [ + 28, + 20, + 2.002857 + ], + [ + 20, + 28, + 0.0 + ], + [ + 12, + 20, + -2.002857 + ] + ] + } +} \ No newline at end of file diff --git a/tests/kernel-cases/continuity/g3-patch-g3-on-a-hole-in-one-sheet/recipe.json b/tests/kernel-cases/continuity/g3-patch-g3-on-a-hole-in-one-sheet/recipe.json new file mode 100644 index 000000000..61662b217 --- /dev/null +++ b/tests/kernel-cases/continuity/g3-patch-g3-on-a-hole-in-one-sheet/recipe.json @@ -0,0 +1,138 @@ +{ + "commands": [ + { + "command": "sketch.create", + "params": { + "plane": "XZ" + } + }, + { + "command": "sketch.spline.control_point", + "params": { + "points": [ + [ + 0, + 0 + ], + [ + 13, + 8 + ], + [ + 27, + -8 + ], + [ + 40, + 0 + ] + ] + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "surface.extrude", + "params": { + "sketch": "Sketch1", + "curves": [ + "s1" + ], + "distance": 40, + "body_name": "Sheet" + } + }, + { + "command": "sketch.create", + "params": { + "plane": "XY" + } + }, + { + "command": "sketch.line", + "params": { + "points": [ + [ + 12, + 12 + ], + [ + 28, + 12 + ], + [ + 28, + 28 + ], + [ + 12, + 28 + ], + [ + 12, + 12 + ] + ] + } + }, + { + "command": "sketch.finish", + "params": {} + }, + { + "command": "surface.trim", + "params": { + "body": "Sheet", + "curves": { + "sketch": "Sketch2" + }, + "keep": [ + 2, + 2, + -1.044595 + ] + } + }, + { + "command": "surface.patch", + "params": { + "body": "Sheet", + "edges": [ + [ + 20, + 12, + 0.0 + ], + [ + 28, + 20, + 2.002857 + ], + [ + 20, + 28, + 0.0 + ], + [ + 12, + 20, + -2.002857 + ] + ], + "continuity": "g3", + "body_name": "Patch" + } + }, + { + "command": "surface.stitch", + "params": { + "bodies": [ + "Sheet", + "Patch" + ] + } + } + ] +} \ No newline at end of file diff --git a/tests/kernel-cases/fillets/KNOWN_FAILING b/tests/kernel-cases/fillets/KNOWN_FAILING index d951af422..17646555d 100644 --- a/tests/kernel-cases/fillets/KNOWN_FAILING +++ b/tests/kernel-cases/fillets/KNOWN_FAILING @@ -1,21 +1,12 @@ # The fillet cases that fail today, one a line: ` `. Sorted. The fillet # rig gate (.github/workflows/fillet-rig.yml) fails on a case that fails and is not listed here, # and on a listed case that passes: a fix removes its line in the same pull request. -# Baseline: develop 30dc4c860 (SMLib 5afca53), aarch64 Linux, 2026-10-28: 71 of 89 pass. -1207-fillet-bar-top-edge-after-boss-arc-round-no-tangent-chain SMLib status 1001 instead of the "continues tangentially" refusal (refused before SMLib on branch fillet-remaining-cases) +# Baseline: develop 229739a70 (SMLib 7e917f0), aarch64 Linux, 2026-10-29. 1207-fillet-bar-top-edge-after-boss-arc-round-r0-5 SMLib's check refuses the round: internal coincident control points in a B-spline curve (an internal pole) -1207-fillet-bar-top-edge-and-boss-arc-together continuity g0: the corner patch meets the bar's round with a 15.6° crease -1207-fillet-bar-top-edge-and-boss-arc-together-curvature-corners continuity g0: the corner patch meets the bar's round with a 15.6° crease (as the rolling corner) -1207-fillet-bar-top-edge-and-boss-arc-together-r1 continuity g0: the corner patch meets the bar's round with a 13.1° crease -1207-fillet-bar-top-edge-and-boss-arc-together-reduce-fit continuity g0: the corner patch meets the bar's round with a 15.6° crease (as the exact fit) -1207-fillet-bar-top-edge-and-boss-arc-together-taper-fit continuity g0: the corner patch meets the bar's round with a 15.6° crease (as the exact fit) -1207-fillet-box-end-edge-into-unblended-round-refused SMLib status 1001 instead of the "continues tangentially" refusal (refused before SMLib on branch fillet-remaining-cases) -1390-chamfer-hole-rim-touching-bottom SMLib status 1001 instead of naming the unsupported corner (SMLIB_ERR_CORNER_UNSUPPORTED on branch fillet-open-cases) +1557-fillet-vertical-corners-after-bottom-rounds SMLib status 1001 since bodies are read back from their records (#8625): the bottom rounds come back as SmCylinder where SMLib's blend made SmCone(0), and the corner-ball trace starts 2.78e-4 off 4782-fillet-bar-edge-wider-than-both-faces SMLib status 1001: a convex round past both its faces is not yet built by subtraction 4782-fillet-two-end-verticals-past-a-full-round SMLib's result is not a closed solid, where a refusal naming 7.5 mm (fillet_max for the exact fit) is right -4782-fillet-two-end-verticals-past-a-full-round-reduce-fit SMLib's result is not a closed solid at r10, so the reduce fit never searches down 5158-fillet-round-just-past-a-10mm-face SMLib status 1001: a convex round 0.01 past its face is not yet built by subtraction (10.0001-10.04 open) -896-fillet-smooth-seam-refused SMLib SM_ERR_INVALID_INPUT instead of the "is smooth" refusal (refused before SMLib on branch fillet-remaining-cases) 9-fillet-corner-curvature-with-reduce-fit not supported yet: solid.fillet builds corner g2 with the exact fit only 9-fillet-corner-curvature-with-taper-fit not supported yet: solid.fillet builds corner g2 with the exact fit only 9-fillet-corner-r1-curvature-default-setback continuity g1: the g2 corner patch seams G1 at the corner point, not G2 diff --git a/tests/oracle/17-loft/expected.json b/tests/oracle/17-loft/expected.json index 790fe3b19..58fa78d83 100644 --- a/tests/oracle/17-loft/expected.json +++ b/tests/oracle/17-loft/expected.json @@ -1,24 +1,34 @@ { - "source": "freecad 1.1.4", - "method": "FreeCAD (OpenCASCADE) build of recipe.json by tools/freecad-oracle/build.py: Part.makeLoft", + "source": "analytic", + "method": "ruled loft, square 40 at z 0 to circle r 10 at z 40, each side on one rational quarter of the circle (corner (20, -20) at -45 deg): A(t) = (1-t)^2 A_S + t^2 A_C + t(1-t) M, M = 1/2 int (S x C' + C x S') du (Gauss-Legendre on the exact rational arcs), V = h (A_S/3 + A_C/3 + M/6), z_c = h (A_S/12 + A_C/4 + M/12) / (V/h), wall area = int |P_u x P_t| du dt", "body_count": 1, - "volume_mm3": 35125.49757633739, - "area_mm2": 6495.0000512370025, + "volume_mm3": 35080.725116114816, + "area_mm2": 6493.984396260195, "center_of_mass": [ - 4.902280481153527e-11, - 9.800242527565077e-16, - 15.119060422795876 + 0.0, + 0.0, + 15.112831028492234 ], "bbox": { "min": [ - -20.0000001, - -20.0000001, - -1e-07 + -20.0, + -20.0, + 0.0 ], "max": [ - 20.0000001, - 20.0000001, - 40.000000100000015 + 20.0, + 20.0, + 40.0 ] - } + }, + "faces": 6, + "note": "a difference of definition with the FreeCAD (OpenCASCADE) loft, which runs each side to the quarter at uniform angle (arc length): that correspondence has no exact rational B-spline form, and SolidCraft keeps its surfaces exact; OpenCASCADE's volume is 35125.50 mm^3 (0.13% more). The reference.stl is OpenCASCADE's, so the surface comparison is left out", + "compare": [ + "body_count", + "volume_mm3", + "area_mm2", + "center_of_mass", + "bbox", + "faces" + ] } diff --git a/tools/oracle-analytic/cases_basic.py b/tools/oracle-analytic/cases_basic.py index 23d343263..08241bd23 100644 --- a/tools/oracle-analytic/cases_basic.py +++ b/tools/oracle-analytic/cases_basic.py @@ -371,6 +371,74 @@ def c16_sweep(): "from the bend axis along the bisector) + 2 end disks", 1, mp.v, A, mp.com(), [-r, -r, 0], [50, r, 50 + r], 5) +def c17_loft(): + """A ruled loft from the 40 x 40 square at z = 0 to the circle r 10 at z = 40. Each side of the + square runs to one quarter of the circle, the corner (20, -20) to angle -45 deg, and both by + their own parameters: the side linearly, the quarter as the exact rational quadratic arc + (middle weight sqrt(2) / 2) that is the circle's B-spline form. Point (u, t) of a wall is + (1 - t) S(u) + t C(u) at height 40 t, so the section at t is the blend of the two loops and + its area A(t) = (1 - t)^2 A_S + t^2 A_C + t (1 - t) M with M the mixed area + 1/2 int (S x C' + C x S') du.""" + h, half, r = 40.0, 20.0, 10.0 + w = math.sqrt(2.0) / 2.0 + corners = [(half, -half), (half, half), (-half, half), (-half, -half)] + + def side(k, t): + (ax, ay), (bx, by) = corners[k], corners[(k + 1) % 4] + return (ax + (bx - ax) * t, ay + (by - ay) * t), (bx - ax, by - ay) + + def quarter(k, t): + a0 = -PI / 4 + k * PI / 2 + p0 = (r * math.cos(a0), r * math.sin(a0)) + p2 = (r * math.cos(a0 + PI / 2), r * math.sin(a0 + PI / 2)) + p1 = (p0[0] + p2[0], p0[1] + p2[1]) # the control polygon's corner, sqrt(2) r out + b = [(1 - t) ** 2, 2 * t * (1 - t) * w, t * t] + db = [-2 * (1 - t), 2 * (1 - 2 * t) * w, 2 * t] + d = sum(b) + dd = sum(db) + n = [sum(bi * q[i] for bi, q in zip(b, (p0, p1, p2))) for i in range(2)] + dn = [sum(bi * q[i] for bi, q in zip(db, (p0, p1, p2))) for i in range(2)] + return (n[0] / d, n[1] / d), ((dn[0] * d - n[0] * dd) / (d * d), (dn[1] * d - n[1] * dd) / (d * d)) + + xs, ws = GL + a_s, a_c = (2 * half) ** 2, PI * r * r + mixed = 0.0 + area_walls = 0.0 + for k in range(4): + for x, wu in zip(xs, ws): + u = 0.5 * (x + 1) + (s, ds), (c, dc) = side(k, u), quarter(k, u) + mixed += 0.5 * wu * 0.5 * ((s[0] * dc[1] - s[1] * dc[0]) + (c[0] * ds[1] - c[1] * ds[0])) + for y, wt in zip(xs, ws): + t = 0.5 * (y + 1) + pu = ((1 - t) * ds[0] + t * dc[0], (1 - t) * ds[1] + t * dc[1], 0.0) + pt = (c[0] - s[0], c[1] - s[1], h) + n = (pu[1] * pt[2] - pu[2] * pt[1], pu[2] * pt[0] - pu[0] * pt[2], pu[0] * pt[1] - pu[1] * pt[0]) + area_walls += 0.25 * wu * wt * math.sqrt(sum(v * v for v in n)) + int_a = a_s / 3 + a_c / 3 + mixed / 6 + int_ta = a_s / 12 + a_c / 4 + mixed / 12 + V = h * int_a + zc = h * int_ta / int_a + return result( + "ruled loft, square 40 at z 0 to circle r 10 at z 40, each side on one rational quarter of the circle " + "(corner (20, -20) at -45 deg): A(t) = (1-t)^2 A_S + t^2 A_C + t(1-t) M, M = 1/2 int (S x C' + C x S') du " + "(Gauss-Legendre on the exact rational arcs), V = h (A_S/3 + A_C/3 + M/6), z_c = h (A_S/12 + A_C/4 + M/12) / (V/h), " + "wall area = int |P_u x P_t| du dt", + 1, + V, + area_walls + a_s + a_c, + (0.0, 0.0, zc), + (-half, -half, 0.0), + (half, half, h), + faces=6, + note="a difference of definition with the FreeCAD (OpenCASCADE) loft, which runs each side to the quarter at " + "uniform angle (arc length): that correspondence has no exact rational B-spline form, and SolidCraft keeps its " + "surfaces exact; OpenCASCADE's volume is 35125.50 mm^3 (0.13% more). The reference.stl is OpenCASCADE's, so " + "the surface comparison is left out", + compare=["body_count", "volume_mm3", "area_mm2", "center_of_mass", "bbox", "faces"], + ) + + def c18_hole_features(): T = 15.0 mp = MP().add(*box_mp([0, 0, 0], [60, 40, T])) @@ -542,6 +610,7 @@ CASES = { "14-combine-cut": c14_combine_cut, "15-combine-intersect": c15_combine_intersect, "16-sweep": c16_sweep, + "17-loft": c17_loft, "18-hole-features": c18_hole_features, "19-l-bracket-constrained": c19_l_bracket, "20-slot-constrained": c20_slot,