Merge ws/devmerge2: develop ac52443d, and ablasik's cone export fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk
This commit is contained in:
Brett LawsonandClaude Opus 5.5 committed 2026-10-29 21:23:05 +01:00
commit 2f623f3f22
145 files changed
+7055 -1190

No files matched your search

@@ -1,7 +1,13 @@
{
"ar": {
"help.version": "الإصدار {version}"
},
"en": {
"help.version": "Version {version}"
},
"he": {
"help.version": "גרסה {version}"
},
"ja": {
"help.version": "バージョン {version}"
},
@@ -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)。"
}
}
@@ -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": "部品ごと",
+12
View File
@@ -1833,6 +1833,16 @@ pub enum FeatureKind {
file: String,
meshes: Vec<MeshData>,
},
/// 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",
}
}
}
+144 -9
View File
@@ -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<u64, KeptSeparate>,
/// 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<u64, u64>,
}
/// 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<ModelState>, f: &Feature, key: u64, mats: Vec<Mat>) {
fn stamp(&mut self, doc: &Document, before: &Arc<ModelState>, f: &Feature, key: u64, mats: Vec<Mat>) {
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<String>,
warning: Option<String>,
import_report: Option<Arc<kernel::ImportReport>>,
repair: Option<Arc<kernel::RepairReport>>,
ms: f64,
state: Arc<ModelState>,
/// 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<Arc<kernel::ImportReport>>,
/// What a Repair Part feature changed, face by face (the command's reply says it).
#[serde(skip)]
pub repair: Option<Arc<kernel::RepairReport>>,
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<String, Value>) -> 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<crate::BodyName>, 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<crate::BodyName>, pts: &[Vec3]) -> Vec<String> {
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<crate::BodyName>, pts: &[Ve
// The body's names are worked out once for all its picks.
let idx: Vec<usize> = on.iter().enumerate().filter(|(_, t)| **t == ti).map(|(i, _)| i).collect();
let at: Vec<Vec3> = 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<String>,
import_report: &mut Option<Arc<kernel::ImportReport>>,
repair: &mut Option<Arc<kernel::RepairReport>>,
) -> 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<String> =
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)]
@@ -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})),
]
}
@@ -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
@@ -207,3 +207,4 @@ move
import
mesh_convert
mesh_import
repair
@@ -238,3 +238,5 @@ import
mesh_convert
remap_bodies: body
mesh_import
repair
remap_bodies: body
@@ -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).
+145 -1
View File
@@ -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<Vec<usize>> {
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<String> = 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<Vec<usize>> {
let mut families: Vec<(*const Operand, Vec<usize>)> = 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<Vec<Vec3>> {
let later = doc.features.iter().skip_while(|g| g.id != f.id).skip(1);
let mut picks: Vec<Vec<Vec3>> = 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<Vec3> {
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<Vec3> = 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<String> = 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<Option<usize>> = 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<usize> = order.into_iter().map(|o| o.or_else(|| free.next())).collect::<Option<_>>().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
+6
View File
@@ -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::<kernel::ImportReport>(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(),
+55 -4
View File
@@ -156,11 +156,55 @@ fn mesh_outlines(positions: &[Vec3], triangles: &[[u32; 3]]) -> Vec<Vec<Vec3>> {
[(_, _, 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<Vec<Vec3>> {
let mut at: std::collections::BTreeMap<u32, Vec<usize>> = 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<usize> {
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());
}
+49 -1
View File
@@ -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<LinkGeom> {
Some(match *s {
+13 -1
View File
@@ -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<f64> {
num(s)
}
/// The refusal for a plain `M<d>` 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<String> {
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<String> = 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()
+27 -18
View File
@@ -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<solidcraft_kernel::Body> = 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<f64> = 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
+120 -3
View File
@@ -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<RepairParams> = 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::<RepairResult>)
.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<Value> {
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<Value> {
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();
+1 -9
View File
@@ -2343,16 +2343,8 @@ fn clearance_diameter(size: &str, fit: &str) -> Option<f64> {
/// The pitches to try for a plain `M<d>` that has no ISO coarse pitch, `None` for anything else.
fn fine_only_hint(t: &str) -> Option<String> {
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::<f64>().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<String> = 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).
+8 -1
View File
@@ -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.
+1 -1
View File
@@ -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"))
}
+4 -2
View File
@@ -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()))
+26 -7
View File
@@ -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<String> = 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!({}));
+3 -2
View File
@@ -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));
+46 -14
View File
@@ -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}");
}
+3
View File
@@ -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;
+66 -22
View File
@@ -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<String> = 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]]);
}
+1 -1
View File
@@ -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")
+11 -10
View File
@@ -43,8 +43,8 @@ fn top_and_hole_names(s: &mut Session) -> (String, Vec<String>) {
}
/// 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}");
}
+46 -34
View File
@@ -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.
+117
View File
@@ -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<LengthExpr>,
/// 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<bool>,
#[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<usize>,
/// 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<String>,
/// 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<RepairFace>,
/// Faces SMLib refuses that could not be rebuilt (the part may still be taken as a whole).
pub refused: Vec<RepairFace>,
pub sewn: Vec<RepairSewn>,
pub holes: Vec<RepairHole>,
/// 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<f64>,
}
/// 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<String>,
/// The bodies the feature made.
pub created_bodies: Vec<String>,
/// Bodies that were there before and now have other geometry.
pub changed_bodies: Vec<String>,
/// Bodies that are gone.
pub removed_bodies: Vec<String>,
/// A warning from the evaluation (a hole left open), or `null`.
pub warning: Option<String>,
/// How long the feature took to evaluate, in milliseconds.
pub ms: Option<f64>,
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<String>,
}
#[cfg(test)]
#[path = "browser_tests.rs"]
mod tests;
+28
View File
@@ -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::<RepairParams>(), &["body", "body_name", "body_names", "gap", "name", "participants", "patch_holes"]);
}
#[test]
fn replies_match_the_output_schema() {
let schema = output_schema_for::<RepairResult>();
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");
}
+1
View File
@@ -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;
+2 -1
View File
@@ -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": {}})),
+2 -2
View File
@@ -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",
+36 -34
View File
@@ -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");
+2 -1
View File
@@ -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"}));
+2
View File
@@ -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);
+232
View File
@@ -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<Ball> {
let mut p: Vec<Vec3> = 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<Vec3> {
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<Vec3> {
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<Ball> = 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<Vec3> {
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<Vec3> = (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<Vec3> = (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<Vec3> = (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<Vec3> = 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);
}
}
+118 -16
View File
@@ -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<f64>, 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<f64>, 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<f64>, Vec<([f64; 2], f64)>) {
@@ -238,10 +293,29 @@ pub fn tube_turned(s: &Surface, angle: f64) -> Option<Surface> {
/// 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<Vec<Vec<[f64; 4]>>> {
@@ -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;
+63
View File
@@ -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());
}
+2 -2
View File
@@ -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
+9 -3
View File
@@ -91,6 +91,10 @@ pub struct Across {
pub normal: Vec3,
/// G2: the neighbour's curvature vector along `leave` (unit speed).
pub bend: Option<Vec3>,
/// 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<crate::linkage::Jet>,
}
/// 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);
+9 -3
View File
@@ -30,7 +30,7 @@ fn tube_end(r: f64, g2: bool) -> impl FnMut(usize, &[f64]) -> Result<Vec<Station
.iter()
.map(|t| {
let a = t * TAU;
let across = Across { leave: Vec3::Z, normal: radial(a), bend: g2.then_some(Vec3::ZERO) };
let across = Across { leave: Vec3::Z, normal: radial(a), bend: g2.then_some(Vec3::ZERO), jet: None };
Station { p: radial(a) * r, up: around(a).cross(Vec3::Z), across: Some(across), corner: false, clash: false }
})
.collect())
@@ -52,7 +52,7 @@ fn window(r: f64, a: f64, h: f64) -> impl FnMut(usize, &[f64]) -> Result<Vec<Sta
};
let p = radial(angle) * r + Vec3::Z * z;
let up = tangent.cross(leave);
Station { p, up, across: Some(Across { leave, normal: radial(angle), bend: None }), corner: t == 0.0, clash: false }
Station { p, up, across: Some(Across { leave, normal: radial(angle), bend: None, jet: None }), corner: t == 0.0, clash: false }
})
.collect())
}
@@ -118,7 +118,13 @@ fn a_planar_polygon_is_its_plane_and_a_point_lifts_it() {
.iter()
.map(|t| {
let p = Vec3::new(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, 0.0);
Station { p, up: Vec3::Z, across: Some(Across { leave: inward, normal: Vec3::Z, bend: None }), corner: *t == 0.0, clash: false }
Station {
p,
up: Vec3::Z,
across: Some(Across { leave: inward, normal: Vec3::Z, bend: None, jet: None }),
corner: *t == 0.0,
clash: false,
}
})
.collect())
};
+1272 -299
View File
File diff suppressed because it is too large. Load diff
+219
View File
@@ -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<HPoint> = 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<IsoEdge> {
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<Vec<Option<Across>>, 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<Vec3> = (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<f64> = (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<Vec<Option<Across>>, 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:?}");
}
}
+9 -3
View File
@@ -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())
};
+3
View File
@@ -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};
+334
View File
@@ -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<f64> {
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<Vec<f64>> {
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<Vec<Target>> {
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<Output = Self> + std::ops::Mul<Output = Self> {
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<T: Coefficient>(a: &[T], b: &[T], top: usize) -> Vec<T> {
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<T: Coefficient>(a: &[T], e: usize, top: usize) -> Vec<T> {
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<Jet> {
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<Vec<f64>> = NODES.iter().map(|l| heights(&d, n, t + w * *l, order)).collect::<Option<_>>()?;
for m in 2..=order {
let values: Vec<f64> = 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<Vec<f64>> {
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<Vec<Vec3>> {
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<Vec<f64>> {
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;
+95
View File
@@ -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");
}
+28 -2
View File
@@ -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
+45
View File
@@ -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<f64>)> {
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<T: Linear>(&self, ctrl: &[T], t: f64, der: usize) -> SplineResult<T> {
if ctrl.len() != self.count() {
+2
View File
@@ -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 {
+8 -4
View File
@@ -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<usize> =
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,
+93 -26
View File
@@ -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<Vec<usize>> {
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<Vec<Vec3>> {
/// 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<usize> = Vec::new();
let mut picked: Vec<usize> = 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<Vec3> {
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<u32> = 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<usize> {
let mut chain = seeds.to_vec();
// The unit direction edge `e` leaves its end `v` in.
let leaving = |e: usize, v: u32| -> Option<Vec3> {
let [a, b] = rec.rec.edges.get(e)?.vertices;
@@ -650,16 +695,7 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result<Vec<Vec3>> {
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<u32> = 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<Vec<Vec3>> {
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<Vec<Vec3>> {
}
}
}
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<Option<Vec3>> {
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<usize> = 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<Vec3>) -> 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)]
+5 -3
View File
@@ -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());
+48 -2
View File
@@ -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<f64> = setbacks.iter().map(|(_, d)| *d).collect();
let tol = pick_tolerance(body);
let at: Vec<Vec3> = 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<f64> = setbacks.iter().map(|(_, d)| *d).collect();
let at: Vec<Vec3> = 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<Vec<(usize, bool)>> {
@@ -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<Body> {
@@ -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));
}
}
+27 -4
View File
@@ -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| {
+36 -34
View File
@@ -188,15 +188,16 @@ fn faces_of(h: &History) -> Vec<(Change, Vec<FaceOrigin>)> {
}
/// 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<usize> = 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<FaceOrigin> = (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<usize> = (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<usize> =
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));
}
+3 -2
View File
@@ -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)
};
+50 -13
View File
@@ -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<Body> {
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<Vec<Seg2>> = 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<NumberedLoop> {
let ccw = l.oriented(false);
if at == 0.0 || taper == 0.0 {
return Ok(ccw);
}
let segs: Option<Vec<Seg2>> = 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<NumberedLoop> = joined.holes.iter().map(|h| section(h, from, -taper)).collect::<Result<_>>()?;
// 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<NumberedLoop> = joined.holes.iter().map(|h| section(h, at, -taper)).collect::<Result<_>>()?;
let pts = |l: &NumberedLoop| l.lp.segs.iter().flat_map(|s| s.polyline(1e-3)).collect::<Vec<Vec2>>();
// 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<NumberedLoop> = 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::<Vec<_>>(),
&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
@@ -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) {
+7 -7
View File
@@ -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));
}
}
+15 -6
View File
@@ -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
+2 -1
View File
@@ -378,7 +378,8 @@ fn a_cylinder_wall_split_along_its_seam_meshes_round() {
let outer: Vec<bool> = (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);
+19 -7
View File
@@ -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<Vec3>, 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<Vec<AUse>>> = 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<Frame>,
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
+16 -3
View File
@@ -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();
+1
View File
@@ -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],
+238 -104
View File
@@ -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<IsoEdge> = chain.iter().map(|&(e, forward)| iso_edge(record, e, forward)).collect::<Result<_>>()?;
let pieces = loop_pieces(record, chain)?;
let edges: Vec<IsoEdge> = pieces.iter().map(|p| iso_edge(record, p)).collect::<Result<_>>()?;
let size = body.size().max(solidcraft_geom::LINEAR_TOL);
let mut beside: Vec<Option<Beside>> = 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<Option<Beside>> = 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<Vec<Option<Across>>, 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<IsoEdge> {
/// 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<Vec<Piece>> {
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<f64> = 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<Piece> = (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<IsoEdge> {
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<f64>, Vec<Vec3>) = match &edge.curve {
let (degree, knots, h): (usize, Vec<f64>, Vec<HPoint>) = 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<HPoint> = 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<Vec3> = 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::<Option<Vec<Vec3>>>()
.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<Beside> {
fn new(record: &b::Brep, e: usize, forward: bool, order: Continuity, size: f64) -> Result<Beside> {
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<Option<Across>> {
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<f64> {
@@ -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<Body> {
fn quilt_body(body: &Body, record: &b::Brep, chain: &[Piece], fill: &IsoFill, tol: f64) -> Result<Body> {
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<u32, u32> = std::collections::HashMap::new();
let mut middle_of: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
let mut middle_of: std::collections::HashMap<(usize, u64), u32> = std::collections::HashMap::new();
let mut edges: Vec<PartEdge> = Vec::new();
// Each part edge's origin: the record edge it is a piece of (`None` for a spoke).
let mut origin: Vec<Option<usize>> = 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<usize, u32>, k: usize, edge: &b::Edge, t: f64) -> Result<u32> {
/// 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<u32> {
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<usi
/// tolerance, since a planar face is exact and other operations treat it as containing its
/// edges to that tolerance. A fitted face gets [`face_tolerance`], ten times looser.
pub(crate) fn planarity_tolerance(body: &Body) -> 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<Vec3> = 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],
+142 -6
View File
@@ -108,7 +108,7 @@ fn rim_points(body: &Body, per: usize) -> Vec<Vec3> {
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<Vec3> {
.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::<Vec<_>>();
// 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<Continuity>, Option<Continuity>, f64)> {
use crate::{ContinuityTolerances, EdgePick, pick_edges, seam_diagnostics};
let sewn = stitch(&[open, fill], 1e-3).unwrap();
let picks: Vec<EdgePick> = 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());
}
+2 -1
View File
@@ -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, &region, 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, &region, Vec3::ZERO, Vec3::Z, 3.0, 3.0).is_err(), "pitch below the section");
+4 -2
View File
@@ -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<f64> = parts.iter().map(|p| p.volume_at(1e-3).unwrap()).collect();
let vs: Vec<f64> = parts.iter().map(|p| crate::measure(p).unwrap().volume).collect();
assert!((vs.iter().sum::<f64>() - 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);
+4 -2
View File
@@ -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");
+4 -2
View File
@@ -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;
+1 -1
View File
@@ -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));
+5 -4
View File
@@ -43,10 +43,11 @@ pub struct MassMeasure {
pub notes: Vec<String>,
}
/// 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),
+53 -5
View File
@@ -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<Option<Body>> {
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<Body> {
})
}
/// 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<bool> {
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<Option<Body>>) -> Result<Option<Body>> {
@@ -141,15 +160,44 @@ pub fn transform_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result<Body> {
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<Option<usize>> = (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<usize> {
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.
+5 -1
View File
@@ -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})");
}
}
}
+2 -1
View File
@@ -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();
+56 -24
View File
@@ -40,23 +40,48 @@ pub(super) fn actual_planes(body: &Body) -> Result<Vec<Option<Plane>>> {
.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<T>(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<T>(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<Plane> {
@@ -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<Plane>]| {
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();
+22
View File
@@ -39,6 +39,8 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result<O
if b.triangles.len() > 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<O
Ok(Some(result.with_checked_history(history, &counts)))
}
/// `m` with corners at the very same point made one vertex, triangles in their order: a body's
/// own mesh (Body::mesh) gives each face its own vertices, the faces along an edge its very
/// points, and is closed only once they are one.
fn welded(m: &Mesh) -> Mesh {
let mut at: BTreeMap<[u64; 3], u32> = BTreeMap::new();
let mut positions = Vec::with_capacity(m.positions.len());
let index: Vec<u32> = 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<Vec<Vec<usize>>> {
+51 -19
View File
@@ -578,14 +578,35 @@ mod tests {
}
out
}
fn trap() -> Vec<f64> {
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<f64> {
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::<f64>();
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<f64>; 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<f64> {
if k == 0 { vec![0., 4., -4.] } else { vec![0.] }
}
fn bezier_knots(degree: usize) -> Vec<f64> {
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::<Vec<_>>();
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<f64> = 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.
+13 -5
View File
@@ -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(&region.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]
+45 -49
View File
@@ -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<Vec<FaceOrigin>> {
#[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<Seg2> = 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(&centres) {
let flat: Vec<Vec2> = 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<u
#[test]
fn sweeps_along_paths() {
let r = Region2 { outer: rotated(&rect(-2.0, -2.0, 2.0, 2.0).reversed(), 1), holes: vec![] };
// A line then a quarter turn (two parts): three faces per segment.
// A line then a quarter turn: a face per segment along each path segment.
let path = [
PathSeg::Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 10.0) },
PathSeg::Arc { a: Vec3::new(0.0, 0.0, 10.0), center: Vec3::new(20.0, 0.0, 10.0), axis: Vec3::Y, angle: FRAC_PI_2 },
];
let b = crate::sweep(&Plane::XY, &r, &path).unwrap();
check_sweep(&b, &Plane::XY, &r, Some(3));
check_sweep(&b, &Plane::XY, &r, Some(2));
// Along a smooth 3D path: one wall per segment.
let curve: Vec<Vec3> = (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<usize> = (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<usize> = (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]
+588
View File
@@ -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<usize>,
/// A point halfway along each of its edges: Patch's `edges`.
pub edges: Vec<Vec3>,
/// 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<String>,
}
/// What a repair did.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RepairReport {
pub rebuilt: Vec<RebuiltFace>,
pub refused: Vec<RefusedFace>,
pub sewn: Vec<SewnGap>,
pub holes: Vec<Hole>,
/// 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<String>) -> 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<String> = 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<u32> = pairs.iter().flat_map(|p| [p.edges[0], p.edges[1]]).collect();
let rest: Vec<u32> = 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(&[&current], 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<String> = 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::<Vec<_>>().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<std::result::Result<(), String>> {
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<Option<b::Face>> {
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<u32> = Vec::new();
let mut vertices: Vec<u32> = 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::<Result<Vec<_>>>()?;
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<Vec<u32>> {
let free: Vec<u32> =
(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<Vec3> {
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<f64> {
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<Pair> {
let samples: Vec<Vec<Vec3>> = free.iter().map(|&e| points(r, e, GAP_SAMPLES)).collect();
let boxes: Vec<Option<(Vec3, Vec3)>> = 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<Vec<u32>> {
let mut by_vertex: std::collections::HashMap<u32, Vec<u32>> = 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<usize> = 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<Vec3> = edges.iter().filter_map(|&e| points(r, e, 2).get(1).copied()).collect();
let along: Vec<Vec3> = 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<Body> {
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<Body> {
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<f64> = 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}");
}
}
}
+14 -3
View File
@@ -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<b::Curve>,
pub interval: [f64; 2],
pub vertices: [u32; 2],
}
@@ -1366,8 +1370,8 @@ pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {
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<b::Frame>> = 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<Assembled> {
let mut labels: Vec<(b::Curve, [f64; 2])> = Vec::with_capacity(edges.len());
let mut forms: Vec<Option<(b::Curve, [f64; 2])>> = 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);
+125 -11
View File
@@ -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<bool> = (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<BTreeSet<usize>> = 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<Vec3>, &Vec<u32>)> = 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<f64> = 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<Brep> {
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<Piece>],
all: &[Piece],
from: f64,
distance: f64,
sign: f64,
draft: Draft,
) -> Result<Body> {
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<Role> = 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<Body> {
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::<Option<Vec<Vec3>>>()
.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,
+16 -9
View File
@@ -154,8 +154,9 @@ fn face_patch(body: &Body, face: usize) -> Result<Patch> {
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<usize> =
@@ -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<f64> = 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();
+14 -1
View File
@@ -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.
+4 -3
View File
@@ -87,11 +87,12 @@ pub fn edge_circle(b: &Body, edge: usize) -> Option<EdgeCircle> {
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;
+9 -8
View File
@@ -69,20 +69,21 @@ mod tests {
assert!(copy.face_count() == 2 && rel(measure(&copy).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
+54 -3
View File
@@ -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<Brep> {
// 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<u32> {
@@ -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<Option<Brep>> {
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.
+4 -4
View File
@@ -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;
+106 -32
View File
@@ -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<Body> {
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<Body> {
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> {
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<History>)> {
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<History>)> {
stitched_with(r, tol, |input, sewn| {
let counted = |b: &SmBrep| -> Result<usize> {
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<History>)> {
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<Vec3> = (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<Vec3> = (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<Vec3> = (-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]
+20 -8
View File
@@ -221,6 +221,21 @@ fn frames_toward(tangents: &[Vec3], d: Vec3) -> Result<Vec<[Vec3; 3]>> {
.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();
+3 -2
View File
@@ -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");
}
+47 -11
View File
@@ -79,6 +79,16 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range<usize>
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<usize>
}
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::<f64>::new()
.keep_constraint_edges()
@@ -115,7 +125,7 @@ pub(crate) fn triangulate(boundary: &[[f64; 2]], loops: &[std::ops::Range<usize>
// 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<usize>
}
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<usize
sides.push((add(&mut cdt, a)?, add(&mut cdt, b)?));
}
}
// The band runs along both sides of a slit (see `triangulate`): its sides bound it on neither.
let slits = slits(&sides);
for &(a, b) in stairs {
sides.push((add(&mut cdt, a)?, add(&mut cdt, b)?));
}
@@ -197,7 +209,7 @@ pub(crate) fn band(points: &[[f64; 2]], n: usize, loops: &[std::ops::Range<usize
}
cdt.add_constraint(a, b);
}
let region = region(&cdt);
let region = region(&cdt, &slits);
let mut tris = Vec::new();
for face in cdt.inner_faces() {
if !region.get(face.index()).copied().unwrap_or(false) {
@@ -216,7 +228,14 @@ pub(crate) fn band(points: &[[f64; 2]], n: usize, loops: &[std::ops::Range<usize
/// the tolerance from the triangle or whose corner normals turn more than the facet angle, and
/// under the middle of every non-constraint side that sags more than the tolerance or is
/// longer than [`LONG`] times `h`, until none does or `budget` points were added. Returns the points added.
fn refine_sag(cdt: &mut Cdt, sag: &Sag, budget: usize, from: &dyn Fn(Point2<f64>) -> [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>) -> [f64; 2],
slits: &std::collections::HashSet<(FixedVertexHandle, FixedVertexHandle)>,
) -> usize {
let mut added = 0;
let mut cache: HashMap<FixedVertexHandle, Option<(Vec3, Option<Vec3>)>> = 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<f64>
(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<f64>
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<bool> {
/// 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<bool> {
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<Option<bool>> = vec![None; cdt.num_all_faces()];
let mut todo: Vec<(FixedFaceHandle<InnerTag>, 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<bool> {
}
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)));
}
}
}
+23 -7
View File
@@ -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<usize>], 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)]
+180
View File
@@ -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<u32>>, 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<u32>
}
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<Vec3> = 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<u32>> = 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<Option<f64>> = 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)));
}
}
+35
View File
@@ -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]);
+199 -10
View File
@@ -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<Vec3> = 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::<Vec<f64>>();
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::<Vec<_>>();
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::<Vec<_>>());
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<Vec3> = 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::<Vec<_>>());
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);
}
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more