Merge develop 739e47b9 into solidcore

This commit is contained in:
Brett Lawson committed 2026-10-30 12:47:46 +01:00
commit 51c474efbc
325 files changed
+13903 -1445

No files matched your search

+3 -3
View File
@@ -160,9 +160,9 @@ the most complete description of the house style.
The reference for what the kernel builds is the kernel-cases ladder (`tests/kernel-cases/ladder/`,
`cargo xtask kernel-cases --ladder`, [docs/kernel-ladder.md](docs/kernel-ladder.md)).
A change to the persistent names of faces and edges, or to what a stored name finds, re-records the
corpus's names in the same pull request, saying why:
`NAMING_CORPUS_BLESS=1 cargo test --profile ci -p solidcraft-cli --test naming_corpus` (`tests/naming/`).
The naming corpus checks persistent names: every name a corpus design stores still finds a face or
an edge, and two builds name its faces and edges alike
(`cargo test --profile ci -p solidcraft-cli --test naming_corpus`).
[docs/mutation-testing.md](docs/mutation-testing.md) shows how to find kernel behaviour these
black-box suites miss.
+131 -156
View File
@@ -1,20 +1,19 @@
//! Every design of the corpus rebuilds with the same persistent names: the names of each body's
//! faces and edges, with whether each follows exact history, and every name a design stores
//! (fillet and chamfer edges, faces a feature picks, the face a sketch sits on, sheet metal
//! edges) with the face or edge it finds now, by that face's or edge's name. A rename, a name
//! that becomes geometric, a face or edge more or fewer, or a reference that finds another face
//! or none fails the test.
//! Every design of the corpus loads, every name it stores still finds a face or an edge, and
//! two builds of it name its faces and edges alike. The stored names are the fillet and chamfer
//! edges, the faces a feature picks, the face a sketch sits on and the sheet metal edges; one
//! that finds nothing (`gone`, a sketch's face `lost`) fails the test, and so does a design that
//! no longer loads. A build's names are each face's and edge's name with where it is (its area
//! and centre, its length and middle); the second build must give the same, and its stored
//! names must find the same faces and edges.
//!
//! Face and edge indices are left out: they are the kernel's order, which a rebuild need not
//! keep (a fillet's or a boolean's faces come out in another order from one process to the next)
//! and which another kernel changes, while names and references must not change. A body's names
//! are listed sorted.
//! keep (a fillet's or a boolean's faces come out in another order from one build to the next).
//! How many faces a body has and what each is called is the kernel's business, not this test's.
//!
//! The corpus is the action matrix's (the old design files in `tests/corpus`, the examples, the
//! demo and typical designs in `tests/action_matrix/designs`, the reference recipes), the sample
//! designs, the engine's design fixtures and the older designs kept by the hole matrix, taper
//! and projection tests. Each design's record is `tests/naming/<group>/<design>.txt`; to record
//! an intended change, run the test with `NAMING_CORPUS_BLESS=1` and say why in the pull request.
//! and projection tests.
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -28,10 +27,6 @@ fn root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap()
}
fn golden_dir() -> PathBuf {
root().join("tests/naming")
}
/// Where a design comes from.
enum Source {
File(PathBuf),
@@ -120,36 +115,39 @@ fn flags(list: &[(bool, &str)]) -> String {
if set.is_empty() { String::new() } else { format!(" [{}]", set.join(", ")) }
}
/// Whether an edge name carries its own number (`~k`): several edges between the same two faces
/// are numbered by where they lie, which is not exact history.
fn numbered(name: &str) -> bool {
name.rfind('~').and_then(|i| name.get(i + 1..)).is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
}
/// The names of a body's faces and edges, sorted (with how many of each it has).
fn record_body(out: &mut Vec<String>, b: &ModelBody) {
/// Where each named face and edge of a body is, by name, sorted: a face's area and centre, an
/// edge's length and middle, from the body's mesh. Two builds that name their faces alike give
/// the same list.
fn placed_names(b: &ModelBody) -> Vec<(String, [f64; 4])> {
if b.body.is_mesh() {
out.push(format!("body {}: mesh", b.name));
return;
return Vec::new();
}
let faces = naming::face_names(b);
let edges = naming::edge_names(b);
out.push(format!("body {}: {} faces, {} edges", b.name, faces.len(), edges.len()));
let mut lines: Vec<String> =
faces.iter().enumerate().map(|(i, n)| format!("{} face {n}{}", b.name, flags(&[(!naming::face_name_exact(b, i), "geometric")]))).collect();
lines.sort();
out.append(&mut lines);
let m = b.mesh();
let mut lines: Vec<String> = edges
let faces = naming::face_names(b);
let mut sums = vec![[0.0f64; 4]; faces.len()];
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
let [p, q, r] = t.map(|i| m.positions.get(i as usize).copied().unwrap_or(Vec3::ZERO));
let area = (q - p).cross(r - p).len() / 2.0;
let c = (p + q + r) / 3.0;
if let Some(s) = sums.get_mut(*f as usize) {
*s = [s[0] + area, s[1] + area * c.x, s[2] + area * c.y, s[3] + area * c.z];
}
}
let mut out: Vec<(String, [f64; 4])> = faces
.iter()
.enumerate()
.map(|(i, n)| {
let exact = m.edge_faces.get(i).is_some_and(|fs| fs.iter().all(|f| naming::face_name_exact(b, *f as usize))) && !numbered(n);
format!("{} edge {n}{}", b.name, flags(&[(!exact, "geometric")]))
.zip(&sums)
.map(|(n, s)| {
let a = s[0].max(1e-300);
(format!("{} face {n}", b.name), [s[0], s[1] / a, s[2] / a, s[3] / a])
})
.collect();
lines.sort();
out.append(&mut lines);
for (n, line) in naming::edge_names(b).iter().zip(&m.edges) {
let length: f64 = line.windows(2).map(|w| w[1].dist(w[0])).sum();
let mid = line.iter().fold(Vec3::ZERO, |acc, p| acc + *p) / (line.len().max(1) as f64);
out.push((format!("{} edge {n}", b.name), [length, mid.x, mid.y, mid.z]));
}
out.sort_by(|x, y| x.0.cmp(&y.0).then(x.1.partial_cmp(&y.1).unwrap_or(std::cmp::Ordering::Equal)));
out
}
fn face_label(st: &ModelState, body: usize, face: usize) -> String {
@@ -160,8 +158,8 @@ fn face_label(st: &ModelState, body: usize, face: usize) -> String {
}
/// Every name feature `f` stores, with what it finds in the model before it, as a feature
/// rebuilding finds it.
fn record_refs(out: &mut Vec<String>, s: &Session, f: &Feature) {
/// rebuilding finds it, and whether it finds anything.
fn record_refs(out: &mut Vec<(String, bool)>, s: &Session, f: &Feature) {
let doc = &*s.doc;
let who = format!("ref {} ({})", f.name, f.id);
let before = s.model.state_before(f.id);
@@ -173,34 +171,40 @@ fn record_refs(out: &mut Vec<String>, s: &Session, f: &Feature) {
if n.is_empty() {
continue;
}
let found = if explicit_emboss {
"not checked (a cylindrical emboss finds its face on its own body)".to_string()
let (found, ok) = if explicit_emboss {
("not checked (a cylindrical emboss finds its face on its own body)".to_string(), true)
} else {
match naming::locate_face_on_body(&fst, f.kind.face_body(), n, p) {
Some(hit) => format!(
"{}{}",
face_label(&fst, hit.body, hit.face),
flags(&[(hit.split, "split"), (hit.merged, "merged"), (!hit.verified, "geometric"), (hit.legacy, "legacy")])
Some(hit) => (
format!(
"{}{}",
face_label(&fst, hit.body, hit.face),
flags(&[(hit.split, "split"), (hit.merged, "merged"), (!hit.verified, "geometric"), (hit.legacy, "legacy")])
),
true,
),
None => "gone".into(),
None => ("gone".into(), false),
}
};
out.push(format!("{who} face {k} `{n}` -> {found}"));
out.push((format!("{who} face {k} `{n}` -> {found}"), ok));
}
}
// Edges a feature picks by point and stores by name.
if f.edge_names.iter().any(|n| !n.is_empty()) {
let edge = |out: &mut Vec<String>, b: &ModelBody, k: usize, n: &str, p: Vec3| {
let found = match naming::locate_edge(b, n, p) {
Ok(hit) => format!(
"{} edge {}{}",
b.name,
naming::edge_names(b).get(hit.edge).map(String::as_str).unwrap_or("?"),
flags(&[(hit.split, "split"), (!hit.verified, "geometric"), (hit.legacy, "legacy")])
let edge = |out: &mut Vec<(String, bool)>, b: &ModelBody, k: usize, n: &str, p: Vec3| {
let (found, ok) = match naming::locate_edge(b, n, p) {
Ok(hit) => (
format!(
"{} edge {}{}",
b.name,
naming::edge_names(b).get(hit.edge).map(String::as_str).unwrap_or("?"),
flags(&[(hit.split, "split"), (!hit.verified, "geometric"), (hit.legacy, "legacy")])
),
true,
),
Err(e) => format!("gone ({e})"),
Err(e) => (format!("gone ({e})"), false),
};
out.push(format!("{who} edge {k} `{n}` -> {found}"));
out.push((format!("{who} edge {k} `{n}` -> {found}"), ok));
};
let named = |k: usize| f.edge_names.get(k).filter(|n| !n.is_empty());
match &f.kind {
@@ -214,7 +218,7 @@ fn record_refs(out: &mut Vec<String>, s: &Session, f: &Feature) {
}
}
}
None => out.push(format!("{who} edges: no body to round")),
None => out.push((format!("{who} edges: no body to round"), false)),
}
}
FeatureKind::SheetConvert { body, bends, .. } => match before.body(body) {
@@ -225,7 +229,7 @@ fn record_refs(out: &mut Vec<String>, s: &Session, f: &Feature) {
}
}
}
None => out.push(format!("{who} bends: body `{body}` gone")),
None => out.push((format!("{who} bends: body `{body}` gone"), false)),
},
// Sheet metal edges are named by the sheet's panels, and found on its sheets.
FeatureKind::SheetFlange { .. } | FeatureKind::SheetHem { .. } => {
@@ -238,18 +242,19 @@ fn record_refs(out: &mut Vec<String>, s: &Session, f: &Feature) {
let Some(n) = named(k) else { continue };
let on: Vec<&str> = before.sheets.iter().filter(|sh| sh.edge_by_name(n, *p).is_some()).map(|sh| sh.body.as_str()).collect();
let found = if on.is_empty() { "gone".to_string() } else { format!("sheet edge on {}", on.join(", ")) };
out.push(format!("{who} sheet edge {k} `{n}` -> {found}"));
out.push((format!("{who} sheet edge {k} `{n}` -> {found}"), !on.is_empty()));
}
}
other => {
for (k, n) in f.edge_names.iter().enumerate().filter(|(_, n)| !n.is_empty()) {
out.push(format!("{who} edge {k} `{n}` -> not checked ({})", other.type_name()));
out.push((format!("{who} edge {k} `{n}` -> not checked ({})", other.type_name()), true));
}
}
}
}
// The face a sketch sits on.
if let FeatureKind::Sketch { plane: PlaneRef::Face { name, anchor, .. }, .. } = &f.kind {
let mut ok = true;
let status = match doc.sketch_face_attachment(f.id, &s.model) {
FaceAttachmentStatus::Healthy { target, .. } => {
let faces = match before.body(&target.body) {
@@ -260,13 +265,22 @@ fn record_refs(out: &mut Vec<String>, s: &Session, f: &Feature) {
list.sort();
format!("{} faces {}{}", b.name, list.join(", "), flags(&[(note.is_some(), "changed cap")]))
}
Err(e) => format!("no faces ({e})"),
Err(e) => {
ok = false;
format!("no faces ({e})")
}
},
None => format!("body `{}` gone", target.body),
None => {
ok = false;
format!("body `{}` gone", target.body)
}
};
format!("healthy: {faces}")
}
FaceAttachmentStatus::Lost { message, .. } => format!("lost: {message}"),
FaceAttachmentStatus::Lost { message, .. } => {
ok = false;
format!("lost: {message}")
}
FaceAttachmentStatus::Legacy { .. } => {
// Found by its name among the faces facing the same way, nearest the pick.
let fst = solidcraft_engine::doc::state_in_frame(doc, &before, f.component).unwrap();
@@ -299,78 +313,61 @@ fn record_refs(out: &mut Vec<String>, s: &Session, f: &Feature) {
(None, Some(n)) => format!("`{n}`"),
(None, None) => "by its pick".into(),
};
out.push(format!("{who} plane {stored} -> {status}"));
out.push((format!("{who} plane {stored} -> {status}"), ok));
}
}
/// A design's record: its features that failed, every body's names, every stored reference.
fn record(name: &str, s: &Session) -> String {
let mut out = vec![format!("# {name}: persistent names after a rebuild (apps/solidcraft-cli/tests/naming_corpus.rs)")];
for r in s.model.results.iter().filter(|r| r.error.is_some()) {
out.push(format!("failed {} ({})", r.name, r.id));
}
let st = s.model.state();
for b in &st.bodies {
record_body(&mut out, b);
}
/// A build of a design: where its faces and edges are by name, and what every name it stores
/// finds.
struct Build {
names: Vec<(String, [f64; 4])>,
refs: Vec<(String, bool)>,
}
fn build(s: &Session) -> Build {
let names = s.model.state().bodies.iter().flat_map(placed_names).collect();
let mut refs = Vec::new();
for f in s.doc.features.iter().filter(|f| !f.suppressed) {
record_refs(&mut out, s, f);
record_refs(&mut refs, s, f);
}
out.push(String::new());
out.join("\n")
Build { names, refs }
}
/// The lines of `want` and `got` that differ, as `-`/`+` lines (the longest common run of
/// lines kept), at most `cap` of them.
fn diff(want: &str, got: &str, cap: usize) -> Vec<String> {
let (a, b): (Vec<&str>, Vec<&str>) = (want.lines().collect(), got.lines().collect());
let pre = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
let suf = a[pre..].iter().rev().zip(b[pre..].iter().rev()).take_while(|(x, y)| x == y).count();
let (a, b) = (&a[pre..a.len() - suf], &b[pre..b.len() - suf]);
/// Where two builds name their faces and edges apart (at most `cap` of them): a name only one
/// has, or a face or edge of that name somewhere else (1e-6 of its size, to the mesh's rounding).
fn differences(a: &Build, b: &Build, cap: usize) -> Vec<String> {
let mut out = Vec::new();
if a.len().saturating_mul(b.len()) > 25_000_000 {
out.extend(a.iter().map(|l| format!("- {l}")));
out.extend(b.iter().map(|l| format!("+ {l}")));
} else {
// lcs[i][j]: the longest common run of a[i..] and b[j..].
let mut lcs = vec![vec![0u32; b.len() + 1]; a.len() + 1];
for i in (0..a.len()).rev() {
for j in (0..b.len()).rev() {
lcs[i][j] = if a[i] == b[j] { lcs[i + 1][j + 1] + 1 } else { lcs[i + 1][j].max(lcs[i][j + 1]) };
}
}
let (mut i, mut j) = (0, 0);
while i < a.len() || j < b.len() {
if i < a.len() && j < b.len() && a[i] == b[j] {
i += 1;
j += 1;
} else if i < a.len() && (j == b.len() || lcs[i + 1][j] >= lcs[i][j + 1]) {
out.push(format!("- {}", a[i]));
i += 1;
} else {
out.push(format!("+ {}", b[j]));
j += 1;
}
if a.names.len() != b.names.len() {
out.push(format!("{} named faces and edges, then {}", a.names.len(), b.names.len()));
}
for ((n, x), (m, y)) in a.names.iter().zip(&b.names) {
let scale = x.iter().chain(y).fold(1.0f64, |s, v| s.max(v.abs()));
if n != m || x.iter().zip(y).any(|(p, q)| (p - q).abs() > 1e-6 * scale) {
out.push(format!("{n} at {x:?}, then {m} at {y:?}"));
}
}
let n = out.len();
for ((r, _), (q, _)) in a.refs.iter().zip(&b.refs) {
if r != q {
out.push(format!("{r}, then {q}"));
}
}
if a.refs.len() != b.refs.len() {
out.push(format!("{} stored names, then {}", a.refs.len(), b.refs.len()));
}
out.truncate(cap);
if n > cap {
out.push(format!("… and {} more", n - cap));
}
out
}
/// Designs whose names differ from one run to the next today: (design, why). Their records are
/// kept and their differences printed, not failed on, until the cause is fixed.
/// Designs whose names differ from one build to the next today: (design, why). Their
/// differences are printed, not failed on, until the cause is fixed; a stored name that finds
/// nothing still fails.
const UNSTABLE: [(&str, &str); 1] = [(
"regressions/closed_sweep_torus_cut",
"the halves of each swept wall lie level along every axis, so which is `#1` and which `#2` follows the order the kernel gives the faces in, which changes from one process to the next",
"the halves of each swept wall lie level along every axis, so which is `#1` and which `#2` follows the order the kernel gives the faces in, which changes from one build to the next",
)];
#[test]
fn corpus_designs_rebuild_with_the_same_names_and_references() {
let bless = std::env::var_os("NAMING_CORPUS_BLESS").is_some();
fn corpus_designs_keep_their_references_and_name_alike_every_build() {
let designs = designs();
let next = std::sync::atomic::AtomicUsize::new(0);
let results = std::sync::Mutex::new(Vec::new());
@@ -379,56 +376,34 @@ fn corpus_designs_rebuild_with_the_same_names_and_references() {
for _ in 0..workers {
scope.spawn(|| {
while let Some((name, source)) = designs.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) {
let got = match load(source) {
Ok(s) => record(name, &s),
Err(e) => format!("# {name}: does not load: {e}\n"),
};
let got = load(source).and_then(|first| Ok((build(&first), build(&load(source)?))));
results.lock().unwrap_or_else(|e| e.into_inner()).push((name.clone(), got));
}
});
}
});
let mut results = results.into_inner().unwrap_or_else(|e| e.into_inner());
results.sort();
let dir = golden_dir();
results.sort_by(|a, b| a.0.cmp(&b.0));
let mut problems = Vec::new();
for (name, got) in &results {
let path = dir.join(format!("{name}.txt"));
let want = std::fs::read_to_string(&path).unwrap_or_default().replace("\r\n", "\n");
if bless {
if want != *got {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, got).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let (first, second) = match got {
Ok(builds) => builds,
Err(e) => {
problems.push(format!("{name}: does not load: {e}"));
continue;
}
continue;
};
let lost: Vec<&str> = first.refs.iter().filter(|(_, ok)| !ok).map(|(r, _)| r.as_str()).collect();
if !lost.is_empty() {
problems.push(format!("{name}: stored names that find nothing:\n {}", lost.join("\n ")));
}
if want.is_empty() {
problems.push(format!("{name}: no record (tests/naming/{name}.txt)"));
} else if want != *got {
let lines = diff(&want, got, 40).join("\n ");
let apart = differences(first, second, 40);
if !apart.is_empty() {
match UNSTABLE.iter().find(|(design, _)| design == name) {
Some((_, why)) => eprintln!("{name} (not checked: {why}):\n {lines}"),
None => problems.push(format!("{name}:\n {lines}")),
Some((_, why)) => eprintln!("{name} (not checked: {why}):\n {}", apart.join("\n ")),
None => problems.push(format!("{name}: two builds name it apart (first, then second):\n {}", apart.join("\n "))),
}
}
}
// A record whose design left the corpus.
let known: std::collections::BTreeSet<PathBuf> = results.iter().map(|(name, _)| dir.join(format!("{name}.txt"))).collect();
for group in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
for file in std::fs::read_dir(group.path()).into_iter().flatten().flatten() {
if !known.contains(&file.path()) {
if bless {
let _ = std::fs::remove_file(file.path());
} else {
problems.push(format!("{}: a record without a design", file.path().display()));
}
}
}
}
assert!(
problems.is_empty(),
"{} design(s) rebuild with other names than tests/naming records (if that is intended, record it with NAMING_CORPUS_BLESS=1 and say why in the pull request; - recorded, + now):\n{}",
problems.len(),
problems.join("\n")
);
assert!(problems.is_empty(), "{} of {} design(s) of the corpus:\n{}", problems.len(), results.len(), problems.join("\n"));
}
@@ -0,0 +1,44 @@
{
"en": {
"ui.comb_length": "Comb length",
"ui.comb_length_tip": "How long the teeth are: a multiple of the automatic length, which makes the longest tooth a fifth of the size of the curves shown.",
"ui.comb_teeth": "Teeth",
"ui.comb_teeth_tip": "How many teeth each comb has, evenly spaced along the curve. More teeth show more detail of how the curvature changes."
},
"ar": {
"ui.comb_length": "طول المشط",
"ui.comb_length_tip": "طول الأسنان: مضاعف للطول التلقائي الذي يجعل أطول سنّ خُمس حجم المنحنيات المعروضة.",
"ui.comb_teeth": "الأسنان",
"ui.comb_teeth_tip": "عدد أسنان كل مشط، موزّعة بالتساوي على طول المنحنى. كلما زادت الأسنان ظهرت تفاصيل أكثر عن تغيّر الانحناء."
},
"de": {
"ui.comb_length": "Kammlänge",
"ui.comb_length_tip": "Wie lang die Zähne sind: ein Vielfaches der automatischen Länge, bei der der längste Zahn ein Fünftel der Größe der gezeigten Kurven ist.",
"ui.comb_teeth": "Zähne",
"ui.comb_teeth_tip": "Wie viele Zähne jeder Kamm hat, gleichmäßig entlang der Kurve verteilt. Mehr Zähne zeigen genauer, wie sich die Krümmung ändert."
},
"he": {
"ui.comb_length": "אורך המסרק",
"ui.comb_length_tip": "אורך השיניים: כפולה של האורך האוטומטי, שבו השן הארוכה ביותר היא חמישית מגודל העקומות המוצגות.",
"ui.comb_teeth": "שיניים",
"ui.comb_teeth_tip": "כמה שיניים יש לכל מסרק, במרווחים שווים לאורך העקומה. יותר שיניים מראות בפירוט רב יותר איך העקמומיות משתנה."
},
"ja": {
"ui.comb_length": "コームの長さ",
"ui.comb_length_tip": "歯の長さ: 自動の長さの倍率です。自動の長さでは、いちばん長い歯が表示中の曲線の大きさの 5 分の 1 になります。",
"ui.comb_teeth": "歯の数",
"ui.comb_teeth_tip": "各コームの歯の数です。曲線に沿って等間隔に並びます。歯を増やすと、曲率の変わり方がより細かく見えます。"
},
"ko": {
"ui.comb_length": "빗 길이",
"ui.comb_length_tip": "빗살의 길이: 자동 길이의 배수입니다. 자동 길이에서는 가장 긴 빗살이 표시된 곡선 크기의 5분의 1이 됩니다.",
"ui.comb_teeth": "빗살 수",
"ui.comb_teeth_tip": "각 빗의 빗살 수이며, 곡선을 따라 같은 간격으로 놓입니다. 빗살이 많을수록 곡률이 어떻게 바뀌는지 더 자세히 보입니다."
},
"zh": {
"ui.comb_length": "梳长",
"ui.comb_length_tip": "梳齿的长度:自动长度的倍数。自动长度使最长的梳齿为所示曲线尺寸的五分之一。",
"ui.comb_teeth": "梳齿数",
"ui.comb_teeth_tip": "每个梳的梳齿数,沿曲线均匀分布。梳齿越多,越能看清曲率如何变化。"
}
}
+14 -2
View File
@@ -843,9 +843,21 @@ pub(super) fn sheet_eval(
}
}
/// Current unmodified extrusion caps, including placement, certify the tool's depth.
/// Tessellation can drift in thickness at distant coordinates and cannot certify a slab.
/// The tool's depth along the sketch normal (from `source`), the roundoff of that depth and the
/// tool's current footprint where it differs from the profile: from its current unmodified
/// extrusion caps, including placement, else from its exact record proving it a uniform prism
/// along the normal (a To Object tool trimmed by the body it runs to, whose boolean leaves no
/// extrusion faces: its section is its footprint). Tessellation can drift in thickness at
/// distant coordinates and cannot certify a slab.
fn sheet_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> {
extrusion_tool_span(body, source).or_else(|| {
let prism = kernel::certified_prism_section(body, source).ok().flatten()?;
(prism.tolerance <= 1e-7).then_some((prism.lo, prism.hi, prism.tolerance, Some((*source, prism.region))))
})
}
/// [`sheet_tool_span`] from the tool's extrusion caps.
fn extrusion_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> {
use kernel::FaceSource;
#[derive(PartialEq)]
enum Signature<'a> {
+14 -4
View File
@@ -597,10 +597,11 @@ fn end_at_wall(base: &mut Face, wall: &mut Face, ids: (usize, usize), by: f64, b
if let Some(x) = wall.pts.get_mut((k + 1) % m) {
*x = q1;
}
let kept = |j: usize, out: &[usize]| !out.contains(&((j + m - k) % m));
wall.pts = wall.pts.iter().enumerate().filter(|(j, _)| kept(*j, &corners_out)).map(|(_, x)| *x).collect();
wall.across = wall.across.iter().enumerate().filter(|(j, _)| kept(*j, &edges_out)).map(|(_, x)| *x).collect();
wall.round = wall.round.iter().enumerate().filter(|(j, _)| kept(*j, &edges_out)).map(|(_, x)| *x).collect();
// Counted from the bend's edge, so each kept corner is still followed by its own edge
// wherever the face's loop starts.
wall.pts = kept_from(&wall.pts, k, &corners_out);
wall.across = kept_from(&wall.across, k, &edges_out);
wall.round = kept_from(&wall.round, k, &edges_out);
// The fixed face's edge: the bend from `p1` to `q1` (it runs the other way along it), no bend
// beside it.
let (Some(&a), Some(&b)) = (base.pts.get(i), base.pts.get((i + 1) % n)) else { return };
@@ -620,6 +621,15 @@ fn end_at_wall(base: &mut Face, wall: &mut Face, ids: (usize, usize), by: f64, b
base.round.splice(i..=i, std::iter::repeat_n(None, count));
}
/// The items of a loop's per-corner or per-edge list `of`, counted from item `k` on, less those
/// at the places `out` (counted from `k`). Corners and edges taken out at the same places counted
/// from one start stay paired (edge `j` from corner `j`); taken out at their places in the list
/// they would not where the places run across the list's start.
fn kept_from<T: Copy>(of: &[T], k: usize, out: &[usize]) -> Vec<T> {
let m = of.len();
(0..m).filter(|j| !out.contains(j)).filter_map(|j| of.get((k + j) % m).copied()).collect()
}
/// Give flange `i` its panel: `outline` in flat coordinates, counter-clockwise, its edge at the
/// bend first trimmed to the end of the bend zone.
fn set_panel(sh: &mut SheetBody, i: usize, outline: &[Vec2]) {
+4 -3
View File
@@ -167,8 +167,11 @@ fn thin_tilted_plates_cannot_cross_between_axis_bound_samples() {
assert!(value > -2.0 && value < -1.9, "{value}");
}
/// A slider carrying a sphere or a box with a rounded edge stops where it meets a block 5 mm
/// away (the sphere's and the box's near sides at x = 15, the block's at 10): ordinary curved
/// bodies sweep within the contact sampling budget, however their faces are meshed.
#[test]
fn ordinary_curved_bodies_keep_a_practical_sampling_step() {
fn ordinary_curved_bodies_stop_at_their_contact_within_the_sampling_budget() {
for curved in ["sphere", "fillet"] {
let mut s = Session::default();
run(&mut s, "component.create", json!({"name": "Blocker"}));
@@ -187,8 +190,6 @@ fn ordinary_curved_bodies_keep_a_practical_sampling_step() {
json!({"type": "slider", "a": 0, "b": "Curved", "at": {"occurrence": 0, "point": [0,0,0], "z": [1,0,0]}, "name": "Slide"}),
);
run(&mut s, "contact.create", json!({"occurrences": ["Blocker", "Curved"]}));
let geometry = super::ContactGeometry::new(&s).unwrap();
assert!(geometry.step > 1.0, "{curved}: tessellation must not force tiny steps: {}", geometry.step);
let result = run(&mut s, "joint.drive", json!({"joint": "Slide", "value": -30}));
assert!(result["stopped_by_contact"].is_object(), "{curved}: {result}");
let value = s.doc.assembly.joints.iter().find(|j| j.name == "Slide").unwrap().values[0];
+21
View File
@@ -184,6 +184,27 @@ fn internal_capture_in_another_component_anchors_an_offset_face_by_its_history_n
assert_eq!(s.pending_moves, pending);
}
/// Extrude from a face in another component whose occurrence has an uncaptured move, where the
/// face has neither a construction certificate nor an exact history name: a half of a box's top
/// that Split Face divided. The face profile would take the legacy path, which can't capture the
/// source's pending position, so the extrude is refused and changes nothing.
#[test]
fn face_extrude_of_a_split_face_in_another_component_refuses_an_uncaptured_source() {
let mut s = Session::default();
let component = run(&mut s, "component.create", json!({"name":"Source","grounded":false}));
let occurrence = component["occurrence"].as_u64().unwrap();
run(&mut s, "solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Stock"}));
run(&mut s, "solid.split_face", json!({"faces":[[10,15,20]],"plane":{"origin":[20,0,0],"normal":[1,0,0]}}));
run(&mut s, "component.activate", json!({"component":0}));
run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0],"capture":false}));
let before = s.doc.to_json();
let pending = s.pending_moves.clone();
let error = s.execute("solid.extrude", &json!({"face":[40,15,20],"distance":5,"operation":"new"})).unwrap_err();
assert!(error.to_string().contains("capture the source occurrence position"), "{error}");
assert_eq!(s.doc.to_json(), before);
assert_eq!(s.pending_moves, pending);
}
#[test]
fn repeated_source_face_profile_requires_and_uses_the_exact_active_occurrence() {
let mut s = Session::default();
+5 -34
View File
@@ -1725,38 +1725,6 @@ fn fillet_straight_edges_that_end_at_the_arc_wall() {
}
}
/// The vertical knife edge at the tip (the arc and the back face meeting at no angle) rounds to
/// the ball 2 from both, about 13 back from the tip: the cusp beyond the ball, on the tip's side
/// of its contacts, all the way up.
#[test]
fn fillet_the_knife_edge_at_the_tip() {
let cx = 62.166666666666664;
let (kx, ky) = (cx - (23.0f64 * 23.0 - 19.0 * 19.0).sqrt(), -2.0);
let (hx, hy) = (0.002, 0.0005);
let mut area = 0.0;
let mut x = kx + hx / 2.0;
while x < cx {
let lo = -21.0 + (441.0 - (x - cx) * (x - cx)).max(0.0).sqrt();
for j in 0..((0.0 - lo) / hy).ceil() as usize {
let (y0, y1) = (lo + j as f64 * hy, (lo + (j + 1) as f64 * hy).min(0.0));
let y = (y0 + y1) * 0.5;
let a = (y - ky).atan2(x - kx);
if (x - kx).hypot(y - ky) > 2.0 && a >= (-21.0 - ky).atan2(cx - kx) {
area += (y1 - y0) * hx;
}
}
x += hx;
}
let mut s = knife_edge_part();
let before = planned(&s);
run(&mut s, "solid.fillet", json!({"edges": [[cx, 0.0, 5.0]], "radius": 2}));
let after = planned(&s);
assert!(rel(before - after, area * 10.0) < 5e-4, "removed {} vs {}", before - after, area * 10.0);
let mut s = knife_edge_part();
run(&mut s, "solid.chamfer", json!({"edges": [[cx, 0.0, 5.0]], "distance": 2}));
assert!(before - planned(&s) > before - after, "the chamfer takes the ball's bulge off too");
}
/// Rounds of the edges at the arc's top front corner, two or all three together (r 2): they meet
/// in creases (with all three, a piece of sphere fills the corner). Each set takes off its rounds
/// alone, less what each alone takes in a box about the corner, plus what they take there
@@ -1786,7 +1754,10 @@ fn fillet_edges_meeting_at_the_front_corner_of_the_arc() {
}
/// The long top front edge rounded, then the small front-left upright as a fillet of its own
/// (as in the app): the new round ends in the earlier one, taking off what both take together.
/// (as in the app). The upright's tangent chain (the Fillet default, since 84bd2daad) runs on
/// through the first round's end, the quarter circle on the left face, to the top-left edge, so
/// the second fillet rounds the upright and the top-left edge: it takes off what the three edges
/// take together.
#[test]
fn fillet_the_long_edge_then_the_small_left_edge() {
let mut s = knife_edge_part();
@@ -1795,7 +1766,7 @@ fn fillet_the_long_edge_then_the_small_left_edge() {
run(&mut s, "solid.fillet", json!({"edges": [[0.0, -21.0, 5.0]], "radius": 2}));
let one_by_one = before - planned(&s);
let mut s = knife_edge_part();
run(&mut s, "solid.fillet", json!({"edges": [[20.0, -21.0, 10.0], [0.0, -21.0, 5.0]], "radius": 2}));
run(&mut s, "solid.fillet", json!({"edges": [[20.0, -21.0, 10.0], [0.0, -21.0, 5.0], [0.0, -10.0, 10.0]], "radius": 2}));
let together = before - planned(&s);
// Within the display meshes' accuracy (the two are built of different faces).
assert!(rel(one_by_one, together) < 2e-4, "one by one {one_by_one} vs together {together}");
+60 -30
View File
@@ -4,7 +4,6 @@
//! answers the pairs of parts that pass through each other along the way.
use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::{Value, json};
use solidcraft_doc::joints;
@@ -31,8 +30,10 @@ pub const INTERFERENCE_DOC: &str = "study: id|name; occurrences?: [ids or names]
default every occurrence), with against?: [ids or names] (then each of `occurrences` is checked only against these, such \
as an arm against the parts it must miss), or contact_sets?: true (the pairs of the design's contact sets); samples? \
(2…1000, default the study's steps + 1) → collisions: [{a, b, first_step, last_step, steps: [[from, to]…] (the step ranges where they overlap), \
depth_mm (how far into each other, the most at deepest_step), volume_mm3 (their overlap there; null when it was not \
cheap to work out)}], clear, \
volume_mm3 (the most volume they share at a sample, worked out exactly from the bodies), deepest_step (the first sample \
sharing that volume), not_measured (null, or why the volume was not worked out at every sample they overlap, such as \
a budget it ran past: then volume_mm3 and deepest_step are null, never an estimate), depth_mm (how far into each \
other at most: an estimate from points of the bodies' contact meshes, not exact)}], clear, \
pairs (checked), samples (taken), truncated (the work budget ran out; checked_to: the last step checked), stopped_at, \
stopped_by_loop. The study plays as motion.play plays it but contact sets do not stop it, on a copy (the design is not \
changed). Parts are tested at the samples only: one that passes wholly through another between two samples is missed";
@@ -43,9 +44,10 @@ const MAX_SAMPLES: usize = 1000;
const MAX_SERIES: usize = 256;
/// Most collision work over a whole study (see `ContactGeometry::hits`).
const MAX_WORK: usize = 500_000_000;
/// Most colliding pairs whose overlap volume is worked out, and most body booleans that takes.
/// Most colliding pairs whose overlap volume is worked out, and most body booleans that takes
/// over the whole study (one per pair of overlapping bodies at each sample a pair collides).
const MAX_VOLUMES: usize = 16;
const MAX_BOOLEANS: usize = 64;
const MAX_BOOLEANS: usize = 256;
/// How many samples `p` asks for (`min`…`MAX_SAMPLES`, default the study's steps + 1).
fn samples(p: &Value, m: &MotionStudy, min: usize, cmd: &str) -> Result<usize> {
@@ -250,15 +252,26 @@ struct Collision {
names: (String, String),
/// The samples where they overlap, in order.
samples: Vec<usize>,
/// The most sampled mesh depth.
depth: f64,
deepest: usize,
/// The design at the deepest sample (its placements).
at_deepest: Arc<Document>,
/// The most exact shared volume and the first sample sharing it, or why it is not measured
/// (a sample's volume was not worked out).
most_volume: std::result::Result<(f64, usize), String>,
}
/// The volume the parts under occurrences `a` and `b` share, placed as in `doc` (`None`: not
/// worked out). Only bodies whose boxes overlap are intersected, at most `booleans` of them.
fn shared_volume(s: &Session, doc: &Document, a: u64, b: u64, booleans: &mut usize) -> Option<f64> {
impl Collision {
/// Takes the exact shared volume at sample `k`, or why it was not worked out. A volume
/// larger by no more than the booleans' rounding is a tie, which keeps the earlier sample.
fn take_volume(&mut self, k: usize, volume: std::result::Result<f64, String>) {
if let Ok((best, at)) = self.most_volume {
self.most_volume = volume.map(|v| if v > best + 1e-9 * best.max(1.0) { (v, k) } else { (best, at) });
}
}
}
/// The volume the parts under occurrences `a` and `b` share, placed as in `doc`, or why it was
/// not worked out. Only bodies whose boxes overlap are intersected, at most `booleans` of them.
fn shared_volume(s: &Session, doc: &Document, a: u64, b: u64, booleans: &mut usize) -> std::result::Result<f64, String> {
let st = s.model.state();
// The bodies under each (and not under the other), with their world frames and boxes.
let mut sides: [Vec<(Mat, Aabb3, &solidcraft_doc::ModelBody)>; 2] = Default::default();
@@ -278,24 +291,31 @@ fn shared_volume(s: &Session, doc: &Document, a: u64, b: u64, booleans: &mut usi
let corner = Vec3::new(pick(1, local.min.x, local.max.x), pick(2, local.min.y, local.max.y), pick(4, local.min.z, local.max.z));
world.add(apply_point(&frame, corner));
}
sides.get_mut(side)?.push((frame, world, body));
if let Some(list) = sides.get_mut(side) {
list.push((frame, world, body));
}
}
}
let [first, second] = &sides;
let mut total = 0.0;
for (fa, xa, ba) in sides.first()? {
for (fb, xb, bb) in sides.get(1)? {
for (fa, xa, ba) in first {
for (fb, xb, bb) in second {
if xa.max.x < xb.min.x || xb.max.x < xa.min.x || xa.max.y < xb.min.y || xb.max.y < xa.min.y || xa.max.z < xb.min.z || xb.max.z < xa.min.z
{
continue;
}
*booleans = booleans.checked_sub(1)?;
let (pa, pb) = (solidcraft_kernel::transform_matrix(&ba.body, *fa).ok()?, solidcraft_kernel::transform_matrix(&bb.body, *fb).ok()?);
if let Some(shared) = solidcraft_kernel::boolean(&pa, &pb, solidcraft_kernel::BoolOp::Intersect).ok()? {
total += solidcraft_kernel::measure(&shared).ok()?.volume;
*booleans = booleans.checked_sub(1).ok_or_else(|| format!("the check's {MAX_BOOLEANS} body intersections ran out"))?;
let failed = |e: &dyn std::fmt::Display| format!("the intersection of {} and {} could not be made ({e})", ba.name, bb.name);
let (pa, pb) = (
solidcraft_kernel::transform_matrix(&ba.body, *fa).map_err(|e| failed(&e))?,
solidcraft_kernel::transform_matrix(&bb.body, *fb).map_err(|e| failed(&e))?,
);
if let Some(shared) = solidcraft_kernel::boolean(&pa, &pb, solidcraft_kernel::BoolOp::Intersect).map_err(|e| failed(&e))? {
total += solidcraft_kernel::measure(&shared).map_err(|e| failed(&e))?.volume;
}
}
}
Some(total)
Ok(total)
}
/// Contiguous runs of samples, as study step ranges.
@@ -358,12 +378,14 @@ pub(super) fn checked_pairs(s: &Session, p: &Value, cmd: &str) -> Result<Contact
}
pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
let s: &Session = s;
let cmd = "motion.interference";
let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?;
let n = samples(p, &m, 2, cmd)?;
let geometry = checked_pairs(s, p, cmd)?;
let mut found: BTreeMap<(u64, u64), Collision> = BTreeMap::new();
let (mut work, mut checked, mut truncated) = (0usize, 0usize, false);
let mut booleans = MAX_BOOLEANS;
let stop = play(s, &m, n, false, |t, k| {
// Placing the meshes is work too, also where nothing comes near.
work = work.saturating_add(geometry.vertex_count());
@@ -383,18 +405,25 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
for ((a, an), (b, bn), depth) in hits {
// Each pair once, the older occurrence (the lower id) first.
let ((a, an), (b, bn)) = if a <= b { ((a, an), (b, bn)) } else { ((b, bn), (a, an)) };
// The first MAX_VOLUMES pairs found have their shared volume worked out.
let slots = found.len() < MAX_VOLUMES;
let c = found.entry((a, b)).or_insert_with(|| Collision {
names: (an, bn),
samples: Vec::new(),
depth: 0.0,
deepest: k,
at_deepest: t.doc.clone(),
most_volume: if slots {
Ok((0.0, k))
} else {
Err(format!("more than {MAX_VOLUMES} pairs collide: only the first {MAX_VOLUMES} found have their volumes worked out"))
},
});
if c.samples.last() != Some(&k) {
c.samples.push(k);
if c.samples.last() == Some(&k) {
continue;
}
if depth > c.depth {
(c.depth, c.deepest, c.at_deepest) = (depth, k, t.doc.clone());
c.samples.push(k);
c.depth = c.depth.max(depth);
if c.most_volume.is_ok() {
c.take_volume(k, shared_volume(s, &t.doc, a, b, &mut booleans));
}
}
Ok(true)
@@ -405,16 +434,17 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
}
let mut list: Vec<(&(u64, u64), &Collision)> = found.iter().collect();
list.sort_by_key(|(_, c)| c.samples.first().copied().unwrap_or(usize::MAX));
let mut booleans = MAX_BOOLEANS;
let collisions: Vec<Value> = list
.iter()
.enumerate()
.map(|(i, ((a, b), c))| {
let volume = if i < MAX_VOLUMES { shared_volume(s, &c.at_deepest, *a, *b, &mut booleans) } else { None };
.map(|(_, c)| {
let (volume, deepest, not_measured) = match &c.most_volume {
Ok((v, at)) => (Some(*v), Some(step_of(&m, *at, n)), None),
Err(why) => (None, None, Some(why.clone())),
};
let first = c.samples.first().map(|k| step_of(&m, *k, n));
let last = c.samples.last().map(|k| step_of(&m, *k, n));
json!({"a": c.names.0, "b": c.names.1, "first_step": first, "last_step": last, "steps": ranges(&m, &c.samples, n),
"depth_mm": c.depth, "deepest_step": step_of(&m, c.deepest, n), "volume_mm3": volume})
"depth_mm": c.depth, "deepest_step": deepest, "volume_mm3": volume, "not_measured": not_measured})
})
.collect();
let mut out = json!({"study": m.name, "steps": m.steps, "clear": collisions.is_empty(), "collisions": collisions,
+54 -4
View File
@@ -147,10 +147,9 @@ fn interference_names_the_step_two_parts_start_to_collide() {
assert_eq!((c["a"].as_str(), c["b"].as_str()), (Some("A:1"), Some("B:1")), "{r}");
assert_eq!((c["first_step"].as_f64(), c["last_step"].as_f64()), (Some(11.0), Some(15.0)), "{r}");
assert_eq!(c["steps"], json!([[11.0, 15.0]]), "{r}");
let deepest = c["deepest_step"].as_f64().unwrap_or(f64::NAN);
assert!(c["depth_mm"].as_f64().unwrap_or(0.0) > 1.0 && (11.0..=15.0).contains(&deepest), "{r}");
let volume = c["volume_mm3"].as_f64().unwrap_or(f64::NAN);
assert!((volume - 100.0 * (deepest - 10.0)).abs() < 1e-6, "{r}");
// Deepest where they share the most: 5 mm of the 10 x 10 face at the end.
assert!(c["depth_mm"].as_f64().unwrap_or(0.0) > 1.0 && c["deepest_step"] == 15.0, "{r}");
assert!((c["volume_mm3"].as_f64().unwrap_or(f64::NAN) - 500.0).abs() < 1e-6, "{r}");
}
// B against a far block C only: B's pass through A is not asked about.
run(&mut s, "component.create", json!({"name": "C"}));
@@ -167,6 +166,57 @@ fn interference_names_the_step_two_parts_start_to_collide() {
assert!(r["clear"] == true && r["collisions"] == json!([]), "{r}");
}
/// An arm (40 x 10 x 10 from (0, -5, 0)) turns on a hinge at the origin from 0 to 90 degrees in
/// 9 steps into a grounded block (50 x 10 x 10 from (-10, 30, 0)). Its corner (40, 5) reaches
/// y = 40 sin θ + 5 cos θ, past 30 from 40.97 degrees, so it overlaps from step 5. Every point of
/// the slab is within 5 mm of z = 0 or z = 10, so from 60 degrees on (where the arm's side
/// crosses y = 35) the depth is 5 mm at every step: only the shared volume, which grows to the
/// arm's 10 x 10 x 10 end inside the block at 90 degrees, tells the deepest step. Sampled twice
/// as densely (5 degrees a sample), the overlap is seen from step 4.5 (45 degrees) and is still
/// deepest at the end.
#[test]
fn interference_is_deepest_where_the_parts_share_the_most_volume() {
let mut s = Session::default();
for (name, size, corner) in [("Base", [20, 20, 10], [-10, -10, -10]), ("Arm", [40, 10, 10], [0, -5, 0]), ("Stop", [50, 10, 10], [-10, 30, 0])] {
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": name}));
run(&mut s, "solid.box", json!({"length": size[0], "width": size[1], "height": size[2], "corner": corner}));
}
run(&mut s, "component.activate", json!({"component": "root"}));
for name in ["Base", "Stop"] {
let o = occ(&s, name);
run(&mut s, "occurrence.ground", json!({"occurrence": o, "grounded": true}));
}
let end = |o: &str| json!({"occurrence": o, "point": [0, 0, 0], "z": [0, 0, 1]});
run(&mut s, "joint.create", json!({"type": "revolute", "name": "Hinge", "flip": true, "a": end("Base"), "b": end("Arm"), "quiet": true}));
run(&mut s, "motion.study", json!({"name": "Open", "steps": 9, "keys": [{"joint": "Hinge", "points": [[0, 0], [9, 90]]}]}));
for (samples, first) in [(10, 5.0), (19, 4.5)] {
let r = run(&mut s, "motion.interference", json!({"study": "Open", "samples": samples, "occurrences": ["Arm"], "against": ["Stop"]}));
let c = &r["collisions"][0];
assert!(r["clear"] == false && c["first_step"] == first && c["last_step"] == 9.0 && c["deepest_step"] == 9.0, "{samples}: {r}");
assert!((c["volume_mm3"].as_f64().unwrap_or(f64::NAN) - 1000.0).abs() < 1e-6, "{samples}: {r}");
assert!(c["depth_mm"].as_f64().is_some_and(|d| d > 0.0 && d <= 5.0 + 1e-9), "{samples}: {r}");
}
}
/// Pushed through A at 1000 samples, B overlaps it at about 330 of them, one intersection each:
/// past the check's 256, so the volume is not measured and no deepest step is guessed. Where
/// they overlap is still answered.
#[test]
fn interference_past_its_intersection_budget_says_the_volume_is_not_measured() {
let mut s = rail();
run(&mut s, "motion.study", json!({"name": "Push", "steps": 15, "keys": [{"joint": "Rail", "points": [[0, 10], [15, -5]]}]}));
let r = run(&mut s, "motion.interference", json!({"study": "Push", "samples": 1000}));
let c = &r["collisions"][0];
assert!(r["clear"] == false && r["truncated"] == false && c["last_step"] == 15.0, "{r}");
assert!(c["first_step"].as_f64().is_some_and(|f| f > 10.0 && f < 10.1), "{r}");
assert!(c["volume_mm3"].is_null() && c["deepest_step"].is_null(), "{r}");
assert!(c["not_measured"].as_str().is_some_and(|w| w.contains("256 body intersections ran out")), "{r}");
// Within the budget, it is measured.
let r = run(&mut s, "motion.interference", json!({"study": "Push"}));
assert!(r["collisions"][0]["not_measured"].is_null() && r["collisions"][0]["deepest_step"] == 15.0, "{r}");
}
/// A number names a study by its id first, text by its name first: a study may be named like
/// another's id.
#[test]
@@ -59,9 +59,10 @@ fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() {
let mut s = Session::default();
let (width, fb, sd) = tray(&mut s, 320.0);
let all = faces(&mut s);
// Every face but the hole's wall (two halves) has a sheet name, and no two faces share one.
// Every face but the hole's wall (r 3.3, however many faces the kernel makes it of) has a
// sheet name, and no two faces share one.
let unnamed: Vec<_> = all.iter().filter(|f| f.0.is_none()).collect();
assert!(unnamed.len() == 2 && unnamed.iter().all(|f| f.2.is_some_and(|r| (r - 3.3).abs() < 1e-6)), "only the hole's wall: {unnamed:?}");
assert!(!unnamed.is_empty() && unnamed.iter().all(|f| f.2.is_some_and(|r| (r - 3.3).abs() < 1e-6)), "only the hole's wall: {unnamed:?}");
let mut names: Vec<&str> = all.iter().filter_map(|f| f.0.as_deref()).collect();
names.sort_unstable();
let n = names.len();
@@ -84,7 +85,9 @@ fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() {
let radius = |name: &str| named(&all, name).first().and_then(|f| f.2);
assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.inner")).map(|r| (r * 1e6).round() / 1e6), Some(1.0));
assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.outer")).map(|r| (r * 1e6).round() / 1e6), Some(2.0));
// 80 mm wider: the same names, each on the same face where it now is.
// 80 mm wider: the same names, each on the same face where it now is. A name's point is
// somewhere on its face: the right flange's top is the plane x = w − 1, the back flange's
// far rim the strip z = 30, 199 <= y <= 200 (the flange 1 thick, its outside at y = 200).
let right = point(&s, &format!("sheet:Body1:F{sd}.1:top"));
assert!((right.x - 319.0).abs() < 1e-3, "{right:?}");
run(&mut s, "parameters.change", json!({"name": width, "expression": "400"}));
@@ -95,7 +98,7 @@ fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() {
let right = point(&s, &format!("sheet:Body1:F{sd}.1:top"));
assert!((right.x - 399.0).abs() < 1e-3, "{right:?}");
let far = point(&s, &format!("sheet:Body1:F{fb}.1:rim.far"));
assert!((far.y - 199.5).abs() < 1e-3 && (far.z - 30.0).abs() < 1e-3, "{far:?}");
assert!((199.0 - 1e-3..=200.0 + 1e-3).contains(&far.y) && (0.0..=400.0).contains(&far.x) && (far.z - 30.0).abs() < 1e-3, "{far:?}");
}
#[test]
+11 -6
View File
@@ -5424,8 +5424,10 @@ fn flat_exports(s: &mut Session) -> Vec<std::result::Result<Value, String>> {
/// A sheet metal body mirrored, or patterned, into new bodies makes sheet metal bodies (#3353):
/// each copy has a flat pattern and a bend table, and a sheet metal feature on a copy rebuilds it
/// from its moved model where it is. A mirrored copy's model is its source's turned over: the
/// same blank, bent the other way, its pocket on the other face.
/// from its moved model where it is. A mirrored copy's model is its source's mirrored in the
/// flat (x → −x) with the same thickness side (`SheetBody::copied`, d9d6af51c, as
/// `a_mirrored_sheet_copy_is_the_opposite_hand_with_the_mirror_image_flat_pattern` has it): the
/// opposite hand's blank, each bend turning the same way, its pocket on the same face.
#[test]
fn a_mirrored_or_patterned_sheet_body_is_sheet_metal_with_its_flat_pattern() {
use solidcraft_geom::Vec3;
@@ -5443,10 +5445,13 @@ fn a_mirrored_or_patterned_sheet_body_is_sheet_metal_with_its_flat_pattern() {
let copy = s.model.state().bodies[1].name.clone();
assert!(rel(volume(&mut s), 2.0 * before) < 1e-9);
let mirrored = run(&mut s, "sheet.flat_pattern", json!({"body": copy}));
assert_eq!(mirrored["outline"], blank["outline"], "the same blank");
assert_eq!(blank["pockets"][0]["side"], "bottom");
assert_eq!(mirrored["pockets"][0]["side"], "top", "{mirrored}");
assert_eq!((&blank["bends"][0]["direction"], &mirrored["bends"][0]["direction"]), (&json!("up"), &json!("down")), "{mirrored}");
// The source's blank and pocket mirrored, the same size, bend and pocket side.
assert_eq!(mirrored["flat_size_mm"], blank["flat_size_mm"], "{mirrored}");
assert_eq!(flat_points(&mirrored["outline"], 1.0), flat_points(&blank["outline"], -1.0), "the mirrored blank: {mirrored}");
let pocket = |f: &Value| json!([f["pockets"][0]["outline"]]);
assert_eq!(flat_points(&pocket(&mirrored), 1.0), flat_points(&pocket(&blank), -1.0), "{mirrored}");
assert_eq!((&blank["pockets"][0]["side"], &mirrored["pockets"][0]["side"]), (&json!("bottom"), &json!("bottom")), "{mirrored}");
assert_eq!((&blank["bends"][0]["direction"], &mirrored["bends"][0]["direction"]), (&json!("up"), &json!("up")), "{mirrored}");
run(&mut s, "sheet.export_bend_table", json!({"body": copy}));
// The copy's model is where its body is: a flange on the copy rebuilds it in place, its
+172 -49
View File
@@ -13,7 +13,17 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SKETCH", "INSPECT")
.icon("curvature_comb")
.noundo()
.params("curves?: [sketch curve ids] (sketch?: id|name, default active) | edges?: [[x,y,z] points on body edges] | faces?: [[x,y,z] points on faces] with count?: isoparametric curves each way (default 4; combs along the face's iso grid); density?: teeth per curve (default 40), scale?: comb length per unit curvature (default auto)"),
.params(
"curves?: [sketch curve ids] (sketch?: id|name, default active) | edges?: [[x,y,z] points on body edges: the edge whose \
exact curve passes nearest] | faces?: [[x,y,z] points on faces] with count?: isoparametric curves each way (default 4; \
combs along the face's iso grid); density?: teeth per curve, 2…2000 (default 40; on an edge or an iso curve exactly \
that many, evenly spaced along its parameter); scale?: comb length per unit curvature (default auto: the longest \
tooth a fifth of the combs' size); length?: a multiplier on the automatic scale, 0.01…100 (default 1; ignored with \
`scale`). The curvature is exact: from each sketch curve, edge curve (line, circle, ellipse, B-spline, NURBS, \
intersection curve) or face surface's own derivatives, never from the display mesh; a face's teeth are the \
surface's normal curvature along each iso curve, along the surface normal. → combs: [{curve, teeth: [[foot, tip]], \
envelope: [tip], max_curvature, min_radius}], scale",
),
CommandSpec::new("inspect.minimum_radius", "Minimum Radius Analysis", minimum_radius)
.at("SKETCH", "INSPECT")
.icon("min_radius")
@@ -61,25 +71,45 @@ fn teeth_2d(segs: &[Seg2], density: usize) -> Vec<(Vec2, f64, Vec2)> {
out
}
/// Teeth along a 3D polyline (discrete curvature from three consecutive points).
fn teeth_3d(pts: &[Vec3]) -> Vec<(Vec3, f64, Vec3)> {
let mut out = Vec::new();
for w in pts.windows(3) {
let (a, b, c) = (w[0], w[1], w[2]);
let (ab, bc, ca) = (b - a, c - b, a - c);
let area2 = ab.cross(bc).len();
let den = ab.len() * bc.len() * ca.len();
let k = if den > 1e-300 { 2.0 * area2 / den } else { 0.0 };
// Towards the centre of curvature.
let n = (a + c - b * 2.0).normalized().unwrap_or(Vec3::ZERO);
out.push((b, k, n));
/// Teeth from the kernel's exact comb: (foot, curvature, unit normal towards the centre of
/// curvature; zero where straight).
fn teeth_exact(teeth: &[crate::kernel::CombTooth]) -> Vec<(Vec3, f64, Vec3)> {
teeth
.iter()
.map(|t| {
let k = t.curvature.len();
(t.at, k, if k > 0.0 { t.curvature * (1.0 / k) } else { Vec3::ZERO })
})
.collect()
}
/// The comb of the body edge whose exact curve passes nearest `at`, over the model's B-rep bodies
/// (mesh bodies have no curves): `density` exact teeth along it.
fn edge_teeth(st: &solidcraft_doc::ModelState, at: Vec3, density: usize) -> Result<Option<Vec<(Vec3, f64, Vec3)>>> {
let mut best: Option<(f64, &solidcraft_doc::ModelBody, usize)> = None;
for b in st.bodies.iter().filter(|b| !b.body.is_mesh()) {
if let Some((d, edge)) = crate::kernel::comb_edge_near(&b.body, at)?
&& best.is_none_or(|x| d < x.0)
{
best = Some((d, b, edge));
}
}
match best {
Some((_, b, edge)) => Ok(Some(teeth_exact(&crate::kernel::edge_comb(&b.body, edge, density)?))),
None => Ok(None),
}
out
}
fn curvature_comb(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "inspect.curvature_comb";
let density = num(p, "density").map(|d| d.clamp(2.0, 2000.0) as usize).unwrap_or(40);
let density = num(p, "density")
.filter(|d| d.is_finite())
.map(|d| d.clamp(crate::kernel::MIN_COMB_TEETH as f64, crate::kernel::MAX_COMB_TEETH as f64) as usize)
.unwrap_or(40);
let length = match p.get("length") {
None | Some(Value::Null) => 1.0,
Some(v) => v.as_f64().filter(|x| (0.01..=100.0).contains(x)).ok_or_else(|| bad(cmd, "`length` must be a multiplier 0.01…100"))?,
};
let st = s.model.state();
let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new();
let curves = string_list(p, "curves");
@@ -101,21 +131,8 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(edges) = p.get("edges").and_then(Value::as_array) {
for e in edges.iter().take(1000) {
let at = vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))?;
let mut best: Option<(f64, Vec<Vec3>)> = None;
for b in &st.bodies {
let m = b.mesh();
for (i, pts) in m.edges.iter().enumerate() {
if m.seams.get(i).copied().unwrap_or(false) {
continue;
}
let d = pts.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);
if best.as_ref().is_none_or(|x| d < x.0) {
best = Some((d, pts.clone()));
}
}
}
let (_, pts) = best.ok_or_else(|| bad(cmd, "no edge there"))?;
combs.push((format!("edge@{},{},{}", at.x, at.y, at.z), teeth_3d(&pts)));
let teeth = edge_teeth(&st, at, density)?.ok_or_else(|| bad(cmd, "no edge there"))?;
combs.push((format!("edge@{},{},{}", at.x, at.y, at.z), teeth));
}
}
if let Some(faces) = p.get("faces") {
@@ -131,7 +148,8 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result<Value> {
let at = vec3(v).ok_or_else(|| bad(cmd, "`faces` must list points [x,y,z]"))?;
let (body, face) = iso_face_at(s, &world, at).ok_or_else(|| bad(cmd, "no face there"))?;
for (k, line) in body.iso_lines(face, count)?.iter().enumerate() {
combs.push((format!("face@{},{},{}#{k}", at.x, at.y, at.z), teeth_3d(&line.points)));
let teeth = teeth_exact(&crate::kernel::iso_comb(&body.body, face, line, density)?);
combs.push((format!("face@{},{},{}#{k}", at.x, at.y, at.z), teeth));
}
}
}
@@ -142,8 +160,8 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result<Value> {
let kmax = combs.iter().flat_map(|c| c.1.iter().map(|t| t.1.abs())).fold(0.0_f64, f64::max);
let bounds: Aabb3 = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).collect();
let diag = bounds.diagonal();
let scale =
num(p, "scale").filter(|x| *x > 0.0).unwrap_or(if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 });
let auto = if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 };
let scale = num(p, "scale").filter(|x| x.is_finite() && *x > 0.0).unwrap_or(auto * length);
let out: Vec<Value> = combs
.iter()
.map(|(id, teeth)| {
@@ -253,21 +271,8 @@ fn minimum_radius(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(edges) = p.get("edges").and_then(Value::as_array) {
for e in edges.iter().take(1000) {
let at = vec3(e).ok_or_else(|| bad(cmd, "`edges` must be points [x,y,z]"))?;
let mut best: Option<(f64, Vec<Vec3>)> = None;
for b in &st.bodies {
let m = b.mesh();
for (i, pts) in m.edges.iter().enumerate() {
if m.seams.get(i).copied().unwrap_or(false) {
continue;
}
let d = pts.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::INFINITY, f64::min);
if best.as_ref().is_none_or(|x| d < x.0) {
best = Some((d, pts.clone()));
}
}
}
let (_, pts) = best.ok_or_else(|| bad(cmd, "no edge there"))?;
items.push((format!("edge@{},{},{}", at.x, at.y, at.z), min_of(&teeth_3d(&pts))));
let teeth = edge_teeth(&st, at, 400)?.ok_or_else(|| bad(cmd, "no edge there"))?;
items.push((format!("edge@{},{},{}", at.x, at.y, at.z), min_of(&teeth)));
}
}
let faces: Vec<Vec3> = match p.get("faces").and_then(Value::as_array) {
@@ -457,7 +462,7 @@ mod tests {
s.execute("sketch.finish", &json!({})).unwrap();
s.execute("solid.cylinder", &json!({"base": [50, 0, 0], "radius": 8, "height": 10})).unwrap();
let r = s.execute("inspect.curvature_comb", &json!({"edges": [[58, 0, 10]]})).unwrap();
assert!((r["combs"][0]["min_radius"].as_f64().unwrap() - 8.0).abs() < 0.5, "{r}");
assert!((r["combs"][0]["min_radius"].as_f64().unwrap() - 8.0).abs() < 1e-9, "{r}");
assert!(s.execute("inspect.curvature_comb", &json!({})).is_err());
// Combs along the side face's isocurves: rings of radius 8 and straight lines along it.
let r = s.execute("inspect.curvature_comb", &json!({"faces": [[58, 0, 5]], "count": 3})).unwrap();
@@ -470,6 +475,124 @@ mod tests {
assert!(s.execute("inspect.curvature_comb", &json!({"faces": [[58, 0, 5]], "count": "x"})).is_err());
}
/// Each tooth of a comb reply as (foot, curvature): the tooth's length over the scale.
fn tooth_curvatures(r: &Value, comb: usize) -> Vec<([f64; 3], f64)> {
let scale = r["scale"].as_f64().unwrap();
r["combs"][comb]["teeth"]
.as_array()
.unwrap()
.iter()
.map(|t| {
let [a, b] = [0, 1].map(|i| [0, 1, 2].map(|k| t[i][k].as_f64().unwrap()));
(a, (0..3).map(|k| (b[k] - a[k]).powi(2)).sum::<f64>().sqrt() / scale)
})
.collect()
}
/// An edge's comb is its exact curve's: on a cylinder's circular edge of radius R every tooth
/// reads 1/R to 1e-9, at any display quality (the comb never reads the mesh), the teeth stand
/// out of the circle (away from its centre), and `density` is the number of teeth.
#[test]
fn an_edge_comb_is_exact_and_has_density_teeth() {
use solidcraft_doc::display_quality::{DisplayQuality, set_current};
let mut s = Session::default();
s.execute("solid.cylinder", &json!({"base": [50, 0, 0], "radius": 0.75, "height": 40})).unwrap();
let mut feet = Vec::new();
for quality in [DisplayQuality::Coarse, DisplayQuality::Ultra] {
set_current(quality);
let r = s.execute("inspect.curvature_comb", &json!({"edges": [[50.75, 0, 40]], "density": 7})).unwrap();
let teeth = tooth_curvatures(&r, 0);
assert_eq!(teeth.len(), 7, "{r}");
for (foot, k) in &teeth {
assert!((k - 1.0 / 0.75).abs() < 1e-9, "{k} at {foot:?}");
assert!(((foot[0] - 50.0).hypot(foot[1]) - 0.75).abs() < 1e-9 && (foot[2] - 40.0).abs() < 1e-9, "{foot:?}");
}
let tip = &r["combs"][0]["envelope"][2];
assert!((tip[0].as_f64().unwrap() - 50.0).hypot(tip[1].as_f64().unwrap()) > 0.75, "outside the circle");
assert!((r["combs"][0]["max_curvature"].as_f64().unwrap() - 1.0 / 0.75).abs() < 1e-9);
feet.push(r["combs"][0]["teeth"].clone());
}
set_current(DisplayQuality::Normal);
assert_eq!(feet[0], feet[1], "the same comb at any display quality");
let r = s.execute("inspect.curvature_comb", &json!({"edges": [[50.75, 0, 0]], "density": 123})).unwrap();
assert_eq!(r["combs"][0]["teeth"].as_array().unwrap().len(), 123);
for density in [json!("x"), json!(-5), json!(1e300)] {
assert!(s.execute("inspect.curvature_comb", &json!({"edges": [[50.75, 0, 0]], "density": density})).is_ok(), "{density}: clamped");
}
}
/// An ellipse's curvature, a b / (b² cos² t + a² sin² t)^{3/2} at angle t, is a/b² at the ends of
/// its major axis and b/a² at those of its minor one: the comb of an extruded ellipse's edge
/// reads it at every tooth, the ends included.
#[test]
fn an_ellipse_edge_comb_matches_the_closed_form() {
let (a, b) = (10.0_f64, 4.0_f64);
let mut s = Session::default();
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
s.execute("sketch.ellipse", &json!({"center": [0, 0], "major": [a, 0], "minor_radius": b})).unwrap();
s.execute("sketch.finish", &json!({})).unwrap();
s.execute("solid.extrude", &json!({"distance": 5})).unwrap();
let r = s.execute("inspect.curvature_comb", &json!({"edges": [[0, b, 5]], "density": 40})).unwrap();
let exact = |p: [f64; 3]| {
let (c, sn) = (p[0] / a, p[1] / b);
a * b / (b * b * c * c + a * a * sn * sn).powf(1.5)
};
let teeth = tooth_curvatures(&r, 0);
assert!(teeth.len() >= 20, "{r}");
for (foot, k) in &teeth {
assert!(((foot[0] / a).hypot(foot[1] / b) - 1.0).abs() < 1e-9, "on the ellipse: {foot:?}");
assert!((k - exact(*foot)).abs() < 1e-9 * exact(*foot), "{k} vs {} at {foot:?}", exact(*foot));
}
// The vertices: the teeth at the ends of the axes, wherever the edge's parameter puts them.
let at = |q: [f64; 2]| teeth.iter().find(|(f, _)| (f[0] - q[0]).hypot(f[1] - q[1]) < 1e-9).map(|t| t.1);
let major = [[a, 0.0], [-a, 0.0]].into_iter().filter_map(at).collect::<Vec<_>>();
let minor = [[0.0, b], [0.0, -b]].into_iter().filter_map(at).collect::<Vec<_>>();
assert!(!major.is_empty() && !minor.is_empty(), "teeth at the vertices: {teeth:?}");
assert!(major.iter().all(|k| (k - a / (b * b)).abs() < 1e-9), "{major:?}");
assert!(minor.iter().all(|k| (k - b / (a * a)).abs() < 1e-12), "{minor:?}");
assert!((r["combs"][0]["max_curvature"].as_f64().unwrap() - a / (b * b)).abs() < 1e-9, "{r}");
}
/// A face comb follows the surface: on a cylinder's side the iso curves round it read 1/R at
/// every tooth and those along it 0, the teeth along the surface normal; `scale` sets the teeth's
/// length per unit curvature and `length` multiplies the automatic one.
#[test]
fn a_face_comb_is_the_normal_curvature_and_scale_sets_its_length() {
let mut s = Session::default();
s.execute("solid.cylinder", &json!({"radius": 6, "height": 30})).unwrap();
let r = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3, "density": 9})).unwrap();
let combs = r["combs"].as_array().unwrap();
let (mut rings, mut lines) = (0, 0);
for (i, comb) in combs.iter().enumerate() {
let teeth = tooth_curvatures(&r, i);
assert_eq!(teeth.len(), 9, "{comb}");
if teeth.iter().all(|(_, k)| *k == 0.0) {
lines += 1;
assert!(comb["min_radius"].is_null());
} else {
rings += 1;
assert!(teeth.iter().all(|(_, k)| (k - 1.0 / 6.0).abs() < 1e-9), "{teeth:?}");
// Out of the surface, along its normal (radially, at the tooth's height).
for t in comb["teeth"].as_array().unwrap() {
let q = |i: usize, k: usize| t[i][k].as_f64().unwrap();
assert!((q(1, 2) - q(0, 2)).abs() < 1e-9 && q(1, 0).hypot(q(1, 1)) > 6.0 + 1e-6, "{t}");
}
}
}
assert_eq!((rings, lines), (3, 3), "{r}");
// Tooth length is curvature × scale.
let tooth = |r: &Value| tooth_curvatures(r, 0)[0].1 * r["scale"].as_f64().unwrap();
let auto = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3})).unwrap();
let fixed = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3, "scale": 12})).unwrap();
assert!((tooth(&fixed) - 2.0).abs() < 1e-9, "12 × 1/6: {}", tooth(&fixed));
let longer = s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "count": 3, "length": 3})).unwrap();
assert!((longer["scale"].as_f64().unwrap() - 3.0 * auto["scale"].as_f64().unwrap()).abs() < 1e-9);
assert!((tooth(&longer) - 3.0 * tooth(&auto)).abs() < 1e-9);
for bad in [json!(0), json!(-1), json!(1000), json!("2")] {
assert!(s.execute("inspect.curvature_comb", &json!({"faces": [[6, 0, 15]], "length": bad})).is_err(), "{bad}");
}
}
#[test]
fn minimum_radius_and_center_of_mass() {
let mut s = Session::default();
+7 -2
View File
@@ -1259,8 +1259,12 @@ fn free_form_profiles_extrude_exactly() {
run(&mut s, "solid.extrude", json!({"distance": 5}));
let v = vol(&mut s);
assert!((v - pi * 40.0 * 5.0).abs() / (pi * 200.0) < 2e-4, "{v}");
// An exact ellipse: its side's area is h times the perimeter, 4a E(e), e² = 1 − b²/a²
// (by the Gauss–Kummer series, P = 46.026225), and only the top and bottom are planes.
let m = run(&mut s, "inspect.measure", json!({}));
assert_eq!(m["bodies"][0]["faces"], 3, "an exact ellipse: top, bottom and one side ({m})");
let area = m["bodies"][0]["area_mm2"].as_f64().unwrap_or(f64::NAN);
assert!((area - (2.0 * pi * 40.0 + 5.0 * 46.026_225_191_329_7)).abs() < 1e-4, "{area} ({m})");
assert_eq!(m["bodies"][0]["face_types"]["plane"], 2, "{m}");
// A region closed by a fit spline and a line.
let mut s = new_sketch();
let sp = ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [20, 0]]}))["curves"])[0].clone();
@@ -1270,8 +1274,9 @@ fn free_form_profiles_extrude_exactly() {
run(&mut s, "solid.extrude", json!({"distance": 2}));
let v = vol(&mut s);
assert!((v - a * 2.0).abs() / (a * 2.0) < 2e-4, "{v} vs {}", a * 2.0);
// Exact: the spline's side is curved, the planes are the top, the bottom and the line's side.
let m = run(&mut s, "inspect.measure", json!({}));
assert!(m["bodies"][0]["faces"].as_u64().unwrap() <= 5, "{m}");
assert_eq!(m["bodies"][0]["face_types"]["plane"], 3, "{m}");
}
#[test]
+15 -7
View File
@@ -1954,17 +1954,25 @@ mod tests {
(numbers[0], numbers[1])
}
/// Surface Fair on the fitted B-spline face of an offset sphere: the face is smoothed in
/// place, its edges do not move at all, the reply carries the energy before and after, undo,
/// redo and a cold reopen keep it, and hostile inputs are refused.
/// Surface Fair on the fitted B-spline face of a patch on a rim that is not planar (a box's
/// top cut away by a sideways cylinder): the face is smoothed in place, its edges do not move
/// at all, the reply carries the energy before and after, undo, redo and a cold reopen keep
/// it, and hostile inputs are refused.
#[test]
fn fairing_a_b_spline_face_keeps_its_edges_and_reports_its_energy() {
let mut s = Session::default();
run(&mut s, "solid.sphere", json!({"radius": 20, "body_name": "Ball"}));
// A sphere is neither a plane nor a cylinder, so its offset is a fitted B-spline face.
run(&mut s, "surface.offset", json!({"faces": [[0, 0, 20]], "body": "Ball", "distance": 2, "body_name": "Shell"}));
run(&mut s, "solid.box", json!({"length": 28, "width": 28, "height": 20, "corner": [-14, -14, 0], "body_name": "Saddle"}));
run(
&mut s,
"solid.cylinder",
json!({"radius": 40, "height": 120, "base": [0, -60, 50], "axis": "Y", "operation": "cut", "targets": ["Saddle"]}),
);
let z = |x: f64| 50.0 - (1600.0 - x * x).sqrt();
let rim = json!([[14, 0, z(14.0)], [0, 14, z(0.0)], [-14, 0, z(-14.0)], [0, -14, z(0.0)]]);
// The rim is not planar, so its patch is a fitted B-spline face.
run(&mut s, "surface.patch", json!({"edges": rim, "body": "Saddle", "body_name": "Shell"}));
let st = s.world_state().unwrap();
assert!(st.body("Shell").unwrap().body.is_surface(), "an offset sphere face is a sheet");
assert!(st.body("Shell").unwrap().body.is_surface(), "a patch on a rim is a sheet");
let before: Vec<solidcraft_geom::Vec3> = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect();
assert!(!before.is_empty());
let area_before = area(&s, "Shell");
+39 -5
View File
@@ -736,6 +736,36 @@ pub(crate) fn hostile_values() -> Vec<Value> {
]
}
/// A copy of `s` as it stands: its design and model (sharing their bodies, as undo does), its
/// undo and redo, its open sketch and the design it was entered from, and its log.
fn copy_with_history(s: &Session) -> Session {
Session { undo: s.undo.clone(), redo: s.redo.clone(), sketch_entry: s.sketch_entry.clone(), log: s.log.clone(), ..s.scratch() }
}
/// The hostile-parameter test's copy starts where a session built afresh stands: cancelling its
/// sketch and undoing step for step give the same designs, and the copied session is untouched.
#[test]
fn a_copy_with_history_undoes_like_the_session_it_copies() {
let start = |s: &mut Session| {
run(s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
run(s, "sketch.create", json!({"plane": "XY"}));
run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [5, 5]}));
};
let mut fresh = Session::default();
start(&mut fresh);
let mut original = Session::default();
start(&mut original);
let before = original.doc.clone();
let mut copy = copy_with_history(&original);
for (command, params) in [("sketch.cancel", json!({})), ("edit.undo", json!({})), ("edit.undo", json!({})), ("edit.redo", json!({}))] {
run(&mut fresh, command, params.clone());
run(&mut copy, command, params);
assert_eq!(*fresh.doc, *copy.doc, "{command}");
assert_eq!(fresh.active_sketch, copy.active_sketch, "{command}");
}
assert!(std::sync::Arc::ptr_eq(&original.doc, &before) && original.active_sketch.is_some(), "the copied session is untouched");
}
/// Every command, every parameter name it documents, every hostile value: no panic escapes and
/// no command panics internally.
#[test]
@@ -880,16 +910,20 @@ fn hostile_params_never_panic() {
scope.spawn(|| {
let mut internal = Vec::new();
while let Some(&id) = ids.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) {
// A model with a sketch, a body and an active sketch, so most commands get far.
// Built once per command and copied for each call: SMLib serialises every
// call behind one lock, so building the box for each of the ~3000 calls
// ran one after another on every thread (over half an hour in CI).
let mut start = Session::default();
let _ = start.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10}));
let _ = start.execute("sketch.create", &json!({"plane": "XY"}));
let _ = start.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]}));
for v in hostile_values() {
for k in keys {
if k == "path" && (id.starts_with("parameters.") || id == "timeline.export_script") {
continue; // parameter and script files: covered by their own tests (no stray files)
}
let mut s = Session::default();
// A model with a sketch, a body and an active sketch, so most commands get far.
let _ = s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10}));
let _ = s.execute("sketch.create", &json!({"plane": "XY"}));
let _ = s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]}));
let mut s = copy_with_history(&start);
let p = json!({ k: v.clone() });
if let Err(EngineError::Internal(id, msg)) = s.execute(id, &p) {
internal.push(format!("{id} {p}: {msg}"));
+25 -2
View File
@@ -493,8 +493,31 @@ fn open_in_easyprint_hands_the_host_a_3mf_or_an_stl_that_reads_back() {
let seen = seen.lock().unwrap();
assert_eq!((seen[0].0.ends_with(".3mf"), seen[1].0.ends_with(".stl")), (true, true), "{:?}", seen.iter().map(|u| &u.0).collect::<Vec<_>>());
assert!(seen[0].1.starts_with(b"PK"), "a 3MF is a zip");
// A binary STL: 80-byte header, a count, 50 bytes a triangle, and a box has 12.
assert_eq!(seen[1].1.len(), 84 + 50 * 12);
// The STL reads back as the imported mesh: its triangles, closed (every side shared by two
// triangles, each way once), enclosing the 10 × 20 × 30 box's 6000 mm³.
let imported = match &s.doc.features[0].kind {
FeatureKind::MeshImport { meshes, .. } => meshes[0].triangles.len() / 3,
other => panic!("{other:?}"),
};
let tris = solidcraft_io::read_stl(&seen[1].1).unwrap();
assert_eq!(tris.len(), imported);
let key = |p: [f32; 3]| p.map(f32::to_bits);
let mut sides = std::collections::HashMap::<_, i32>::new();
for t in &tris {
for i in 0..3 {
let (a, b) = (key(t[i]), key(t[(i + 1) % 3]));
*sides.entry(if a < b { (a, b) } else { (b, a) }).or_default() += if a < b { 1 } else { -1 };
}
}
assert!(sides.values().all(|n| *n == 0), "an open or inconsistently wound STL");
let at = |p: [f32; 3]| Vec3::new(p[0].into(), p[1].into(), p[2].into());
let volume: f64 = tris.iter().map(|t| at(t[0]).dot(at(t[1]).cross(at(t[2]))) / 6.0).sum();
assert!((volume - 6000.0).abs() < 1e-6, "{volume}");
let (lo, hi) = tris
.iter()
.flatten()
.fold(([f32::MAX; 3], [f32::MIN; 3]), |(lo, hi), p| (std::array::from_fn(|i| lo[i].min(p[i])), std::array::from_fn(|i| hi[i].max(p[i]))));
assert_eq!((lo, hi), ([0.0; 3], [10.0, 20.0, 30.0]));
}
#[test]
+27 -105
View File
@@ -39,26 +39,15 @@ fn shell_with_a_shallow_arc_side() {
]));
}
/// Shell of a plate with a hole whose wall meets the plate's arc side: the edge where the two
/// cylinders meet is neither a line nor an arc, and is rebuilt through its moved points.
#[test]
fn shell_with_a_hole_through_a_curved_side() {
script(json!([
{"command": "sketch.create", "params": {"plane": "XY"}},
{"command": "sketch.line", "params": {"points": [[0, 0], [42.5, 0], [42.5, 20.0], [0, 20.0]]}},
{"command": "sketch.arc.three_point", "params": {"end": [0, 0], "start": [0, 20.0], "through": [-10.0, 10.0]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.extrude", "params": {"distance": 27.5}},
{"command": "solid.cylinder", "params": {"axis": [1.0, 0.0, 0.0], "base": [-10.000000000000002, 12.5, 12.5], "height": 17.5, "operation": "cut", "radius": 5.0}},
{"command": "solid.shell", "params": {"faces": [[42.5, 10.0, 13.75]], "thickness": 2.0}}
]));
}
/// A cut whose end only touches the plate's arc side (#897, robustness seed 14): the end lies
/// tangent to the arc at its apex, the direct boolean fails, and the last-resort nudge used to
/// push the end into the arc, leaving a sliver of it a tenth of a millimetre wide that a shell
/// then couldn't offset. The nudge the other way parts them: the same faces as a cut clear of
/// the apex, and seed 14 shells and fillets again.
/// then couldn't offset. The touching cut must make the same part as a cut 0.1 clear of the
/// apex (x = −10.1 .. 7.4 instead of −10 .. 7.5), less the hole's last 0.1 mm: the arc (centre
/// (0, 10), r 10) reaches x = −10 only at y = 10, so both cuts open the same patch of it, and
/// the slice x = 7.4 .. 7.5 of the r 5 hole lies wholly inside the plate. The touching cut has
/// π 5² 0.1 less volume and 2π 5 0.1 more area (the longer hole wall; the floor disc is the
/// same); a sliver left on the arc adds about a square millimetre of faces.
#[test]
fn cut_whose_end_touches_an_arc_side_leaves_no_sliver() {
let plate = |x: f64| {
@@ -72,11 +61,27 @@ fn cut_whose_end_touches_an_arc_side_leaves_no_sliver() {
]))
};
let (touching, clear) = (plate(-10.0), plate(-10.1));
let faces = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.face_count()).sum::<usize>();
assert_eq!(faces(&touching), faces(&clear), "a sliver face was left where the cut's end touches the arc");
let r = fuzz::run(14, 8);
let kinds: Vec<&str> = r.steps.iter().map(|s| s.kind).collect();
assert!(r.outcome.kind == "ok" && kinds.contains(&"shell"), "seed 14: {:?} {kinds:?}\n{}", r.outcome, r.script());
let area = |s: &Session| s.model.state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).map(|m| m.area).unwrap_or(0.0)).sum::<f64>();
let dv = total_volume(&clear) - total_volume(&touching);
assert!((dv - PI * 25.0 * 0.1).abs() < 1e-4, "volume: clear − touching = {dv}, not π 5² 0.1");
let da = area(&touching) - area(&clear);
assert!((da - 2.0 * PI * 5.0 * 0.1).abs() < 1e-4, "area: touching − clear = {da}, not 2π 5 0.1: a sliver where the cut's end touches the arc");
assert_eq!(touching.model.state().bodies.len(), 1);
}
/// Robustness seed 14 (#897) as the generator made it: the touching cut above, then a shell
/// opening the plate's top face (y = 20). Every step builds and the body is a sound solid.
#[test]
fn shell_after_a_cut_whose_end_touches_an_arc_side() {
script(json!([
{"command": "sketch.create", "params": {"plane": "XY"}},
{"command": "sketch.line", "params": {"points": [[0, 0], [42.5, 0], [42.5, 20.0], [0, 20.0]]}},
{"command": "sketch.arc.three_point", "params": {"end": [0, 0], "start": [0, 20.0], "through": [-10.0, 10.0]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.extrude", "params": {"distance": 27.5}},
{"command": "solid.cylinder", "params": {"axis": [1.0, 0.0, 0.0], "base": [-10.000000000000002, 12.5, 12.5], "height": 17.5, "operation": "cut", "radius": 5.0}},
{"command": "solid.shell", "params": {"faces": [[21.25, 19.999999999999993, 13.749999999999998]], "thickness": 2.0}}
]));
}
/// #827: a hinge barrel joined to a laptop lid through its mounting leaf. The barrel's top lies
@@ -477,27 +482,6 @@ fn planned_volume(s: &Session) -> f64 {
s.model.state().bodies.iter().map(|b| b.body.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(2e-4)).unwrap().evaluate().measure().volume).sum()
}
/// #851: the knife edge where the wall runs out has opposite normals on its two faces. It rounds
/// to the ball that fits there and chamfers with the plane through that ball's contacts (the cusp
/// area less the wall's sector and the ball's, or the chord triangle less the wall's segment,
/// times the 10 mm height).
#[test]
fn blend_a_knife_edge_where_a_curved_wall_runs_out() {
let knife = json!([[62.1667, 0, 5]]);
for (command, params, removed) in
[("solid.fillet", json!({"edges": knife, "radius": 2}), 119.648_812), ("solid.chamfer", json!({"edges": knife, "distance": 2}), 159.236_451)]
{
let mut s = knife_edge_part();
let before = planned_volume(&s);
s.execute(command, &params).unwrap_or_else(|e| panic!("{command}: {e}"));
let after = planned_volume(&s);
assert!((before - after - removed).abs() < 0.5, "{command}: removed {}, expected {removed}", before - after);
for b in &s.model.state().bodies {
assert!(b.body.validity().is_empty(), "{command}: {:?}", b.body.validity());
}
}
}
/// #851: the arc's top edge runs out tangent to the back face at the knife edge's top. The blend
/// is cut by that face along a curve that touches the wall's contact at the tip.
#[test]
@@ -517,53 +501,6 @@ fn blend_an_arc_edge_that_runs_out_tangent_to_a_face() {
}
}
/// #851: every selection of the issue's table works, picked together or one after the other as
/// the issue lists them, on the part with the wall that meets the front face square and runs out
/// tangent into the back face (the top front edge, the arc's top edge, the front upright at the
/// arc, the front-left upright and the knife edge at the tip). Each makes a sound solid the
/// display plan can mesh, and takes less than its edges would one by one where they meet.
#[test]
fn blend_corners_where_edges_meet_on_a_curved_wall() {
let (tf, at, fu, fl, kn) =
(json!([20, -21, 10]), json!([47.3174, -6.1508, 10]), json!([41.1667, -21, 5]), json!([0, -21, 5]), json!([62.1667, 0, 5]));
let fillet = |edges: Value| json!({"command": "solid.fillet", "params": {"edges": edges, "radius": 2}});
let chamfer = |edges: Value| json!({"command": "solid.chamfer", "params": {"edges": edges, "distance": 2}});
let base = planned_volume(&knife_edge_part());
let rows: Vec<(&str, Vec<Value>)> = vec![
("three at the corner", vec![fillet(json!([tf, at, fu]))]),
("top front and arc", vec![fillet(json!([tf, at]))]),
("arc and upright", vec![fillet(json!([at, fu]))]),
("top front and upright", vec![fillet(json!([tf, fu]))]),
("arc alone", vec![fillet(json!([at]))]),
("top front, then the front-left upright", vec![fillet(json!([tf])), fillet(json!([fl]))]),
("top front and front-left together", vec![fillet(json!([tf, fl]))]),
("the knife edge", vec![fillet(json!([kn]))]),
("chamfer: the knife edge", vec![chamfer(json!([kn]))]),
("chamfer: the arc", vec![chamfer(json!([at]))]),
("chamfer: the arc and the top front", vec![chamfer(json!([at, tf]))]),
("arc, then top front", vec![fillet(json!([at])), fillet(json!([tf]))]),
("top front, then upright", vec![fillet(json!([tf])), fillet(json!([fu]))]),
];
for (name, steps) in rows {
let mut s = knife_edge_part();
for step in &steps {
let (c, p) = (step["command"].as_str().unwrap_or(""), &step["params"]);
s.execute(c, p).unwrap_or_else(|e| panic!("{name}: {c} {p}: {e}"));
}
for b in &s.model.state().bodies {
assert!(b.body.validity().is_empty(), "{name}: {:?}", b.body.validity());
assert!(b.body.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(2e-4)).is_ok(), "{name}: the display plan refuses the body");
}
let removed = base - planned_volume(&s);
assert!(removed > 0.0 && removed < 250.0, "{name}: removed {removed}");
}
// The three edges end in a sphere: the volume of the rounds and the ball's corner.
let mut s = knife_edge_part();
s.execute("solid.fillet", &fillet(json!([tf, at, fu]))["params"]).unwrap_or_else(|e| panic!("three at the corner: {e}"));
let removed = base - planned_volume(&s);
assert!((removed - 67.05).abs() < 0.15, "three at the corner: removed {removed}, expected 67.05");
}
/// Seed 20 cuts a patterned cylinder's holes through a filleted plate. The lenient retry of a
/// face's parameter boundary (#970) searched the whole cylinder for a point and found it across
/// the seam, half a turn away; the face was divided wrongly and the cut failed. Such a boundary
@@ -575,21 +512,6 @@ fn a_boundary_found_across_a_seam_is_not_used() {
assert!(r.steps.iter().any(|s| s.kind == "circular pattern"), "the pattern must build, not be skipped as unsupported: {:?}", r.unsupported);
}
/// Seed 33 ends in a fillet on its second body (#854's corner blends build it differently from
/// before). Its display plan and its measured volume agree for every body (on main before #854,
/// that body read 4439.42 through the display plan and 4443.51 measured).
#[test]
fn seed_33_display_plan_and_measure_agree() {
let r = fuzz::run(33, 8);
assert_eq!(r.outcome.kind, "ok", "seed 33: {:?}\n{}", r.outcome, r.script());
let s = script(r.script());
for b in &s.model.state().bodies {
let planned = b.body.mesh_plan(&solidcraft_kernel::MeshTolerance::chord(2e-4)).unwrap().evaluate().measure().volume;
let measured = solidcraft_kernel::measure(&b.body).unwrap().volume;
assert!((planned - measured).abs() < 2e-5 * measured, "{}: planned {planned}, measured {measured}", b.name);
}
}
/// A chamfer on a concave edge fills the corner, so it adds material, as a fillet there does. The
/// fuzzer expected every chamfer to shrink the body and reported these as a wrong volume (about
/// 1 % of the designs of a 6,000-seed run; seed 7100465: a box, a shell, a chamfer of an inside
+91
View File
@@ -8,6 +8,7 @@
//!
//! Call on validated records. Evaluation of a well-formed record never panics: a point that
//! cannot be had (a vanishing weight, a Newton step that does not converge) is `None`.
use super::normal_section::normal_section;
use super::pcurve::Error;
use super::{Curve, Curve2, Frame, Surface};
use crate::Vec3;
@@ -338,6 +339,23 @@ pub enum CurveEval {
Intersection(Box<Intersection>),
}
/// A curve's differential geometry at one parameter.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CurveJet {
pub point: Vec3,
/// The unit tangent, along the curve's parameter.
pub tangent: Vec3,
/// The curvature vector `κ N`, 1/mm: towards the centre of curvature, its length the
/// curvature; zero where the curve is straight.
pub curvature: Vec3,
}
impl CurveJet {
fn is_finite(&self) -> bool {
self.point.is_finite() && self.tangent.is_finite() && self.curvature.is_finite()
}
}
/// A `surface_intersection` ready to evaluate.
#[derive(Clone, Debug, PartialEq)]
pub struct Intersection {
@@ -402,6 +420,44 @@ impl CurveEval {
}
}
/// The point, unit tangent and curvature vector at `t` ([`CurveJet`]), exactly: from the
/// record's first two derivatives on a line, conic or spline (in closed form, or the basis
/// functions' own, weights divided out), straight on each segment of a polyline; on a traced
/// intersection from both surfaces' normal curvatures along its tangent
/// ([`Intersection::jet`]). `None` where the tangent vanishes, the two surfaces are tangent,
/// or a value is not finite.
pub fn jet(&self, t: f64) -> Option<CurveJet> {
if !t.is_finite() {
return None;
}
let (point, d1, d2) = match self {
CurveEval::Line { start, end } => (*start + (*end - *start) * t, *end - *start, Vec3::ZERO),
CurveEval::Conic { axes: a, radii } => {
let (s, c) = t.sin_cos();
let (x, y) = (a.x * (radii[0] * c), a.y * (radii[1] * s));
(a.o + x + y, a.y * (radii[1] * c) - a.x * (radii[0] * s), -(x + y))
}
CurveEval::Polyline(_) => {
let (p, d) = self.leader(t)?;
(p, d, Vec3::ZERO)
}
CurveEval::Spline(c) => match c.derivatives(t, 2)?.as_slice() {
[p, d1, d2] => (*p, *d1, *d2),
_ => return None,
},
CurveEval::Intersection(x) => return x.jet(t),
};
let speed2 = d1.len2();
if !(speed2 > 0.0) {
return None;
}
let tangent = d1 * (1.0 / speed2.sqrt());
// κ N = (r'' − (r''·T) T) / |r'|²: the part of the acceleration across the curve.
let curvature = (d2 - tangent * d2.dot(tangent)) * (1.0 / speed2);
let jet = CurveJet { point, tangent, curvature };
jet.is_finite().then_some(jet)
}
fn leader(&self, t: f64) -> Option<(Vec3, Vec3)> {
match self {
CurveEval::Polyline(p) => {
@@ -442,6 +498,41 @@ impl Intersection {
self.solve(lead, along)
}
/// The curve's [`CurveJet`] at `t`. The tangent is square to both surfaces' normals (along the
/// leader); the curvature vector lies in the plane of those normals, and its component along
/// each is that surface's normal curvature in the tangent's direction (Meusnier), from the
/// surface's exact partial derivatives ([`normal_section`]): two equations for its two
/// components. `None` where the surfaces are tangent (their normals do not span a plane).
fn jet(&self, t: f64) -> Option<CurveJet> {
let (lead, along) = self.leader.leader(t)?;
if !(along.len2() > 0.0) {
return None;
}
let point = self.solve(lead, along)?;
let mut feet = [(Vec3::ZERO, None); 2];
for (foot, s) in feet.iter_mut().zip(&self.surfaces) {
let q = s.project(point, None, f64::INFINITY)?;
let d = s.partials(q[0], q[1])?;
*foot = (d[1][0].cross(d[0][1]).normalized()?, Some(d));
}
let [(n0, Some(d0)), (n1, Some(d1))] = feet else { return None };
let mut tangent = n0.cross(n1).normalized()?;
if tangent.dot(along) < 0.0 {
tangent = -tangent;
}
let k0 = normal_section(&d0, n0, tangent)?.curvature;
let k1 = normal_section(&d1, n1, tangent)?.curvature;
// κN = a n0 + b n1 with κN·n0 = k0 and κN·n1 = k1.
let c = n0.dot(n1);
let det = 1.0 - c * c;
if !(det > 1e-12) {
return None;
}
let (a, b) = ((k0 - c * k1) / det, (k1 - c * k0) / det);
let jet = CurveJet { point, tangent, curvature: n0 * a + n1 * b };
jet.is_finite().then_some(jet)
}
/// Newton on the planes: each surface's tangent plane at the foot of the current point, and
/// the leader's normal plane, until the point stops moving.
fn solve(&self, lead: Vec3, along: Vec3) -> Option<Vec3> {
+49
View File
@@ -954,6 +954,55 @@ fn analytic_partials_are_the_derivatives_of_the_order_below() {
}
}
/// A curve's curvature vector, exactly, on every kind of record: a circle's is 1/R towards its
/// centre (as a conic and as SMLib's rational quadratic B-spline of it); an ellipse's at its
/// vertices is a/b² and b/a²; a line is straight; and the circle where a plane z = 3 cuts a
/// sphere of radius 5 about the origin, traced from a rough leader, has radius 4.
#[test]
fn curve_jets_are_exact_on_every_record() {
use crate::Vec3;
let near = |a: Vec3, b: Vec3| a.dist(b) <= 1e-9 * (1.0 + b.len());
let jet = |c: &Curve, t: f64| eval::CurveEval::new(c).unwrap().jet(t).unwrap();
let flat = Frame { origin: [1., 2., 3.], x_axis: [0.6, 0.8, 0.], y_axis: [-0.8, 0.6, 0.] };
let o = Vec3::new(1., 2., 3.);
for t in [0.0, 0.7, 2.5, 5.9] {
let j = jet(&Curve::Circle { frame: flat.clone(), radius: 4. }, t);
assert!(near(j.curvature, (o - j.point) * (1.0 / 16.0)), "{j:?}");
assert!(j.tangent.dot(j.curvature).abs() < 1e-12);
}
// A quarter circle of radius 2 as a rational quadratic.
let w = std::f64::consts::FRAC_1_SQRT_2;
let quarter =
Curve::RationalSpline { knots: vec![0., 0., 0., 1., 1., 1.], homogeneous: vec![[2., 0., 0., 1.], [2. * w, 2. * w, 0., w], [0., 2., 0., 1.]] };
for t in [0.0, 0.3, 0.5, 1.0] {
let j = jet(&quarter, t);
assert!(near(j.curvature, j.point * -0.25), "{t}: {j:?}");
}
let (a, b) = (10.0, 4.0);
let ellipse = Curve::Ellipse { frame: flat.clone(), radii: [a, b] };
assert!((jet(&ellipse, 0.0).curvature.len() - a / (b * b)).abs() < 1e-12);
assert!((jet(&ellipse, FRAC_PI_2).curvature.len() - b / (a * a)).abs() < 1e-12);
assert_eq!(jet(&Curve::Line { start: [0.; 3], end: [1., 2., 3.] }, 0.4).curvature, Vec3::ZERO);
// The plane z = 3 and a sphere of radius 5: a circle of radius 4 about (0, 0, 3).
let z = Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] };
let leader = Curve::Polyline { points: (0..=12).map(|k| (k as f64 * TAU / 12.0).sin_cos()).map(|(s, c)| [4.1 * c, 4.1 * s, 3.2]).collect() };
let cut = Curve::SurfaceIntersection {
surfaces: [
Box::new(Surface::Plane { origin: [0., 0., 3.], u_axis: [1., 0., 0.], v_axis: [0., 1., 0.] }),
Box::new(Surface::Sphere { frame: z, radius: 5. }),
],
leader: Box::new(leader),
tolerance: 1e-6,
};
for t in [0.0, 1.5, 4.25, 11.0] {
let j = jet(&cut, t);
let centre = Vec3::new(0., 0., 3.);
assert!((j.point.dist(centre) - 4.0).abs() < 1e-9 && (j.point.z - 3.0).abs() < 1e-12, "{j:?}");
assert!(near(j.curvature, (centre - j.point) * (1.0 / 16.0)), "{t}: {j:?}");
assert!(j.tangent.dot(j.point - centre).abs() < 1e-9);
}
}
#[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
-15
View File
@@ -1070,21 +1070,6 @@ mod tests {
}
}
#[test]
fn a_blend_ends_where_a_joined_boss_turns_back_round_its_end() {
// The box's top right edge runs into the cylinder at (40, 8, 20): the blend's end lies on
// the cylinder where the box was, now laid bare.
let body = box_and_boss();
let v0 = vol(&body);
for (round, area) in [(true, (1.0 - std::f64::consts::PI / 4.0) * 0.64), (false, 0.32)] {
let out = blend(&body, &[Vec3::new(40.0, 4.0, 20.0)], 0.8, round).unwrap();
assert!(out.validity().is_empty(), "{:?}", out.validity());
assert_eq!(out.lumps().unwrap().len(), 1);
let removed = v0 - vol(&out);
assert!((removed - area * 8.0).abs() < area * 8.0 * 1e-3, "{removed} vs {}", area * 8.0);
}
}
#[test]
fn a_blend_along_a_boss_ends_on_the_box_side_beside_it() {
// The boss's bottom edge outside the box (a half circle) ends at the box's side, square to
+37 -95
View File
@@ -168,28 +168,40 @@ mod tests {
assert!(fillet_radii(&rounded, &[(seam, 2.0)]).is_err());
}
/// A 40 x 80 x 27 box (and the same shelled 1 mm, open at the top) with its bottom edges
/// rounded R2 as four separate fillets (mitred at the bottom corners), then one vertical
/// edge R2: the same solid whichever of its picks comes first. Horizontal sections: below
/// z = r above the bottom, s up, the rectangle moved in by d = r − ρ, ρ = √(r² − (r − s)²),
/// with the rounded corner a quarter disc of radius ρ less than its square (the sphere octant
/// where the three rounds meet); above, the rectangle less that corner at r. With
/// ∫ ρ = π r² / 4, ∫ ρ² = 2 r³ / 3, ∫ d = r² (1 − π/4) and ∫ d² = r³ (5/3 − π/2) over the
/// bottom r. The shell's cavity, 38 x 78 x 26, lies clear of both rounds (the bottom round's
/// arc passes 2 − √2 from the outer corner along the diagonal, the cavity's corner 1).
#[test]
fn issue2422_vertical_after_separate_bottom_rounds() {
use std::f64::consts::{FRAC_PI_2, FRAC_PI_4};
let origin = Vec3::new(-5.0, 7.2, -2.0);
let b = box_solid(origin, origin + Vec3::new(40.0, 80.0, 27.0)).unwrap();
let (l, w, h, r) = (40.0, 80.0, 27.0, 2.0);
let b = box_solid(origin, origin + Vec3::new(l, w, h)).unwrap();
let bottom = [Vec3::new(15.0, 7.2, -2.0), Vec3::new(35.0, 47.2, -2.0), Vec3::new(15.0, 87.2, -2.0), Vec3::new(-5.0, 47.2, -2.0)];
let spandrel = 1.0 - FRAC_PI_4;
let solid = l * w * r - 2.0 * (l + w) * r * r * spandrel + 4.0 * r * r * r * (5.0 / 3.0 - FRAC_PI_2) - spandrel * 2.0 * r * r * r / 3.0
+ (h - r) * (l * w - spandrel * r * r);
let cavity = (l - 2.0) * (w - 2.0) * (h - 1.0);
// The issue has no design attached. Reconstruct its outside corner and bottom mitre,
// 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()] {
for (base, want) in [(b.clone(), solid), (crate::shell(&b, &[Vec3::new(15.0, 47.2, 25.0)], 1.0).unwrap(), solid - cavity)] {
// 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, &crate::tangent_chain(&rounded, &[edge]).unwrap(), 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, &crate::tangent_chain(&rounded, &selection).unwrap(), 2.0).unwrap();
assert_eq!(result.face_count(), reference.face_count());
assert_eq!(result.unmeshed_faces(), 0);
for selection in [&picks[..1], &picks[..], &[picks[1], picks[0]][..]] {
let result = fillet(&rounded, &crate::tangent_chain(&rounded, selection).unwrap(), 2.0).unwrap();
assert!(result.validity().is_empty(), "{:?}", result.validity());
assert!((vol(&result) - vol(&reference)).abs() < 0.05);
assert!((vol(&result) - want).abs() < 1e-6 * want, "{selection:?}: {} vs {want}", vol(&result));
assert!(!result.contains(Vec3::new(-4.9, 87.1, 10.0)));
assert!(result.contains(Vec3::new(-4.1, 86.3, 10.0)));
}
@@ -223,12 +235,17 @@ mod tests {
#[test]
fn three_rounds_at_a_corner() {
let (bx, a, b, c) = setup();
// Two rounds meeting in a mitre, then the third edge: a sphere octant.
// Two rounds meeting in a mitre, then the third edge with its tangent chain, as the Fillet
// feature asks for it (84bd2daad): the mitre's seam leaves c's end along c, so the chain
// is c and the seam, and the corner is a sphere octant. The cube less its three rounds
// (each (1 − π/4) r² over its 18 mm straight part) and the corner's 2 mm cube less the
// octant (r³ (1 − π/6)).
let ab = fillet(&bx, &[a, b], 2.0).unwrap();
let r = fillet(&ab, &[c], 2.0).unwrap();
let r = fillet(&ab, &crate::tangent_chain(&ab, &[c]).unwrap(), 2.0).unwrap();
let sphere = 8000.0 - 3.0 * (1.0 - std::f64::consts::FRAC_PI_4) * 4.0 * 18.0 - 8.0 * (1.0 - std::f64::consts::PI / 6.0);
assert_eq!(r.face_count(), 10);
assert!((vol(&r) - sphere).abs() < 0.05, "{} vs {sphere}", vol(&r));
assert!(r.validity().is_empty(), "{:?}", r.validity());
assert!((vol(&r) - sphere).abs() < 1e-11 * sphere, "{} vs {sphere}", vol(&r));
assert!(kink(&r) < 0.01);
// Different radii: a smooth patch over the corner, slightly more than the strips take.
for (rs, sel) in [((2.0, 2.0, 3.0), fillet(&ab, &[c], 3.0)), ((2.0, 3.0, 4.0), fillet_radii(&bx, &[(a, 2.0), (b, 3.0), (c, 4.0)]))] {
@@ -281,81 +298,12 @@ mod tests {
}
}
/// A chamfer of a basin's rim loop whose leg would run off the 1 mm rim over the slab's front
/// edge is refused as too large, the kind a fit can reduce. (The largest size that fits is
/// the doc layer's to name; it and the loop's blends that fit, with their exact mitred
/// volumes, are graded by the rig's fillets/1080-*-equal-slope-basin-* cases.)
#[test]
fn sloped_rim_fillets_stay_inside_the_material() {
use solidcraft_geom::{Loop2, Plane, Vec2};
for margin in [0.5, 1.0] {
let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]);
let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap();
let pocket = crate::loft(&[
(Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)),
(Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0)),
])
.unwrap();
let basin = crate::boolean(&slab, &pocket, crate::BoolOp::Cut).unwrap().unwrap();
let picks = [Vec3::new(50.0, margin, 30.0), Vec3::new(80.0, 27.0, 30.0), Vec3::new(50.0, 50.0, 30.0), Vec3::new(20.0, 27.0, 30.0)];
// R4 runs over the thin rim's top past the slab's front edge (a cliff): it is built
// as if the top went on and cut from the slab (the blend-overflow decision,
// 237f0ae74), so nothing of it lies outside the slab.
for count in [1, 2, 4] {
for r in [4.0, margin * 0.5] {
let result = fillet(&basin, &picks[..count], r).unwrap_or_else(|e| panic!("{margin}, {count}, {r}: {e}"));
assert!(result.validity().is_empty(), "{margin}, {count}, {r}: {:?}", result.validity());
assert!(vol(&result) < vol(&basin));
for p in vertices(&result) {
assert!(
p.x >= 0.0 && p.x <= 100.0 && p.y >= 0.0 && p.y <= 60.0 && p.z >= 0.0 && p.z <= 30.0 + 1e-8,
"{margin}, {count}, {r}: {p:?}"
);
}
}
}
}
}
#[test]
fn chamfers_meet_on_unequal_sloped_rim_walls() {
use solidcraft_geom::{Loop2, Plane, Vec2};
for margin in [1.0, 4.0] {
let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]);
let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap();
let pocket = crate::loft(&[
(Plane::XY.offset(30.0), rectangle(20.0, margin, 80.0, 50.0)),
(Plane::XY.offset(10.0), rectangle(30.0, 20.0, 70.0, 40.0)),
])
.unwrap();
let basin = crate::boolean(&slab, &pocket, crate::BoolOp::Cut).unwrap().unwrap();
let picks = [Vec3::new(50.0, margin, 30.0), Vec3::new(80.0, 27.0, 30.0), Vec3::new(50.0, 50.0, 30.0), Vec3::new(20.0, 27.0, 30.0)];
for count in [2, 3, 4] {
if margin == 1.0 {
assert!(crate::chamfer(&basin, &picks[..count], 2.0).is_err());
assert!(crate::chamfer(&basin, &picks[..count], 1.0).is_err());
}
let distance = if margin == 1.0 { 0.5 } else { 2.0 };
let result = crate::chamfer(&basin, &picks[..count], distance).unwrap();
assert!(result.validity().is_empty());
assert_eq!(result.unmeshed_faces(), 0);
assert!(vol(&result) < vol(&basin));
assert!(vol(&basin) - vol(&result) < distance.powi(2) * (60.0 + 50.0 - margin));
let reverse: Vec<_> = picks[..count].iter().copied().rev().collect();
let reversed = crate::chamfer(&basin, &reverse, distance).unwrap();
assert!((vol(&result) - vol(&reversed)).abs() < 1e-6);
// These are exact planes, with every boundary on its owning face.
let rec = Faces::of(&result).unwrap();
for f in 0..rec.rec.faces.len() {
let Some(n) = rec.plane_normal(f) else { continue };
let points: Vec<Vec3> = rec.uses(f).filter_map(|u| rec.ends(u.edge as usize)).flat_map(|(a, b)| [a, b]).collect();
let origin = points[0];
for p in points {
assert!((p - origin).dot(n).abs() < 1e-7);
}
}
}
}
}
#[test]
fn equal_slope_rim_loops_stay_inside_the_material() {
fn a_rim_loop_chamfer_running_off_its_rim_is_refused() {
use solidcraft_geom::{Loop2, Plane, Vec2};
let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]);
let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap();
@@ -364,16 +312,10 @@ mod tests {
.unwrap();
let basin = crate::boolean(&slab, &pocket, crate::BoolOp::Cut).unwrap().unwrap();
let picks = [Vec3::new(50.0, 1.0, 30.0), Vec3::new(80.0, 27.0, 30.0), Vec3::new(50.0, 50.0, 30.0), Vec3::new(20.0, 27.0, 30.0)];
// Past the 1 mm rim the blends run over the slab's front edge (a cliff) and are cut from
// the slab (the blend-overflow decision, 237f0ae74): nothing escapes it.
for (round, size) in [(false, 2.0), (true, 4.0), (false, 0.5), (true, 0.5)] {
let result = if round { fillet(&basin, &picks, size) } else { crate::chamfer(&basin, &picks, size) };
let result = result.unwrap_or_else(|e| panic!("round={round}, {size}: {e}"));
assert!(result.validity().is_empty(), "round={round}, {size}: {:?}", result.validity());
assert!(vol(&result) < vol(&basin));
for p in vertices(&result) {
assert!(p.x >= 0.0 && p.x <= 100.0 && p.y >= 0.0 && p.y <= 60.0 && p.z >= 0.0 && p.z <= 30.0 + 1e-8, "round={round}, {size}: {p:?}");
}
match crate::chamfer(&basin, &picks, 2.0) {
Err(KernelError::TooLarge(_)) => {}
Err(e) => panic!("refused, but not as too large: {e}"),
Ok(_) => panic!("a chamfer whose leg runs off the rim was built"),
}
}
}
+1 -2
View File
@@ -730,8 +730,7 @@ mod tests {
let f = fillet_variable_spline(&wedge, at, t.start, &t.spline).unwrap();
let v = fine_volume(&f);
assert!(rel(v, 6000.0 - removed(&law, 40.0)) < 1e-4, "{v} vs {}", 6000.0 - removed(&law, 40.0));
assert_eq!(f.unmeshed_faces(), 0);
assert!(faces_and_vertices(&f).0.contains(&3));
assert!(f.validity().is_empty(), "{:?}", f.validity());
}
/// A radius spline given directly: a cubic with its control radii pulling the radius up in
@@ -8,7 +8,7 @@ use std::f64::consts::PI;
use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3};
use crate::build::{box_solid, extrude, extrude_tapered};
use crate::{Body, BoolOp, ChamferSide, KernelError, boolean, chamfer, chamfer_sides};
use crate::{Body, BoolOp, ChamferSide, boolean, chamfer, chamfer_sides};
const TOL: f64 = 1e-3;
@@ -193,35 +193,13 @@ fn cone_rim() {
assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out));
}
/// A cylinder's seam is smooth: no edge there to chamfer. (The rim chamfers too large for the
/// faces, past the bottom, past the wall and of an elliptical rim are the rig's
/// fillets/2893-chamfer-* cases; the seam's place is the kernel's, so it stays here.)
#[test]
fn too_large_or_unsupported_is_refused() {
let c = cylinder(0.0);
// Across the whole top: the cone would end in a point.
assert!(chamfer_sides(&c, &[RIM], 10.0, ChamferSide::Distance(3.0), false).is_err());
assert!(chamfer_sides(&c, &[RIM], 12.0, ChamferSide::Distance(3.0), false).is_err());
// Down past the bottom.
assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(25.0), false).is_err());
// An angle that runs past the wall.
assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(PI / 2.0 + 0.01), false).is_err());
// A cylinder's seam is smooth: nothing to chamfer.
assert!(chamfer_sides(&c, &[Vec3::new(10.0, 0.0, 10.0)], 2.0, ChamferSide::Distance(3.0), false).is_err());
// A tilted cylinder cut flat: its rim on the cut is an ellipse, which the loop chamfer does
// not take. Refused as not supported, never a wrong solid.
let tilted = crate::build::cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::new(1.0, 0.0, 2.0), 5.0, 40.0).unwrap();
let cut = box_solid(Vec3::new(-50.0, -50.0, 10.0), Vec3::new(50.0, 50.0, 50.0)).unwrap();
let t = boolean(&tilted, &cut, BoolOp::Cut).unwrap().unwrap();
let rim = t
.record()
.edges
.iter()
.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) {
Err(KernelError::Failed(m)) => assert!(m.starts_with("not supported yet"), "{m}"),
Err(e) => panic!("{e}"),
Ok(_) => panic!("an unequal chamfer of an elliptical rim was built"),
}
}
/// The top loop of a plate with rounded corners: lines and quarter circles, planar and
+172
View File
@@ -0,0 +1,172 @@
//! Curvature combs on a body's edges and along a face's isoparametric curves, from the exact
//! geometry: each tooth stands at an even step of the curve's own parameter and carries the
//! curvature vector there, worked out from the record's derivatives (never from the display
//! mesh), so a comb does not depend on the tessellation and has as many teeth as asked for.
//!
//! An edge's tooth is its curve's curvature vector `κ N` ([`CurveEval::jet`]: lines, conics,
//! polylines, B-splines and NURBS from their first two derivatives, a traced intersection from
//! both surfaces' normal curvatures). A face's tooth along an iso line is the surface's normal
//! curvature in the line's direction times the surface normal, `κₙ n` with
//! `κₙ = n · S_tt / |S_t|²` (the second fundamental form over the first, in that direction).
use solidcraft_geom::Vec3;
use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval};
use crate::body::Body;
use crate::iso::IsoLine;
use crate::{KernelError, Result};
/// Fewest and most teeth along one curve.
pub const MIN_COMB_TEETH: usize = 2;
pub const MAX_COMB_TEETH: usize = 2000;
/// Samples along each edge for the first, coarse look for the edge nearest a point.
const PICK_SAMPLES: usize = 32;
/// Edges (nearest by the coarse look) whose distance is then found exactly.
const PICK_REFINED: usize = 8;
/// Golden-section steps of the exact distance: the bracket shrinks to 0.618⁹⁰ ≈ 10⁻¹⁹ of a sample step.
const PICK_STEPS: usize = 90;
/// One tooth of a comb.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CombTooth {
/// Where the tooth stands, on the curve.
pub at: Vec3,
/// The curvature vector there, 1/mm: towards the centre of curvature, its length the
/// curvature (a face's: the normal curvature along the iso line, along the surface normal).
pub curvature: Vec3,
}
fn check_density(density: usize) -> Result<()> {
if (MIN_COMB_TEETH..=MAX_COMB_TEETH).contains(&density) {
Ok(())
} else {
Err(KernelError::Invalid(format!("a comb has {MIN_COMB_TEETH}…{MAX_COMB_TEETH} teeth")))
}
}
/// The station fractions of `density` teeth: both ends of an open curve, every step of a closed
/// one once (its end is its start).
fn fractions(density: usize, closed: bool) -> impl Iterator<Item = f64> {
let steps = if closed { density } else { density.saturating_sub(1).max(1) };
(0..density).map(move |k| k as f64 / steps as f64)
}
/// The edge of `body` nearest `at` and its exact distance: the distance to the edge's own curve
/// over its interval, not to a tessellation. A periodic face's own seam (an edge whose uses are
/// all on one face, the face meeting itself) and a degenerate edge (a pole) are not edges a comb
/// is drawn on. `None` when the body has no such edge.
pub fn comb_edge_near(body: &Body, at: Vec3) -> Result<Option<(f64, usize)>> {
body.require_brep("a curvature comb")?;
if !at.is_finite() {
return Err(KernelError::Invalid("the point must be finite".into()));
}
crate::guard("curvature comb pick", || {
let record = body.record();
let mut coarse: Vec<(f64, usize, usize)> = Vec::new();
for (index, edge) in record.edges.iter().enumerate() {
let seam = edge.uses.len() >= 2 && edge.uses.iter().all(|u| edge.uses.first().is_some_and(|f| f.face == u.face));
let Ok(curve) = CurveEval::new(edge.parameters()) else { continue };
let [t0, t1] = edge.interval;
if seam || curve.jet(0.5 * (t0 + t1)).is_none() {
continue;
}
let best = (0..=PICK_SAMPLES)
.filter_map(|k| curve.point(t0 + (t1 - t0) * k as f64 / PICK_SAMPLES as f64).map(|q| (q.dist(at), k)))
.filter(|(d, _)| d.is_finite())
.min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((d, k)) = best {
coarse.push((d, index, k));
}
}
coarse.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut best: Option<(f64, usize)> = None;
for &(_, index, k) in coarse.iter().take(PICK_REFINED) {
let Some(edge) = record.edges.get(index) else { continue };
let Ok(curve) = CurveEval::new(edge.parameters()) else { continue };
let Some(d) = nearest_on(&curve, edge.interval, k, at) else { continue };
if best.is_none_or(|(bd, _)| d < bd) {
best = Some((d, index));
}
}
Ok(best)
})
}
/// The distance from `at` to `curve` on `[t0, t1]`, by golden-section search on the sample steps
/// either side of sample `k` (the nearest of [`PICK_SAMPLES`] + 1), ends included.
fn nearest_on(curve: &CurveEval, [t0, t1]: [f64; 2], k: usize, at: Vec3) -> Option<f64> {
let step = (t1 - t0) / PICK_SAMPLES as f64;
let mid = t0 + step * k as f64;
let (mut a, mut b) = ((mid - step).max(t0.min(t1)), (mid + step).min(t0.max(t1)));
let dist = |t: f64| curve.point(t).map(|q| q.dist(at)).filter(|d| d.is_finite());
let ratio = 0.5 * (5f64.sqrt() - 1.0);
let mut best = dist(mid)?;
let (mut x, mut y) = (b - (b - a) * ratio, a + (b - a) * ratio);
let (mut fx, mut fy) = (dist(x)?, dist(y)?);
for _ in 0..PICK_STEPS {
if fx < fy {
(b, y, fy) = (y, x, fx);
x = b - (b - a) * ratio;
fx = dist(x)?;
} else {
(a, x, fx) = (x, y, fy);
y = a + (b - a) * ratio;
fy = dist(y)?;
}
}
for d in [fx, fy, dist(a)?, dist(b)?] {
best = best.min(d);
}
Some(best)
}
/// The comb of edge `edge` of `body` (its index in the body's edge order): `density` teeth at
/// even steps of the edge curve's parameter over the edge, ends included (a closed edge's end is
/// its start, once), each with the curve's exact curvature vector. Stations where the curve has
/// no tangent are left out.
pub fn edge_comb(body: &Body, edge: usize, density: usize) -> Result<Vec<CombTooth>> {
body.require_brep("a curvature comb")?;
check_density(density)?;
crate::guard("curvature comb", || {
let e = body.record().edges.get(edge).ok_or_else(|| KernelError::Invalid(format!("the body has no edge {edge}")))?;
let curve = CurveEval::new(e.parameters()).map_err(|err| KernelError::Failed(format!("curvature comb: {err}")))?;
let [t0, t1] = e.interval;
let closed = e.vertices[0] == e.vertices[1];
Ok(fractions(density, closed)
.filter_map(|f| curve.jet(t0 + (t1 - t0) * f))
.map(|j| CombTooth { at: j.point, curvature: j.curvature })
.collect())
})
}
/// The comb along `line`, an isoparametric curve of face `face` of `body` ([`crate::iso_grid`]):
/// `density` teeth at even steps of the surface parameter that runs along it, ends included, each
/// the surface's normal curvature in the line's direction along its normal, from the surface's
/// exact partial derivatives. Stations at a pole (no tangent along the line) are left out.
pub fn iso_comb(body: &Body, face: usize, line: &IsoLine, density: usize) -> Result<Vec<CombTooth>> {
body.require_brep("a curvature comb")?;
check_density(density)?;
crate::guard("curvature comb", || {
let f = body.record().faces.get(face).ok_or_else(|| KernelError::Invalid(format!("the body has no face {face}")))?;
let surface = SurfaceEval::new(f.parameters()).map_err(|err| KernelError::Failed(format!("curvature comb: {err}")))?;
let [s0, s1] = line.span;
let mut out = Vec::with_capacity(density);
for frac in fractions(density, false) {
let s = s0 + (s1 - s0) * frac;
let [u, v] = if line.along_u { [s, line.fixed] } else { [line.fixed, s] };
let Some(d) = surface.partials(u, v) else { continue };
let (along, bend) = if line.along_u { (d[1][0], d[2][0]) } else { (d[0][1], d[0][2]) };
let speed2 = along.len2();
let Some(n) = d[1][0].cross(d[0][1]).normalized() else { continue };
if !(speed2 > 0.0) {
continue;
}
let curvature = n * (n.dot(bend) / speed2);
if d[0][0].is_finite() && curvature.is_finite() {
out.push(CombTooth { at: d[0][0], curvature });
}
}
Ok(out)
})
}
+2 -23
View File
@@ -166,22 +166,6 @@ fn off_tip(x: f64, y: f64) -> bool {
(x - k.x).hypot(y - k.y) > 2.0 && a >= (-21.0 - k.y).atan2(CX - k.x) && a <= std::f64::consts::FRAC_PI_2
}
/// The knife-edge tip (the arc and the top line meeting at no angle) rounds to the ball 2 from
/// both, 13 back from the tip; its chamfer cuts the cusp at the chord between the same contacts.
#[test]
fn a_knife_edge_tip_rounds_where_the_ball_fits() {
let k = tip_ball();
let round = over_cusp(k.x - 1.0, |x, y| if off_tip(x, y) { 1.0 } else { 0.0 }) * 10.0;
let got = removed(true, &[TIP]);
assert!((got - round).abs() < round * 1e-3, "round: removed {got} vs {round}");
// The chord from the top line's contact to the arc's.
let (a, b) = (Vec2::new(k.x, 0.0), k + (Vec2::new(CX, -21.0) - k) * (2.0 / 23.0));
let beyond = |x: f64, y: f64| (b.x - a.x) * (y - a.y) - (b.y - a.y) * (x - a.x) > 0.0;
let flat = over_cusp(k.x - 1.0, |x, y| if beyond(x, y) { 1.0 } else { 0.0 }) * 10.0;
let got = removed(false, &[TIP]);
assert!((got - flat).abs() < flat * 1e-3, "chamfer: removed {got} vs {flat}");
}
/// The tip's round with the arc's or the back edge's at the top, where all three meet: as at
/// the front corner, each alone less what both would take twice — over the tip's corner region,
/// the other's (above 8 + √(4 − d²), d across from its ball's path).
@@ -239,18 +223,13 @@ fn a_round_ending_in_an_earlier_round_matches_both_together() {
(arc_top(), TIP),
(BACK, TIP),
(arc_top(), BACK),
// The other order (the arc's round once left 0.05 mm³ more at the knife-edge tip).
(BACK, arc_top()),
] {
one_then_the_other(first, then);
}
}
/// The back edge rounded first, then the arc's top edge: the same solid as both together, or the
/// other order (the arc's round once left 0.05 mm³ more at the knife-edge tip).
#[test]
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, 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
+4 -17
View File
@@ -150,13 +150,16 @@ fn rim(m: &Mesh, centre: Vec2, radius: f64, z: f64) -> (usize, f64) {
(segments, widest)
}
/// What the display mesh of a bent sheet 3000 mm long shows at its r1 and r3 bends, whose
/// sagitta is below the chord tolerance: each bend round, a quarter turn in facets that each turn
/// at most `DISPLAY_ANGLE` and so sag at most 1 − cos(angle / 2) of the radius, within the chord
/// tolerance.
#[test]
fn a_small_bend_on_a_large_sheet_is_meshed_round() {
let b = bent_sheet(3000.0);
let tol = display_tol(&b);
// The tolerance is larger than either side's sagitta: 1 - cos 45° of the radius.
assert!(tol > 3.0 * (1.0 - (PI / 4.0).cos()));
let coarse = b.mesh(&crate::MeshTolerance::chord(tol)).unwrap();
let round = b.mesh(&crate::MeshTolerance { chord: tol, angle: Some(DISPLAY_ANGLE) }).unwrap();
// A quarter turn in facets of at most DISPLAY_ANGLE.
let facets = (FRAC_PI_2 / DISPLAY_ANGLE).ceil() as usize;
@@ -165,9 +168,6 @@ fn a_small_bend_on_a_large_sheet_is_meshed_round() {
let faces = cylinder_faces(&b, radius);
assert_eq!(faces.len(), 1, "one bend face of radius {radius}");
let (face, origin, axis) = faces[0];
// The chord tolerance alone: one flat strip from tangent line to tangent line.
assert_eq!(angles_around(&coarse, face, origin, *axis).len(), 2, "radius {radius}");
assert!(sag(&coarse, face, origin, *axis, radius) > 0.29 * radius);
let a = angles_around(&round, face, origin, *axis);
assert!(a.len() > facets, "radius {radius}: {} facets across the bend", a.len() - 1);
assert!((a[a.len() - 1] - FRAC_PI_2).abs() < 1e-6, "the bend is a quarter turn: {a:?}");
@@ -178,19 +178,6 @@ fn a_small_bend_on_a_large_sheet_is_meshed_round() {
let s = sag(&round, face, origin, *axis, radius);
assert!(s <= radius * (1.0 - (DISPLAY_ANGLE / 2.0).cos()) * 1.001 && s < tol, "radius {radius}: sag {s}");
}
// The flat faces along the sheet meet the bends in straight lines and need nothing more:
// only the bends, and the two ends where their arcs now have more points, gain triangles.
let count = |m: &Mesh, face: usize| m.tri_face.iter().filter(|f| **f as usize == face).count();
let mut along = 0;
for face in 0..b.face_count() {
if let Some(FaceSurface::Plane { normal, .. }) = face_surface(&b, face)
&& normal.dot(Vec3::Z).abs() < 0.5
{
along += 1;
assert_eq!(count(&round, face), count(&coarse, face), "face {face}");
}
}
assert_eq!(along, 6);
}
#[test]
+2 -1
View File
@@ -1580,7 +1580,8 @@ mod tests {
assert!(matches!(first_surface(&lid), b::Surface::Plane { .. }), "a planar loop is a plane");
// Hostile crowns are refused before anything is built.
for crown in [f64::NAN, f64::INFINITY, 3.01, -0.91, 1e300] {
assert!(patch_edges_crowned(&open, &rim, crown).is_err(), "crown {crown}");
let e = patch_edges_crowned(&open, &rim, crown).unwrap_err();
assert!(e.to_string().contains("crown must be between -0.9 and 3"), "crown {crown}: {e}");
}
}
}
+3 -135
View File
@@ -9,7 +9,7 @@ use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3};
use super::{PATCH_ANGLE_TOL_DEG, PatchReport, PatchSpec, face_tolerance, patch_edges_report};
use crate::body::Body;
use crate::bridge::Continuity;
use crate::{BoolOp, boolean, box_solid, copy_faces, cylinder, extrude, measure, patch_edges, stitch, torus};
use crate::{BoolOp, boolean, box_solid, copy_faces, cylinder, extrude, measure, patch_edges, stitch};
/// A body's faces as surfaces over their parameter boxes, with the (u, v) polygon of each face's
/// loops (its exact pcurves, sampled).
@@ -212,15 +212,6 @@ fn report(name: &str, r: &PatchReport) {
);
}
/// A cylinder about z of radius 10 and 30 high with its top face taken off; points around the rim.
fn open_tube() -> (Body, Vec<Vec3>) {
let solid = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 30.0).unwrap();
let open = copy_faces(&solid, &[&around(10.0, 15.0)[..], &[Vec3::ZERO]].concat()).unwrap();
assert!(open.is_surface());
let rim = (0..8).map(|k| Vec2::from_angle(k as f64 * 0.785).extend(0.0) * 10.0 + Vec3::Z * 30.0).collect();
(open, rim)
}
/// `body` without its planar faces but those at height `z0` or `z1` (the ends of a cylinder):
/// a cut solid's walls (and ends) as a surface, the faces the cut made taken away.
fn curved_and_ends(body: &Body, ends: &[f64]) -> Body {
@@ -258,130 +249,10 @@ fn free_edge_points(body: &Body) -> Vec<Vec3> {
points
}
/// Points round the circle of radius `r` about z at height `z`, every 30°.
fn around(r: f64, z: f64) -> Vec<Vec3> {
(0..12).map(|k| Vec2::from_angle(0.1 + k as f64 * std::f64::consts::TAU / 12.0).extend(0.0) * r + Vec3::Z * z).collect()
}
fn radial(p: Vec3) -> Vec3 {
Vec3::new(p.x, p.y, 0.0).normalized().unwrap()
}
#[test]
fn an_opened_tube_end_capped_g1_and_g2_meets_the_wall() {
let (open, rim) = open_tube();
let mut kappas = Vec::new();
for g in [Continuity::G1, Continuity::G2] {
let name = format!("tube end {}", g.as_str());
let started = std::time::Instant::now();
let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap();
eprintln!("{name}: filled in {:?}", started.elapsed());
report(&name, &r);
assert!(r.general);
let area = check_face(&name, &open, &fill);
// The wall's normal is radial and it does not bend along its axis.
let (gap, angle, kappa) = along_the_loop(&fill, &radial, &|_| 0.0);
eprintln!(
"{name}: along the rim (1600 points): within {gap:e} of it, normal within {angle:.5}° of the wall's, curvature across {kappa:e} /mm (the wall's 0)"
);
assert!(angle < 0.1, "{name}: the normal turns {angle}° from the wall's");
kappas.push(kappa);
// A dome over the rim, not a flat lid: more than the disc.
assert!(area > std::f64::consts::PI * 100.0 * 1.05, "{name}: {area}");
// Sealed: the tube's volume plus the dome's, the dome's by the divergence theorem over the
// patch (∫∫ (z − 30)·n_z dA), independent of the mesher.
let closed = stitch(&[&open, &fill], 0.0).unwrap();
assert!(!closed.is_surface(), "{name}: the cap closes the tube");
let dome = Faces::of(&fill).quadrature(500, &|p, n| (p.z - 30.0) * n.z).abs();
let (got, want) = (measure(&closed).unwrap().volume, std::f64::consts::PI * 100.0 * 30.0 + dome);
eprintln!("{name}: sealed volume {got:.3}, tube + dome {want:.3}");
assert!((got - want).abs() < 2e-4 * want, "{name}: {got} vs {want}");
}
eprintln!("tube end: curvature across the rim g1 {:e}, g2 {:e} /mm", kappas[0], kappas[1]);
assert!(kappas[1] < kappas[0], "g2 holds the wall's curvature closer than g1");
}
/// A cylinder about z (radius 10, 40 high) with a window `half` either side of the x axis
/// through its wall, from z = 15 to 25; the wall and both ends without the faces the cut made (the
/// window's edges bound only the wall), and a point on each of the window's edges.
fn windowed(half: f64) -> (Body, Body, Vec<Vec3>) {
let solid = cylinder(Vec3::ZERO, Vec3::Z, 10.0, 40.0).unwrap();
let x = 10.0 * half.cos();
let tool = box_solid(Vec3::new(x, -11.0, 15.0), Vec3::new(11.0, 11.0, 25.0)).unwrap();
let cut = boolean(&solid, &tool, BoolOp::Cut).unwrap().unwrap();
let open = curved_and_ends(&cut, &[0.0, 40.0]);
let rim = free_edge_points(&open);
(solid, open, rim)
}
#[test]
fn a_window_cut_through_a_cylinder_wall_past_half_way_fills_g1_close_to_the_cylinder() {
// 240° round: seen along any direction the window folds over itself, so it bounds no height
// field; the old fill refused it.
let half = 2.0 * std::f64::consts::PI / 3.0;
let (solid, open, rim) = windowed(half);
for g in [Continuity::G0, Continuity::G1] {
let name = format!("window {}", g.as_str());
let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap();
report(&name, &r);
let area = check_face(&name, &open, &fill);
let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0);
eprintln!("{name}: along the window (1600 points): within {gap:e}, normal within {angle:.5}° of the wall's");
// How far the fill strays from the cylinder it replaces, inside.
let mut stray = 0.0f64;
for (s, [[u0, u1], [v0, v1]], _) in &Faces::of(&fill).faces {
for i in 0..=40 {
for j in 0..=40 {
let p = s.point([u0 + (u1 - u0) * i as f64 / 40.0, v0 + (v1 - v0) * j as f64 / 40.0]).unwrap();
let ang = p.y.atan2(p.x);
if ang.abs() < half - 0.05 && p.z > 15.5 && p.z < 24.5 {
stray = stray.max((Vec2::new(p.x, p.y).len() - 10.0).abs());
}
}
}
}
let exact = 10.0 * 2.0 * half * 10.0;
let closed = stitch(&[&open, &fill], 0.0).unwrap();
let (got, want) = (measure(&closed).unwrap().volume, measure(&solid).unwrap().volume);
eprintln!(
"{name}: area {area:.3} (the cylinder's window {exact:.3}), the fill within {stray:.4} of the cylinder inside, sealed volume {got:.2} against the whole cylinder's {want:.2}"
);
assert!(!closed.is_surface());
if g == Continuity::G1 {
assert!(angle < 0.1, "{name}: the normal turns {angle}° from the wall's");
assert!((area - exact).abs() < 0.01 * exact && stray < 0.25, "{name}: {area} vs {exact}, stray {stray}");
assert!((got - want).abs() < 0.005 * want, "{name}: {got} vs {want}");
}
}
}
#[test]
fn a_saddle_window_in_a_torus_fills_g0_and_g1() {
// The inner wall of a torus (major 20, minor 8) is saddle-shaped; a window 240° round it
// between z = ±3 bounds no height field.
let solid = torus(Vec3::ZERO, 20.0, 8.0).unwrap();
let tool = box_solid(Vec3::new(-6.0, -13.0, -3.0), Vec3::new(13.0, 13.0, 3.0)).unwrap();
let cut = boolean(&solid, &tool, BoolOp::Cut).unwrap().unwrap();
let open = curved_and_ends(&cut, &[]);
let rim = free_edge_points(&open);
// The torus's normal: from the tube's centre circle.
let normal = |p: Vec3| {
let c = Vec3::new(p.x, p.y, 0.0).normalized().unwrap() * 20.0;
(p - c).normalized().unwrap()
};
for g in [Continuity::G0, Continuity::G1] {
let name = format!("torus window {}", g.as_str());
let (fill, r) = patch_edges_report(&open, &rim, &spec(g)).unwrap();
report(&name, &r);
check_face(&name, &open, &fill);
let (gap, angle, _) = along_the_loop(&fill, &normal, &|_| 0.0);
eprintln!("{name}: along the window (1600 points): within {gap:e}, normal within {angle:.5}° of the torus's");
if g == Continuity::G1 {
assert!(angle < 0.1, "{name}: {angle}°");
}
}
}
/// A cylinder about z (radius 10, 40 high) with a pentagonal pocket cut into its wall from the
/// +x side (the pentagon in the yz plane about z = 20, circumradius 6): the wall and both ends
/// copied out, and a point on each of the pocket rim's five edges.
@@ -400,8 +271,6 @@ fn a_five_sided_window_fills_g1_and_through_a_point() {
let (open, rim) = pentagon_window();
let (fill, r) = patch_edges_report(&open, &rim, &spec(Continuity::G1)).unwrap();
report("pentagon g1", &r);
// Five patches about a centre: each rim edge in two halves, and five spokes.
assert!(fill.face_count() == 5 && fill.edge_count() >= 15, "five patches on the rim's halves and five spokes");
check_face("pentagon g1", &open, &fill);
let (gap, angle, _) = along_the_loop(&fill, &radial, &|_| 0.0);
eprintln!("pentagon g1: along the rim: within {gap:e}, normal within {angle:.5}° of the wall's");
@@ -437,12 +306,11 @@ fn a_hexagonal_rim_fills_through_a_point_and_g1_to_walls_meeting_at_angles_holds
let open = copy_faces(&solid, &keep).unwrap();
let plain = patch_edges(&open, &rim).unwrap();
let sealed = |f: &Body| measure(&stitch(&[&open, f], 0.0).unwrap()).unwrap().volume;
// Six sides, G0, through a point 3 mm above the middle of the plain fill: six patches about
// a centre.
// Six sides, G0, through a point 3 mm above the middle of the plain fill: it passes through
// the point and seals the cup into a closed solid holding more than the plain fill's.
let point = Faces::of(&plain).nearest(Vec3::new(0.0, 0.0, 12.0)).2 + Vec3::Z * 3.0;
let (lifted, r) = patch_edges_report(&open, &rim, &PatchSpec { points: vec![point], ..PatchSpec::default() }).unwrap();
report("hexagon through a point", &r);
assert_eq!((lifted.face_count(), lifted.edge_count()), (6, 18), "six patches on the rim's twelve halves and six spokes");
check_face("hexagon through a point", &open, &lifted);
let off = Faces::of(&lifted).nearest(point).2.dist(point);
eprintln!("hexagon through a point: the point is {off:e} off the surface; sealed {:.2} against {:.2} plain", sealed(&lifted), sealed(&plain));
+14 -8
View File
@@ -35,6 +35,9 @@ pub struct IsoLine {
/// The exact record curve on `interval` of its own parameter.
pub curve: brep::Curve,
pub interval: [f64; 2],
/// The surface parameter that runs along the curve (u when `along_u`, else v), from the
/// start of `interval` to its end.
pub span: [f64; 2],
/// Its points from the start of `interval` to its end, at the chord tolerance asked for.
pub points: Vec<Vec3>,
}
@@ -104,9 +107,10 @@ impl<'a> FaceTrims<'a> {
}
/// The iso line of the surface at `fixed` (v when `along_u`, else u) across the face's box,
/// cut to the face: the pieces inside it, each as its exact record curve on its interval, in
/// the order the line runs (none when the line misses the face).
fn clip(&self, along_u: bool, fixed: f64) -> Result<Vec<(brep::Curve, [f64; 2])>> {
/// cut to the face: the pieces inside it, each as its exact record curve on its interval and
/// the running parameter's span, in the order the line runs (none when the line misses the
/// face).
fn clip(&self, along_u: bool, fixed: f64) -> Result<Vec<(brep::Curve, [f64; 2], [f64; 2])>> {
let [[u0, u1], [v0, v1]] = self.domain;
let (lo, hi) = if along_u { (u0, u1) } else { (v0, v1) };
let at_t = |t: f64| if along_u { [t, fixed] } else { [fixed, t] };
@@ -149,11 +153,13 @@ impl<'a> FaceTrims<'a> {
if self.inside(at_t(0.5 * (a + b))) {
run = Some(run.map_or((a, b), |(s, _)| (s, b)));
} else if let Some(r) = run.take() {
out.push(iso_record(self.surface, along_u, fixed, r)?);
let (curve, interval) = iso_record(self.surface, along_u, fixed, r)?;
out.push((curve, interval, [r.0, r.1]));
}
}
if let Some(r) = run {
out.push(iso_record(self.surface, along_u, fixed, r)?);
let (curve, interval) = iso_record(self.surface, along_u, fixed, r)?;
out.push((curve, interval, [r.0, r.1]));
}
Ok(out)
}
@@ -184,7 +190,7 @@ pub fn iso_curves(body: &Body, face: usize, at: Vec3, along_u: bool) -> Result<V
}
}
}
let out = trims.clip(along_u, if along_u { pv } else { pu })?;
let out: Vec<(brep::Curve, [f64; 2])> = trims.clip(along_u, if along_u { pv } else { pu })?.into_iter().map(|(c, i, _)| (c, i)).collect();
if out.is_empty() {
return Err(KernelError::Invalid("the iso curve runs outside the face".into()));
}
@@ -216,13 +222,13 @@ pub fn iso_grid(body: &Body, face: usize, count: usize, chord: f64) -> Result<Ve
}
for k in 1..=count {
let fixed = lo + (hi - lo) * k as f64 / (count + 1) as f64;
for (curve, interval) in trims.clip(along_u, fixed)? {
for (curve, interval, span) in trims.clip(along_u, fixed)? {
let segs = curve_path(&curve, interval)?;
let mut points: Vec<Vec3> = segs.first().map(crate::PathSeg::start).into_iter().collect();
for s in &segs {
points.extend(s.points_after_start(chord));
}
out.push(IsoLine { along_u, fixed, curve, interval, points });
out.push(IsoLine { along_u, fixed, curve, interval, span, points });
}
}
}
-81
View File
@@ -103,84 +103,3 @@ fn chamfers_meeting_at_a_corner_still_build() {
assert!(crate::chamfer(&b, &edges, 5.0).is_ok());
assert!(crate::fillet(&b, &edges, 5.0).is_ok());
}
/// #1668: a box shelled outward 2 mm, open at the bottom. R5 on its top outer edge alone leaves
/// the sharp inside corner 2 mm away on its ball's side, 0.76 mm inside the round; it reaches
/// the corner only past 2√2 / (√2 - 1) ≈ 6.83 mm. With the inside edge rounded in the same
/// fillet, the two build as one feature as they do one after the other: the outer round takes
/// (1 - π/4) · 25 mm² along 104 mm, the inner one adds it along 100 mm.
#[test]
fn rounds_on_both_sides_of_a_wall_build_as_one_fillet() {
let outer = box_solid(Vec3::new(-52.0, -32.0, 0.0), Vec3::new(52.0, 32.0, 42.0)).unwrap();
let shelled = cut(&outer, [-50.0, -30.0, -1.0], [50.0, 30.0, 40.0]);
let v0 = 104.0 * 64.0 * 42.0 - 100.0 * 60.0 * 40.0;
let (out_edge, in_edge) = (Vec3::new(0.0, 32.0, 42.0), Vec3::new(0.0, 30.0, 40.0));
let section = (1.0 - std::f64::consts::FRAC_PI_4) * 25.0;
let alone = crate::fillet(&shelled, &[out_edge], 5.0).unwrap();
assert!(alone.validity().is_empty(), "{:?}", alone.validity());
let want = shelled.volume_at(0.01).unwrap() - section * 104.0;
assert!((crate::measure(&alone).unwrap().volume - want).abs() < 1e-4 * want);
// R7 alone passes the inside corner: the round is cut from the wall as if the hollow were
// not there, which opens a slit along the hollow's 100 mm. Its section (1 - π/4)·49 along
// 104, less its part over the hollow, the square [25, 30] × [35, 40] outside the circle about
// (25, 35) of radius 7: 5 (5 - √24) - (F(5) - F(√24)), F(t) = (t √(49 - t²) + 49 asin(t/7)) / 2.
let f = |t: f64| 0.5 * (t * (49.0 - t * t).sqrt() + 49.0 * (t / 7.0).asin());
let over = 5.0 * (5.0 - 24f64.sqrt()) - (f(5.0) - f(24f64.sqrt()));
let section7 = (1.0 - std::f64::consts::FRAC_PI_4) * 49.0;
let wide = crate::fillet(&shelled, &[out_edge], 7.0).unwrap();
assert!(wide.validity().is_empty(), "{:?}", wide.validity());
let want = v0 - (section7 * 104.0 - over * 100.0);
let v = crate::measure(&wide).unwrap().volume;
assert!((v - want).abs() < 1e-7 * want, "{v} vs {want}");
let both = crate::fillet(&shelled, &[out_edge, in_edge], 5.0).unwrap();
assert!(both.validity().is_empty(), "{:?}", both.validity());
let want = shelled.volume_at(0.01).unwrap() - section * 104.0 + section * 100.0;
let v = crate::measure(&both).unwrap().volume;
assert!((v - want).abs() < 1e-4 * want, "{v} vs {want}");
let stepped = crate::fillet(&crate::fillet(&shelled, &[in_edge], 5.0).unwrap(), &[out_edge], 5.0).unwrap();
assert!((crate::measure(&stepped).unwrap().volume - v).abs() < 1e-4 * want);
// Both at R7: the arcs, about (25, 35) and (23, 33), cross only outside both quarter arcs,
// and the inner round's material holds the part of the outer round over the hollow (at least
// 9.7 mm from (23, 33)), so the wall stays closed: the outer round takes its whole section
// along 104 and the inner one adds it along 100.
let both = crate::fillet(&shelled, &[out_edge, in_edge], 7.0).unwrap();
assert!(both.validity().is_empty(), "{:?}", both.validity());
let want = v0 - section7 * 4.0;
let v = crate::measure(&both).unwrap().volume;
assert!((v - want).abs() < 1e-7 * want, "{v} vs {want}");
}
/// A shell 3 mm thick bent over like an upside-down U: 60 wide, 20 long, 50 high, its top
/// plate from z = 47 to 50 and its walls from x = 0 to 3 and 57 to 60.
fn bent_shell() -> Body {
let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 20.0, 50.0)).unwrap();
cut(&b, [3.0, -1.0, -1.0], [57.0, 21.0, 47.0])
}
/// The corner left by a round of radius `r` on a 90° edge, per unit length.
fn corner(r: f64) -> f64 {
r * r * (1.0 - std::f64::consts::FRAC_PI_4)
}
/// An outside round concentric with the inside one keeps the wall 3 mm thick: the inside round
/// lies inside the outside one's wedge, but on its ball's side of the arc, which the round
/// leaves as it is. It used to be refused as running into other geometry.
#[test]
fn outside_round_concentric_with_the_inside_round_of_a_wall_fits() {
let s = bent_shell();
let inside = [Vec3::new(3.0, 10.0, 47.0), Vec3::new(57.0, 10.0, 47.0)];
let outside = [Vec3::new(0.0, 10.0, 50.0), Vec3::new(60.0, 10.0, 50.0)];
let a = crate::fillet(&s, &inside, 15.0).unwrap();
let b = crate::fillet(&a, &outside, 18.0).unwrap();
assert!(b.validity().is_empty(), "{:?}", b.validity());
// The inside rounds fill their corners, the outside ones take theirs away.
let want = s.volume_at(0.01).unwrap() + 2.0 * 20.0 * (corner(15.0) - corner(18.0));
let got = b.volume_at(0.01).unwrap();
assert!((got - want).abs() < 1e-3 * want, "{got} for {want}");
// Larger, the outside round's centre moves off the inside one's: it runs into the hollow
// where its arc crosses the inside round's, at r = (18√2 - 15) / (√2 - 1) ≈ 25.24 mm.
let m = too_large(crate::fillet(&a, &outside, 30.0));
let largest: f64 = m.rsplit("that fits is ").next().and_then(|t| t.trim_end_matches(" mm").parse().ok()).unwrap_or(0.0);
let limit = (18.0 * 2f64.sqrt() - 15.0) / (2f64.sqrt() - 1.0);
assert!(largest <= limit && largest > limit - 0.5, "{m}");
}
-46
View File
@@ -1,46 +0,0 @@
//! #324: a round on a block's top edge that runs over a through hole: built as if the top went
//! on, and cut by the hole.
use solidcraft_geom::Vec3;
use crate::{Body, BoolOp, build::box_solid, build::cylinder, ops::boolean};
/// A 40 x 20 x 10 block with a through hole of radius 3 at (20, `y`).
fn block_with_hole(y: f64) -> Body {
let block = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 20.0, 10.0)).unwrap();
let hole = cylinder(Vec3::new(20.0, y, -1.0), Vec3::Z, 3.0, 12.0).unwrap();
boolean(&block, &hole, BoolOp::Cut).unwrap().unwrap()
}
/// The round on the top edge at y = 20 covers the top face from y = 20 - r, and the hole's
/// wall reaches y = 17.5: a radius over 2.5 runs into the hole. R4 is built as if the top went
/// on over the hole and cut from the block (the blend-overflow decision, 237f0ae74): the round
/// takes 16 (1 - π/4) of the section along 40, less its part over the hole, where the round's
/// height above its arc, 4 - √(16 - (y - 16)²), stands over the hole's width
/// 2 √(9 - (y - 14.5)²) for y in [16, 17.5] (integrated with y = 17.5 - s², smooth in s).
#[test]
fn a_round_into_a_hole_is_cut_by_it() {
use std::f64::consts::{FRAC_PI_4, PI};
let b = block_with_hole(14.5);
let edge = Vec3::new(10.0, 20.0, 10.0);
let r = crate::fillet(&b, &[edge], 4.0).unwrap();
assert!(r.validity().is_empty(), "{:?}", r.validity());
let (n, top) = (20000, 1.5f64.sqrt());
let over: f64 = (0..n)
.map(|i| {
let s = (i as f64 + 0.5) * top / n as f64;
let y = 17.5 - s * s;
2.0 * (9.0 - (y - 14.5).powi(2)).sqrt() * (4.0 - (16.0 - (y - 16.0).powi(2)).sqrt()) * 2.0 * s
})
.sum::<f64>()
* top
/ n as f64;
let want = 8000.0 - PI * 9.0 * 10.0 - (40.0 * 16.0 * (1.0 - FRAC_PI_4) - over);
let v = crate::measure(&r).unwrap().volume;
assert!((v - want).abs() < 1e-7 * want, "{v} against {want}");
// Clear of the hole (up to 2.5) the round keeps its whole section.
let r = crate::fillet(&b, &[edge], 2.5).unwrap();
let want = 8000.0 - PI * 9.0 * 10.0 - 40.0 * 2.5 * 2.5 * (1.0 - FRAC_PI_4);
let v = r.volume_at(0.005).unwrap();
assert!((v - want).abs() < 0.05, "{v} against {want}");
}
-66
View File
@@ -56,19 +56,6 @@ fn part_cut_from_a_box() -> Body {
boolean(&slab, &disc, BoolOp::Cut).unwrap().unwrap()
}
/// Area a chamfer of distance `d` takes off the cusp: the triangle between the plane's contact,
/// the tip and the wall's contact, less the wall's circular segment.
fn chamfered_area(d: f64) -> f64 {
let beta = ((R_WALL - d) / (R_WALL + d)).acos();
let o = (TIP_X - (4.0 * R_WALL * d).sqrt(), -d);
let c = (TIP_X, -R_WALL);
let k = R_WALL / (R_WALL + d);
let q2 = (c.0 + (o.0 - c.0) * k, c.1 + (o.1 - c.1) * k);
let (t1, tip) = ((o.0, 0.0), (TIP_X, 0.0));
let triangle = 0.5 * ((tip.0 - t1.0) * (q2.1 - t1.1) - (q2.0 - t1.0) * (tip.1 - t1.1)).abs();
triangle - 0.5 * R_WALL * R_WALL * (beta - beta.sin())
}
#[test]
fn fillet_the_knife_edge() {
for (name, body) in [("plate first", part()), ("corner first", part_other_order()), ("cut from a box", part_cut_from_a_box())] {
@@ -84,21 +71,6 @@ fn fillet_the_knife_edge() {
}
}
#[test]
fn chamfer_the_knife_edge() {
for (name, body) in [("plate first", part()), ("corner first", part_other_order()), ("cut from a box", part_cut_from_a_box())] {
let before = measure(&body).unwrap().volume;
for d in [0.5, 2.0, 5.0] {
let cut = chamfer(&body, &[knife()], d).unwrap_or_else(|e| panic!("{name} d={d}: {e}"));
assert!(cut.validity().is_empty(), "{name} d={d}: {:?}", cut.validity());
assert_eq!(cut.face_count(), body.face_count() + 1, "{name} d={d}: one chamfer face");
let v = measure(&cut).unwrap().volume;
let expected = before - HEIGHT * chamfered_area(d);
assert!((v - expected).abs() < 1e-3 * expected.abs(), "{name} d={d}: volume {v}, expected {expected}");
}
}
}
/// A ball that does not fit between the faces, and sizes at the ends of the range, are refused
/// or blended; they never panic or give an invalid solid.
#[test]
@@ -231,44 +203,6 @@ fn arc_top_edge_sizes_never_panic() {
}
}
/// At the full wall height the fitted contact coincides with the bottom arc. A round there uses
/// the wall up (the blend-overflow decision, 237f0ae74: a round may use up a face), taking the
/// whole corner between the wall and the top; a chamfer of the wall's full height is refused as
/// too large (it would leave the wall a zero-area face, #1113). Just below the limit the wall
/// still has area and both build. Face order and mirrored edge directions do not change either
/// outcome.
#[test]
fn arc_top_blend_uses_up_the_wall_and_refuses_a_collapsed_one() {
for body in [part(), part_other_order(), part_cut_from_a_box()] {
for z in [1.0, -1.0] {
let matrix = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, z, 0.0], [0.0, 0.0, 0.0, 1.0]];
let body = transform_matrix(&body, matrix).unwrap();
let at = arc_top();
let pick = [Vec3::new(at.x, at.y, at.z * z)];
let before = planned_volume(&body);
for round in [true, false] {
let blend = |r| if round { fillet(&body, &pick, r) } else { chamfer(&body, &pick, r) };
if round {
let made = blend(HEIGHT).unwrap();
assert!(made.validity().is_empty(), "mirror={z}: {:?}", made.validity());
assert_eq!(made.face_count(), body.face_count(), "mirror={z}: the round takes the wall's place");
let removed = before - planned_volume(&made);
let expected = arc_top_removed(HEIGHT, true);
assert!((removed - expected).abs() < 0.01 * expected + 0.01, "mirror={z}: removed {removed}, expected {expected}");
} else {
let error = blend(HEIGHT).unwrap_err();
assert!(matches!(error, KernelError::TooLarge(_)), "mirror={z}: {error}");
}
let made = blend(HEIGHT - 0.5).unwrap();
assert!(made.validity().is_empty(), "round={round}, mirror={z}: {:?}", made.validity());
let removed = before - planned_volume(&made);
let expected = arc_top_removed(HEIGHT - 0.5, round);
assert!((removed - expected).abs() < 0.01 * expected + 0.01, "round={round}, mirror={z}: removed {removed}, expected {expected}");
}
}
}
}
fn tf() -> Vec3 {
Vec3::new(20.0, -R_WALL, HEIGHT)
}
+19 -3
View File
@@ -49,12 +49,28 @@ fn overlapping_rounds_are_refused() {
}
}
/// Below half the wall the rounds fit: a closed solid with a round on every edge.
/// Below half the wall the rounds fit: a closed solid with a round on every edge. Each end face's
/// round section at depth u into the round is the end face's outline moved in by
/// d = r − √(r² − (r − u)²), each edge parallel to itself and every corner mitred (two rounds
/// meeting at a corner beside an unpicked sharp edge, convex or concave: the owner's ruling of
/// 2026-10-30): the area less L d (L the outline's and the window's length together,
/// 2 · 41.5 + 2 · 12.3 = 107.6), plus d² at each of the six convex corners (the two strips
/// overlap) and less d² at each of the six concave ones (the two shoulders and the window's four
/// corners: the mitre takes the d × d square beyond both strips). The corner terms cancel, so
/// both ends remove 2 L ∫ d = 2 L r² (1 − π/4).
#[test]
fn rounds_that_fit_are_closed() {
use std::f64::consts::FRAC_PI_4;
let p = part();
let b = crate::fillet(&p, &edges(), 0.5).unwrap();
let r = 0.5;
let b = crate::fillet(&p, &edges(), r).unwrap();
assert!(b.validity().is_empty(), "{:?}", b.validity());
assert_eq!(b.crossed_face_loops().unwrap(), 0);
assert_eq!(b.face_count(), p.face_count() + edges().len());
let (a, top) = (12.74437365538526, 22.69275963366936);
let part_volume = 14.0 * (21.5 * 10.0 + (top - a) * 10.0 - 5.2 * 7.1);
assert!((crate::measure(&p).unwrap().volume - part_volume).abs() < 1e-9 * part_volume);
let length = 2.0 * (21.5 + 20.0) + 2.0 * (5.2 + 7.1);
let removed = 2.0 * length * r * r * (1.0 - FRAC_PI_4);
let v = crate::measure(&b).unwrap().volume;
assert!((v - (part_volume - removed)).abs() < 1e-7 * part_volume, "{v} vs {}", part_volume - removed);
}
+3 -3
View File
@@ -32,6 +32,7 @@ mod continuity_order;
#[cfg(test)]
mod coplanar_tests;
mod corner_g2;
mod curvature_comb;
mod delete_face;
mod distance;
mod draft_corners;
@@ -62,8 +63,6 @@ mod issue_1510_tests;
#[cfg(test)]
mod issue_2005_tests;
#[cfg(test)]
mod issue_324_tests;
#[cfg(test)]
mod issue_616_tests;
#[cfg(test)]
mod issue_674_tests;
@@ -176,6 +175,7 @@ pub use continuity::{
};
pub use continuity_order::{Construction, Continuity};
pub use corner_g2::{CURVATURE_SHARE, DEFAULT_SETBACK_FACTOR};
pub use curvature_comb::{CombTooth, MAX_COMB_TEETH, MIN_COMB_TEETH, comb_edge_near, edge_comb, iso_comb};
pub use delete_face::delete_faces;
pub use distance::{BodyDistance, DistanceShape, body_distance};
pub use draft_corners::{CornerFill, CornerOption, CornerRefusal, CornerReport, DraftCorner, draft_corners};
@@ -207,7 +207,7 @@ pub use point_path::{
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 prism_measure::{PrismSection, certified_prism_equivalent, certified_prism_section};
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).
+31 -24
View File
@@ -263,15 +263,23 @@ fn shell_of_a_stepped_body_joins_its_walls() {
assert_eq!(offsets, b.face_count() - 1, "{h:?}");
}
/// A shell of a painted block: its faces are used as they are (unhealed), keeping the paint's
/// face order, with the history of that copy. Paint is an authored boundary, so the cavity Cut
/// keeps the side faces it sews across the rim's level in pieces (Split).
/// A shell of a painted block: the painted face (face 0) comes through as one face on its own
/// support, so the paint has one face to follow, and each of the five inner walls is an offset of
/// the face it lines, as on the plain block (`shell_lines_the_walls_with_offsets`).
#[test]
fn shell_of_a_painted_body() {
let b = painted_cube();
let r = crate::shell(&b, &[Vec3::new(20.0, 15.0, 20.0)], 2.0).unwrap();
let top = Vec3::new(20.0, 15.0, 20.0);
let r = crate::shell(&b, &[top], 2.0).unwrap();
let h = verified(&r, &b, reach(2.0));
assert_eq!(changes(h), [0, 2, 8, 0, 5], "{h:?}");
assert_eq!(with(h, &[face(0)]).len(), 1, "the painted face is one face: {h:?}");
let top = face_at(&b, top);
for f in (0..6).filter(|f| *f != top) {
let walls = with(h, &[FaceOrigin::Offset { operand: 0, face: f }]);
assert_eq!(walls.len(), 1, "{h:?}");
assert_eq!(h.faces[walls[0]].change, Change::Generated);
}
assert!(with(h, &[FaceOrigin::Offset { operand: 0, face: top }]).is_empty());
}
#[test]
@@ -370,10 +378,22 @@ fn surfaces_keep_their_faces() {
let h = checked(&lid, &[&open], reach(0.0), &|_| true);
assert_eq!(h.faces[0].change, Change::Generated);
assert!(h.edges.iter().all(|e| matches!(e.origins.as_slice(), [EdgeOrigin::Edge { operand: 0, .. }])));
// Stitched: each face the one it was sewn from, the seam the edges sewn together.
// Stitched: each face the one it was sewn from (its geometry checked against it), the five
// walls each one of the open box's and the lid the patch, and the seam the edges sewn
// together.
let closed = crate::stitch(&[&open, &lid], 0.0).unwrap();
let h = checked(&closed, &[&open, &lid], reach(0.0), &|_| false);
assert!(h.faces.iter().all(|f| f.change == Change::Kept && f.origins.len() == 1));
let mut sewn: Vec<FaceOrigin> = h
.faces
.iter()
.map(|f| match f.origins[..] {
[o] => o,
_ => panic!("a stitched face from one face: {f:?}"),
})
.collect();
sewn.sort();
let want = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0)].map(|(operand, face)| FaceOrigin::Face { operand, face });
assert_eq!(sewn, want, "{h:?}");
assert_eq!(h.edges.iter().filter(|e| e.origins.len() == 2).count(), 4);
let patch = crate::patch_region(&Plane::XY, &Region2 { outer: square(0.0, 0.0, 10.0, 10.0), holes: vec![] }).unwrap();
assert_eq!(patch.history().unwrap().operands, 0);
@@ -432,29 +452,16 @@ fn box_cuts_of(b: &Body) -> Vec<(&'static str, Body, Body)> {
.collect()
}
/// Meetings with a side of several origins (a face the modifier's heal merged).
fn merged_meetings(h: &History) -> usize {
h.edges.iter().flat_map(|e| &e.origins).filter(|o| matches!(o, EdgeOrigin::Meet { a, b } if a.single().is_none() || b.single().is_none())).count()
}
/// A fillet right after a box cut. The cut joins the walls it sews in pieces across its slabs
/// on their common supports, so the fillet finds whole faces. Where the block is painted the cut
/// keeps those pieces (it has more faces), the fillet's heal merges them, and the edges where
/// the round runs into such a face meet all of it. Composed with the cut, over the block and
/// the tool.
/// A fillet right after a box cut, on the plain and the painted block: the round stands in place
/// of the picked edge, and composed with the cut its history holds over the block and the tool.
#[test]
fn fillet_after_box_cuts() {
let at = Vec3::new(5.0, 0.0, 20.0);
let plain = box_cuts_of(&cube());
for (b, painted) in [(cube(), false), (painted_cube(), true)] {
let cuts = if painted { box_cuts_of(&b) } else { plain.clone() };
for ((name, cut, tool), (_, whole, _)) in cuts.into_iter().zip(&plain) {
for (name, cut, tool) in box_cuts_of(&b) {
let r = crate::fillet(&cut, &[at], 2.0).unwrap();
let h = verified(&r, &cut, reach(2.0 * 1.5));
assert_eq!(blends(h), [vec![edge(edge_at(&cut, at))]], "{name}");
let pieces = cut.face_count() > whole.face_count();
assert_eq!(pieces, painted && name != "notch" && name != "hole", "{name} (painted: {painted})");
assert_eq!(merged_meetings(h) > 0, pieces, "{name} (painted: {painted}): {h:?}");
assert_eq!(blends(h), [vec![edge(edge_at(&cut, at))]], "{name} (painted: {painted})");
let mut through = h.clone();
through.substitute(0, cut.history().unwrap()).unwrap();
through.check(&r, &[&b, &tool]).unwrap();
+60 -6
View File
@@ -68,13 +68,8 @@ pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {
let saved = SavedBody { solid: body.record().clone(), metadata: metadata::encode(body)?, runtime };
// Structural validation does not invoke another geometric reconstruction.
validate_topology(&saved)?;
let value = serde_json::to_value(saved).map_err(invalid)?;
validate_value(&value, 0)?;
if value_nodes(&value) > MAX_VALUES {
return Err(invalid("value budget"));
}
let mut out = MAGIC.to_vec();
binary::write(&value, &mut out, 0)?;
binary::write_serialized(&saved, &mut out)?;
Ok(out)
})
}
@@ -275,6 +270,8 @@ fn validate_value(v: &Value, depth: usize) -> Result<()> {
Ok(())
}
/// How many values `v` is (a collection and each of its items): [`MAX_VALUES`] at most.
#[cfg(test)]
fn value_nodes(v: &Value) -> usize {
match v {
Value::Array(a) => a.iter().fold(1usize, |n, v| n.saturating_add(value_nodes(v))),
@@ -338,6 +335,63 @@ mod tests {
}
}
/// The encoding as it was made before the encoder wrote as it serialized: the whole record as
/// a JSON value, checked, then written.
fn encoded_through_a_value(body: &Body) -> Result<Vec<u8>> {
let runtime = Runtime { size: body.size, coarse_missing: None };
let saved = SavedBody { solid: body.record().clone(), metadata: metadata::encode(body)?, runtime };
validate_topology(&saved)?;
let value = serde_json::to_value(saved).map_err(invalid)?;
validate_value(&value, 0)?;
if value_nodes(&value) > MAX_VALUES {
return Err(invalid("value budget"));
}
let mut out = MAGIC.to_vec();
binary::write(&value, &mut out, 0)?;
Ok(out)
}
/// Written as it serializes, a body's encoding is the bytes its JSON value gave, byte for
/// byte: plain, blended, cut (history), extruded (face sources), coloured, painted, split
/// along lines, round (spline forms), open, and placed far off.
#[test]
fn the_encoding_is_the_bytes_of_the_record_as_a_json_value() {
use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap();
let rounded = crate::fillet(&cube, &[Vec3::new(20., 0., 10.)], 2.).unwrap();
let bore = crate::cylinder(Vec3::new(10., 10., -1.), Vec3::Z, 3., 12.).unwrap();
let cut = crate::boolean(&rounded, &bore, crate::BoolOp::Cut).unwrap().unwrap();
let region = Region2 {
outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]),
holes: vec![Loop2::circle(Vec2::new(10., 10.), 4.)],
};
let extruded = crate::extrude(&Plane::XY, &[region], 0., 5.).unwrap().remove(0);
assert!(extruded.face_sources().is_some_and(|s| s.iter().any(Option::is_some)), "an extrusion carries its face sources");
assert!(cut.history().is_some(), "a cut carries its history");
let paint = crate::Paint { opacity: 0.5, faces: vec![crate::FacePaint { face: 1, color: [0.9, 0.1, 0.2], opacity: 0.75 }] };
let painted = cube.clone().with_color(Some([0.1, 0.5, 0.9])).with_paint(Some(paint));
let top = (0..cube.face_count()).find(|f| cube.planar_face(*f).is_some_and(|p| p.normal().z > 0.5 && p.origin.z > 9.)).unwrap();
let split =
crate::split_faces(&cube, &[top], &crate::SplitTool::Plane(Plane::from_normal(Vec3::new(20., 0., 0.), Vec3::X).unwrap())).unwrap();
let surface = crate::copy_faces(&cube, &[Vec3::new(20., 15., 10.)]).unwrap();
let far = crate::transform(&cut, Vec3::new(1.0e6, -2.5e5, 3.0e4), Vec3::ZERO, Vec3::Z, 0.7).unwrap();
let bodies = [
cube,
rounded,
cut,
extruded,
painted,
split,
surface,
crate::sphere(Vec3::ZERO, 12.).unwrap(),
crate::torus(Vec3::ZERO, 20., 4.).unwrap(),
far,
];
for (i, body) in bodies.iter().enumerate() {
assert_eq!(encode_native_body(body).unwrap(), encoded_through_a_value(body).unwrap(), "body {i}");
}
}
#[test]
fn box_and_fillet_have_stable_wire_records() {
let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap();
+519
View File
@@ -61,15 +61,20 @@ pub(super) fn read(input: &mut &[u8], depth: usize, budget: &mut usize) -> Resul
_ => return Err(invalid("unknown binary tag")),
})
}
#[cfg(test)]
fn count(n: usize, out: &mut Vec<u8>) -> Result<()> {
out.extend_from_slice(&u32::try_from(n).map_err(invalid)?.to_le_bytes());
Ok(())
}
#[cfg(test)]
fn text(s: &str, out: &mut Vec<u8>) -> Result<()> {
count(s.len(), out)?;
out.extend_from_slice(s.as_bytes());
Ok(())
}
/// `value` appended to `out`. The encoder writes a body as it serializes
/// ([`write_serialized`]); this writes a value already built, as tests build hostile ones.
#[cfg(test)]
pub(super) fn write(value: &Value, out: &mut Vec<u8>, depth: usize) -> Result<()> {
if depth > 48 || out.len() > MAX_BYTES {
return Err(invalid("encoding budget"));
@@ -114,3 +119,517 @@ pub(super) fn write(value: &Value, out: &mut Vec<u8>, depth: usize) -> Result<()
}
Ok(())
}
/// Why a value could not be written (a serde error carries only its message).
#[derive(Debug)]
pub(super) struct WriteError(String);
impl std::fmt::Display for WriteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for WriteError {}
impl serde::ser::Error for WriteError {
fn custom<T: std::fmt::Display>(msg: T) -> Self {
WriteError(msg.to_string())
}
}
fn refuse(what: &str) -> WriteError {
WriteError(what.into())
}
type Written<T = ()> = std::result::Result<T, WriteError>;
/// `value` appended to `out` as the tagged binary value it is as JSON: the bytes [`write`] gives
/// for `serde_json::to_value(value)`, refused where that, the checks on its result
/// (`validate_value`, the [`MAX_VALUES`] budget) or [`write`] refuse. Written as it is
/// serialized, with no JSON value in between: a body's record is millions of values, and building
/// them all first was most of the cost of encoding it.
///
/// As JSON: a struct or a map is an object of its entries in key order (a JSON object's), its
/// keys strings (a map's keys may be strings, characters, booleans or integers, written as JSON
/// writes such keys); an enum variant without data its name, one with data an object of its name
/// and the data; an option its value or null; bytes an array of numbers. A number is an integer
/// (unsigned from 0 up, signed below) or a finite float; a float that is not finite is null.
///
/// Refused: nesting past 48, a string over 1 MiB, an array of more than [`MAX_ITEMS`], a float
/// over 1e12 in size, more than [`MAX_VALUES`] values, more than [`MAX_BYTES`] in `out`.
pub(super) fn write_serialized<T: serde::Serialize + ?Sized>(value: &T, out: &mut Vec<u8>) -> Result<()> {
let mut w = Writer { out, values: 0 };
value.serialize(Ser { w: &mut w, depth: 0 }).map_err(invalid)
}
struct Writer<'a> {
out: &'a mut Vec<u8>,
values: usize,
}
impl Writer<'_> {
/// Count a value at `depth` and write its tag.
fn start(&mut self, depth: usize, tag: u8) -> Written {
if depth > 48 {
return Err(refuse("nesting"));
}
self.values = self.values.saturating_add(1);
if self.values > MAX_VALUES {
return Err(refuse("value budget"));
}
self.out.push(tag);
self.fits()
}
fn fits(&self) -> Written {
if self.out.len() > MAX_BYTES { Err(refuse("encoding size")) } else { Ok(()) }
}
fn number(&mut self, depth: usize, tag: u8, bits: [u8; 8]) -> Written {
self.start(depth, tag)?;
self.out.extend_from_slice(&bits);
self.fits()
}
fn unsigned(&mut self, depth: usize, v: u64) -> Written {
self.number(depth, 4, v.to_le_bytes())
}
fn signed(&mut self, depth: usize, v: i64) -> Written {
match u64::try_from(v) {
Ok(u) => self.unsigned(depth, u),
Err(_) => self.number(depth, 3, v.to_le_bytes()),
}
}
fn float(&mut self, depth: usize, v: f64) -> Written {
if !v.is_finite() {
return self.start(depth, 0);
}
if v.abs() > 1e12 {
return Err(refuse("non-finite metadata"));
}
self.number(depth, 5, v.to_le_bytes())
}
fn length(&mut self, n: usize) -> Written {
self.out.extend_from_slice(&u32::try_from(n).map_err(|_| refuse("length"))?.to_le_bytes());
self.fits()
}
fn text(&mut self, s: &str) -> Written {
self.length(s.len())?;
self.out.extend_from_slice(s.as_bytes());
self.fits()
}
fn string(&mut self, depth: usize, s: &str) -> Written {
if s.len() > 1 << 20 {
return Err(refuse("string budget"));
}
self.start(depth, 6)?;
self.text(s)
}
/// Open a collection at `depth`: its tag and room for its count, which goes at the place
/// returned.
fn open(&mut self, depth: usize, tag: u8) -> Written<usize> {
self.start(depth, tag)?;
let at = self.out.len();
self.out.extend_from_slice(&[0; 4]);
self.fits()?;
Ok(at)
}
fn count_at(&mut self, at: usize, n: usize) -> Written {
let n = u32::try_from(n).map_err(|_| refuse("length"))?.to_le_bytes();
self.out.get_mut(at..at + 4).ok_or_else(|| refuse("count"))?.copy_from_slice(&n);
Ok(())
}
}
/// A value to write at a depth.
pub(super) struct Ser<'w, 'a> {
w: &'w mut Writer<'a>,
depth: usize,
}
impl<'w, 'a> Ser<'w, 'a> {
/// An object of one entry, named `variant`, whose value comes next (at the depth returned).
fn variant(self, variant: &str) -> Written<Ser<'w, 'a>> {
let at = self.w.open(self.depth, 8)?;
self.w.count_at(at, 1)?;
self.w.text(variant)?;
Ok(Ser { w: self.w, depth: self.depth + 1 })
}
fn array(self) -> Written<Array<'w, 'a>> {
let at = self.w.open(self.depth, 7)?;
Ok(Array { w: self.w, depth: self.depth, at, items: 0 })
}
fn object(self) -> Written<Object<'w, 'a>> {
let at = self.w.open(self.depth, 8)?;
Ok(Object { w: self.w, depth: self.depth, at, entries: Vec::new(), key: None })
}
}
/// An array being written: where its count goes, and how many items it has.
pub(super) struct Array<'w, 'a> {
w: &'w mut Writer<'a>,
depth: usize,
at: usize,
items: usize,
}
impl Array<'_, '_> {
fn item<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
self.items += 1;
if self.items > MAX_ITEMS {
return Err(refuse("array budget"));
}
value.serialize(Ser { w: self.w, depth: self.depth + 1 })
}
fn close(self) -> Written {
self.w.count_at(self.at, self.items)
}
}
/// An object being written: where its count goes, and each entry's key and where it ends. The
/// entries are written as they come and put in key order when it closes.
pub(super) struct Object<'w, 'a> {
w: &'w mut Writer<'a>,
depth: usize,
at: usize,
entries: Vec<(String, usize)>,
/// The key of the entry whose value comes next.
key: Option<String>,
}
impl Object<'_, '_> {
fn key(&mut self, key: String) -> Written {
self.w.text(&key)?;
self.key = Some(key);
Ok(())
}
fn value<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
let key = self.key.take().ok_or_else(|| refuse("an object's value without its key"))?;
value.serialize(Ser { w: self.w, depth: self.depth + 1 })?;
self.entries.push((key, self.w.out.len()));
Ok(())
}
fn entry<T: serde::Serialize + ?Sized>(&mut self, key: &str, value: &T) -> Written {
self.key(key.to_owned())?;
self.value(value)
}
fn close(self) -> Written {
let Object { w, at, entries, .. } = self;
let first = at + 4;
if !entries.windows(2).all(|p| p[0].0 < p[1].0) {
// In key order, as a JSON object (a map by key) holds them. A key twice would keep
// only its last value there; no record repeats one.
let mut spans: Vec<(&str, usize, usize)> = Vec::with_capacity(entries.len());
let mut start = first;
for (key, end) in &entries {
spans.push((key.as_str(), start, *end));
start = *end;
}
spans.sort_by(|a, b| a.0.cmp(b.0));
if spans.windows(2).any(|p| p[0].0 == p[1].0) {
return Err(refuse("duplicate key"));
}
let written = w.out.split_off(first);
for (_, start, end) in spans {
w.out.extend_from_slice(written.get(start - first..end - first).ok_or_else(|| refuse("object"))?);
}
}
w.count_at(at, entries.len())
}
}
/// A map key as JSON writes it: a string.
struct Key;
impl serde::Serializer for Key {
type Ok = String;
type Error = WriteError;
type SerializeSeq = serde::ser::Impossible<String, WriteError>;
type SerializeTuple = serde::ser::Impossible<String, WriteError>;
type SerializeTupleStruct = serde::ser::Impossible<String, WriteError>;
type SerializeTupleVariant = serde::ser::Impossible<String, WriteError>;
type SerializeMap = serde::ser::Impossible<String, WriteError>;
type SerializeStruct = serde::ser::Impossible<String, WriteError>;
type SerializeStructVariant = serde::ser::Impossible<String, WriteError>;
fn serialize_bool(self, v: bool) -> Written<String> {
Ok(v.to_string())
}
fn serialize_i8(self, v: i8) -> Written<String> {
Ok(v.to_string())
}
fn serialize_i16(self, v: i16) -> Written<String> {
Ok(v.to_string())
}
fn serialize_i32(self, v: i32) -> Written<String> {
Ok(v.to_string())
}
fn serialize_i64(self, v: i64) -> Written<String> {
Ok(v.to_string())
}
fn serialize_i128(self, v: i128) -> Written<String> {
Ok(v.to_string())
}
fn serialize_u8(self, v: u8) -> Written<String> {
Ok(v.to_string())
}
fn serialize_u16(self, v: u16) -> Written<String> {
Ok(v.to_string())
}
fn serialize_u32(self, v: u32) -> Written<String> {
Ok(v.to_string())
}
fn serialize_u64(self, v: u64) -> Written<String> {
Ok(v.to_string())
}
fn serialize_u128(self, v: u128) -> Written<String> {
Ok(v.to_string())
}
fn serialize_f32(self, _: f32) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_f64(self, _: f64) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_char(self, v: char) -> Written<String> {
Ok(v.to_string())
}
fn serialize_str(self, v: &str) -> Written<String> {
Ok(v.to_owned())
}
fn serialize_bytes(self, _: &[u8]) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_none(self) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_some<T: serde::Serialize + ?Sized>(self, _: &T) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_unit(self) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_unit_struct(self, _: &'static str) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_unit_variant(self, _: &'static str, _: u32, variant: &'static str) -> Written<String> {
Ok(variant.to_owned())
}
fn serialize_newtype_struct<T: serde::Serialize + ?Sized>(self, _: &'static str, value: &T) -> Written<String> {
value.serialize(self)
}
fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(self, _: &'static str, _: u32, _: &'static str, _: &T) -> Written<String> {
Err(refuse("a map key must be a string"))
}
fn serialize_seq(self, _: Option<usize>) -> Written<Self::SerializeSeq> {
Err(refuse("a map key must be a string"))
}
fn serialize_tuple(self, _: usize) -> Written<Self::SerializeTuple> {
Err(refuse("a map key must be a string"))
}
fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Written<Self::SerializeTupleStruct> {
Err(refuse("a map key must be a string"))
}
fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Written<Self::SerializeTupleVariant> {
Err(refuse("a map key must be a string"))
}
fn serialize_map(self, _: Option<usize>) -> Written<Self::SerializeMap> {
Err(refuse("a map key must be a string"))
}
fn serialize_struct(self, _: &'static str, _: usize) -> Written<Self::SerializeStruct> {
Err(refuse("a map key must be a string"))
}
fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Written<Self::SerializeStructVariant> {
Err(refuse("a map key must be a string"))
}
}
impl<'w, 'a> serde::Serializer for Ser<'w, 'a> {
type Ok = ();
type Error = WriteError;
type SerializeSeq = Array<'w, 'a>;
type SerializeTuple = Array<'w, 'a>;
type SerializeTupleStruct = Array<'w, 'a>;
type SerializeTupleVariant = Array<'w, 'a>;
type SerializeMap = Object<'w, 'a>;
type SerializeStruct = Object<'w, 'a>;
type SerializeStructVariant = Object<'w, 'a>;
fn serialize_bool(self, v: bool) -> Written {
self.w.start(self.depth, if v { 2 } else { 1 })
}
fn serialize_i8(self, v: i8) -> Written {
self.w.signed(self.depth, v.into())
}
fn serialize_i16(self, v: i16) -> Written {
self.w.signed(self.depth, v.into())
}
fn serialize_i32(self, v: i32) -> Written {
self.w.signed(self.depth, v.into())
}
fn serialize_i64(self, v: i64) -> Written {
self.w.signed(self.depth, v)
}
fn serialize_i128(self, v: i128) -> Written {
match (u64::try_from(v), i64::try_from(v)) {
(Ok(u), _) => self.w.unsigned(self.depth, u),
(_, Ok(i)) => self.w.signed(self.depth, i),
_ => Err(refuse("number out of range")),
}
}
fn serialize_u8(self, v: u8) -> Written {
self.w.unsigned(self.depth, v.into())
}
fn serialize_u16(self, v: u16) -> Written {
self.w.unsigned(self.depth, v.into())
}
fn serialize_u32(self, v: u32) -> Written {
self.w.unsigned(self.depth, v.into())
}
fn serialize_u64(self, v: u64) -> Written {
self.w.unsigned(self.depth, v)
}
fn serialize_u128(self, v: u128) -> Written {
self.w.unsigned(self.depth, u64::try_from(v).map_err(|_| refuse("number out of range"))?)
}
fn serialize_f32(self, v: f32) -> Written {
self.w.float(self.depth, v.into())
}
fn serialize_f64(self, v: f64) -> Written {
self.w.float(self.depth, v)
}
fn serialize_char(self, v: char) -> Written {
self.w.string(self.depth, v.encode_utf8(&mut [0; 4]))
}
fn serialize_str(self, v: &str) -> Written {
self.w.string(self.depth, v)
}
fn serialize_bytes(self, v: &[u8]) -> Written {
let mut a = self.array()?;
for b in v {
a.item(b)?;
}
a.close()
}
fn serialize_none(self) -> Written {
self.w.start(self.depth, 0)
}
fn serialize_some<T: serde::Serialize + ?Sized>(self, value: &T) -> Written {
value.serialize(self)
}
fn serialize_unit(self) -> Written {
self.w.start(self.depth, 0)
}
fn serialize_unit_struct(self, _: &'static str) -> Written {
self.w.start(self.depth, 0)
}
fn serialize_unit_variant(self, _: &'static str, _: u32, variant: &'static str) -> Written {
self.w.string(self.depth, variant)
}
fn serialize_newtype_struct<T: serde::Serialize + ?Sized>(self, _: &'static str, value: &T) -> Written {
value.serialize(self)
}
fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(self, _: &'static str, _: u32, variant: &'static str, value: &T) -> Written {
value.serialize(self.variant(variant)?)
}
fn serialize_seq(self, _: Option<usize>) -> Written<Array<'w, 'a>> {
self.array()
}
fn serialize_tuple(self, _: usize) -> Written<Array<'w, 'a>> {
self.array()
}
fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Written<Array<'w, 'a>> {
self.array()
}
fn serialize_tuple_variant(self, _: &'static str, _: u32, variant: &'static str, _: usize) -> Written<Array<'w, 'a>> {
self.variant(variant)?.array()
}
fn serialize_map(self, _: Option<usize>) -> Written<Object<'w, 'a>> {
self.object()
}
fn serialize_struct(self, _: &'static str, _: usize) -> Written<Object<'w, 'a>> {
self.object()
}
fn serialize_struct_variant(self, _: &'static str, _: u32, variant: &'static str, _: usize) -> Written<Object<'w, 'a>> {
self.variant(variant)?.object()
}
}
impl serde::ser::SerializeSeq for Array<'_, '_> {
type Ok = ();
type Error = WriteError;
fn serialize_element<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
self.item(value)
}
fn end(self) -> Written {
self.close()
}
}
impl serde::ser::SerializeTuple for Array<'_, '_> {
type Ok = ();
type Error = WriteError;
fn serialize_element<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
self.item(value)
}
fn end(self) -> Written {
self.close()
}
}
impl serde::ser::SerializeTupleStruct for Array<'_, '_> {
type Ok = ();
type Error = WriteError;
fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
self.item(value)
}
fn end(self) -> Written {
self.close()
}
}
impl serde::ser::SerializeTupleVariant for Array<'_, '_> {
type Ok = ();
type Error = WriteError;
fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
self.item(value)
}
fn end(self) -> Written {
self.close()
}
}
impl serde::ser::SerializeMap for Object<'_, '_> {
type Ok = ();
type Error = WriteError;
fn serialize_key<T: serde::Serialize + ?Sized>(&mut self, key: &T) -> Written {
let key = key.serialize(Key)?;
self.key(key)
}
fn serialize_value<T: serde::Serialize + ?Sized>(&mut self, value: &T) -> Written {
self.value(value)
}
fn end(self) -> Written {
self.close()
}
}
impl serde::ser::SerializeStruct for Object<'_, '_> {
type Ok = ();
type Error = WriteError;
fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Written {
self.entry(key, value)
}
fn end(self) -> Written {
self.close()
}
}
impl serde::ser::SerializeStructVariant for Object<'_, '_> {
type Ok = ();
type Error = WriteError;
fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Written {
self.entry(key, value)
}
fn end(self) -> Written {
self.close()
}
}
+6 -36
View File
@@ -616,36 +616,7 @@ mod tests {
assert!((moved.face_plane(floor).unwrap().origin.z - (300. + thickness)).abs() < 1e-9);
assert!(matches!(moved.face_sources().unwrap().get(right), Some(Some(FaceSource::ShellPlanar { producer: Some(9), inner: false, .. }))));
assert!(moved.face_plane(right).unwrap().normal().dot(Vec3::Y) > 0.999999);
let raw = cup.mesh(&crate::MeshTolerance::chord(0.01)).unwrap();
let display = cup.mesh(&crate::MeshTolerance::chord(0.01)).unwrap();
let cylindrical: Vec<_> = (0..cup.face_count())
.filter_map(|i| {
let crate::FaceSurface::Cylinder { radius, .. } = crate::face_surface(&cup, i)? else { return None };
let z: Vec<f64> = face_points(&cup, i).iter().map(|p| p.z).collect();
let lo = z.iter().copied().fold(f64::INFINITY, f64::min);
let hi = z.iter().copied().fold(f64::NEG_INFINITY, f64::max);
Some((i, radius, lo, hi))
})
.collect();
eprintln!("roundedShell width{width} thickness{thickness} raw{} cylindrical roles{cylindrical:?}", cup.face_count());
let mut corner_joins = 0;
for (edge, adjacent) in raw.edge_faces.iter().enumerate() {
let [a, b] = adjacent.as_slice() else { continue };
if raw.edges[edge].iter().all(|p| (p.z - thickness).abs() < 1e-8)
&& cylindrical.iter().any(|(i, r, _, _)| *i == *a as usize && (*r - 6.).abs() < 1e-6)
&& cylindrical.iter().any(|(i, r, _, _)| *i == *b as usize && (*r - 6.).abs() < 1e-6)
{
corner_joins += 1;
assert!(display.seams[edge], "existing cylindrical corner joins must not draw a floor-height arc");
}
}
assert_eq!(corner_joins, 0, "no physical lower corner strip remains");
assert_eq!(cup.face_count(), 19);
let outer: Vec<_> = cylindrical.iter().filter(|(_, r, _, _)| (*r - 6.).abs() < 1e-6).collect();
assert_eq!(outer.len(), 4);
assert!(outer.iter().all(|(i, _, _, _)| cup.face_was_coalesced(*i) && moved.face_was_coalesced(*i)));
assert!(outer.iter().all(|(_, _, lo, hi)| lo.abs() < 1e-9 && (*hi - 30.).abs() < 1e-9));
for axis in 0..2 {
for high in [false, true] {
let matching: Vec<_> = sources.iter().enumerate().filter_map(|(i,s)| matches!(s,Some(FaceSource::ShellPlanar {inner:false,source,..}) if matches!(source.as_ref(),FaceSource::Box {axis:a,high:h,..} if *a==axis && *h==high)).then_some(i)).collect();
@@ -658,18 +629,17 @@ mod tests {
assert!(display.contains(Vec3::new(width / 2. - thickness / 2., 0., thickness / 2.)));
assert!(display.contains(Vec3::new(width / 2. - thickness / 2., 0., 15.)));
assert!(!display.contains(Vec3::new(0., 0., 15.)));
// Different meshers (the display plan and the reference), both within 0.01 mm.
let (rv, dv) = (raw.measure().volume, display.measure().volume);
assert!((rv - dv).abs() <= raw.measure().area * 0.01, "display volume {dv} vs {rv}");
// The rounded box less its inside, the box moved in by the wall with its corners'
// rounds at 6 − t, open at the top: exact (SMLib's volume, to 1e-8; the rounds
// are its surfaces).
let expected = (width * 60. - (4. - std::f64::consts::PI) * 36.) * 30.
- ((width - 2. * thickness) * (60. - 2. * thickness) - (4. - std::f64::consts::PI) * (6. - thickness).powi(2)) * (30. - thickness);
assert!((cup.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume - expected).abs() < 0.2);
let v = crate::measure(&cup).unwrap().volume;
assert!((v - expected).abs() < 1e-6 * expected, "{v} vs {expected}");
let imported = crate::step_import(&crate::step_export(&[&cup], "regularized rounded shell").unwrap()).unwrap();
assert!(imported.warnings.is_empty());
let copy = &imported.bodies[0].body;
assert_eq!(copy.face_count(), 19);
// STEP may additionally coalesce cylindrical corner patches. The
// certified planar wall topology itself must survive unchanged.
// The certified planar walls come back from STEP as one full-height face each.
for (axis, coordinate) in [(Vec3::X, width / 2.), (-Vec3::X, width / 2.), (Vec3::Y, 30.), (-Vec3::Y, 30.)] {
let walls: Vec<usize> = actual_planes(copy)
.unwrap()
+73
View File
@@ -637,6 +637,54 @@ pub fn certified_prism_equivalent(a: &crate::Body, b: &crate::Body) -> crate::Re
})
}
/// A uniform prism along a plane's normal, read off a body's record: its levels above the plane
/// and its section in the plane's coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct PrismSection {
/// The levels of its bottom and its top cap above the plane (`lo < hi`).
pub lo: f64,
pub hi: f64,
/// Its section, exact: lines and arcs, the outer loop counter-clockwise, the holes clockwise.
pub region: solidcraft_geom::Region2,
/// How far the levels may be off the body's caps (the caps' vertices lie within it of them).
pub tolerance: f64,
}
/// The uniform prism `body` is along `plane`'s normal, when its record proves it one: two caps
/// square to the normal, every other face a wall running straight between them along the
/// normal and standing on both caps' edges, the two caps one section (see [`certified_prism_equivalent`]
/// for the profiles it proves: a convex straight outline or a circle, with separate round
/// holes). The body's current geometry, not how it was made: a tool trimmed by a boolean that
/// left it a prism is one. `None` when that is not proved.
pub fn certified_prism_section(body: &crate::Body, plane: &Plane) -> crate::Result<Option<PrismSection>> {
crate::guard("certified prism section", || {
if body.is_mesh() || !body.size().is_finite() {
return Ok(None);
}
let record = crate::native::brep_record(body)?;
let tol = body.size().max(1.) * 1e-10;
let Some(c) = certificate(&record, body.size(), plane, tol) else { return Ok(None) };
let mut outer = None;
let mut holes = Vec::new();
for lp in c.loops {
let positive = lp.area.lo > 0.;
let lp = solidcraft_geom::Loop2 { segs: lp.segments.into_vec() };
if positive {
if outer.replace(lp).is_some() {
return Ok(None);
}
} else {
holes.push(lp);
}
}
let Some(outer) = outer else { return Ok(None) };
// The caps' vertices are within twice the tolerance of their levels (`certificate`), and
// the levels are worked out from the plane's origin.
let tolerance = 2. * tol + 128. * f64::EPSILON * (plane.origin.len() + c.lo.abs() + c.hi.abs()).max(1.);
Ok(Some(PrismSection { lo: c.lo, hi: c.hi, region: solidcraft_geom::Region2 { outer, holes }, tolerance }))
})
}
/// [`certified_prism_equivalent`] of the records `a` and `b` of bodies of sizes `size_a` and
/// `size_b`.
fn equivalent(a: &Brep, size_a: f64, b: &Brep, size_b: f64) -> Option<bool> {
@@ -823,6 +871,31 @@ mod tests {
r.faces.iter().position(|f| plane_of(&f.surface).is_none()).unwrap()
}
/// A 10 x 10 tool from z = 0 cut by a pin of radius 2 standing through it, joined to a plate
/// at z 1 ... 2 (a To Object tool trimmed by its curved target): the lump under the plate is
/// a prism from 0 to 1 whose section is the square less the pin's circle, 100 - 4π; the lump
/// above it steps (the pin stands up through it) and is no prism.
#[test]
fn a_trimmed_tool_reads_as_the_prism_of_its_current_section() {
use solidcraft_geom::{Loop2, Region2};
let pin = crate::cylinder(Vec3::new(25., 25., 0.), Vec3::Z, 2., 20.).unwrap();
let stop = crate::box_solid(Vec3::new(19., 19., 1.), Vec3::new(31., 31., 2.)).unwrap();
let roof = crate::boolean(&pin, &stop, crate::BoolOp::Union).unwrap().unwrap();
let square =
Region2 { outer: Loop2::polygon(&[Vec2::new(20., 20.), Vec2::new(30., 20.), Vec2::new(30., 30.), Vec2::new(20., 30.)]), holes: vec![] };
let tool = crate::extrude(&Plane::XY, &[square], 0., 25.).unwrap().remove(0);
let lumps = crate::boolean(&tool, &roof, crate::BoolOp::Cut).unwrap().unwrap().lumps().unwrap();
assert_eq!(lumps.len(), 2);
let sections: Vec<Option<PrismSection>> = lumps.iter().map(|l| certified_prism_section(l, &Plane::XY).unwrap()).collect();
let lower = sections.iter().flatten().collect::<Vec<_>>();
assert_eq!(lower.len(), 1, "only the lump under the plate is a prism");
let lower = lower[0];
assert!(lower.lo.abs() <= lower.tolerance && (lower.hi - 1.).abs() <= lower.tolerance, "{} … {}", lower.lo, lower.hi);
assert_eq!(lower.region.holes.len(), 1);
assert!(lower.region.outer.signed_area() > 0. && lower.region.holes[0].signed_area() < 0.);
assert!((lower.region.area() - (100. - 4. * std::f64::consts::PI)).abs() < 1e-8, "{}", lower.region.area());
}
#[test]
fn actual_drilled_prism_and_step_reopen_are_certified_without_history() {
let source = drilled(6., 0.);
+10 -20
View File
@@ -1127,7 +1127,8 @@ fn surface_of_revolution_sense_follows_iso() {
/// A tube revolved about a line it touches (a horn torus, as a tight sweep makes) is written as
/// one rational B-spline face whose loop passes the pole twice, with no zero-length edge there:
/// no TOROIDAL_SURFACE (it would be degenerate) and no surface of revolution.
/// no TOROIDAL_SURFACE (it would be degenerate) and no surface of revolution. (Its volume, built
/// and read back, is the rig's import/cov-step-horn-torus-quarter-round-trip.)
#[test]
fn horn_torus_written_as_one_spline_face() {
let prof = Region2 { outer: Loop2::circle(Vec2::new(5.0, 0.0), 5.0), holes: vec![] };
@@ -1135,9 +1136,6 @@ fn horn_torus_written_as_one_spline_face() {
let text = step_export(&[&b], "t").unwrap();
assert!(!text.contains("TOROIDAL_SURFACE") && !text.contains("SURFACE_OF_REVOLUTION"));
assert_eq!(text.matches("ADVANCED_FACE(").count(), 3, "{text}");
let imp = round_trip(&b);
let v = std::f64::consts::PI * 25.0 * std::f64::consts::TAU * 5.0 / 4.0;
assert!(rel(measure(&imp.bodies[0].body).unwrap().volume, v) < 1e-3);
}
/// How a torus-capped cylinder ([`torus_capped_cylinder`]) ends.
@@ -1388,10 +1386,10 @@ fn glued_halves_export_as_whole_faces() {
assert_eq!(imp.bodies[0].file_faces, 8);
}
/// A slot plate with a round on its top outline (issue #612): the extruded arc ends and the
/// rounds along the straight edges are lone B-spline sheets, written as cylinders bounded by
/// their faces. The rounds' sheets reach far past their edges, and a reader bounding the part by
/// its surfaces saw a 60 mm part as 130 mm long.
/// A slot plate with a round on its top outline (issue #612): every surface the file writes is
/// bounded by its face, whatever kind it is written as. The rounds' sheets once reached far past
/// their edges, and a reader bounding the part by its surfaces saw a 60 mm part as 130 mm long.
/// Read back, the part has its exact volume.
#[test]
fn rounded_slot_exports_cylinders() {
use solidcraft_geom::Seg2;
@@ -1408,10 +1406,7 @@ fn rounded_slot_exports_cylinders() {
let edges = [Vec3::new(30.0, -10.0, 4.0), Vec3::new(30.0, 10.0, 4.0), Vec3::new(0.0, 0.0, 4.0), Vec3::new(60.0, 0.0, 4.0)];
let b = fillet(&plate, &edges, 1.0).unwrap();
let text = step_export(&[&b], "t").unwrap();
assert!(!text.contains("B_SPLINE_SURFACE"), "{text}");
assert_eq!(text.matches("CYLINDRICAL_SURFACE(").count(), 4);
assert_eq!(text.matches("TOROIDAL_SURFACE(").count(), 2);
// No point of the file (surface placements included) lies outside the part.
// No point of the file (control points and surface placements included) lies outside the part.
let imp = round_trip(&b);
for line in text.lines().filter(|l| l.contains("CARTESIAN_POINT")) {
let Some(xyz) = line.split("((").nth(1).and_then(|r| r.split("))").next()) else { continue };
@@ -1427,10 +1422,9 @@ fn rounded_slot_exports_cylinders() {
}
/// A slot plate rounded along its top and bottom outlines, with a ramp cut across one end
/// (issue #1198). The other end's half turn is still written as a cylinder (its corners alone
/// point both ways: the seam comes from points along its edges). The faces the ramp crosses keep
/// their B-spline sheets, cut down to the faces: the rounds' sheets reached 35 mm past both ends,
/// and readers bounding the part by its surfaces saw a 60 mm part as 130 mm long.
/// (issue #1198): every surface the file writes is cut down to its face, so nothing reaches past
/// the part's ends (the rounds' sheets once reached 35 mm past both, and readers bounding the part
/// by its surfaces saw a 60 mm part as 130 mm long), and the part reads back whole.
#[test]
fn ramp_cut_slot_exports_sheets_bounded_by_their_faces() {
use solidcraft_geom::Seg2;
@@ -1453,10 +1447,6 @@ fn ramp_cut_slot_exports_sheets_bounded_by_their_faces() {
let tool = extrude(&side, &[ramp], -12.0, 0.0).unwrap().pop().unwrap();
let b = boolean(&rounded, &tool, BoolOp::Cut).unwrap().unwrap();
let text = step_export(&[&b], "t").unwrap();
// Both ends' walls and the three rounds along the sides it leaves whole; the two the ramp
// crosses stay sheets.
assert_eq!(text.matches("CYLINDRICAL_SURFACE(").count(), 5, "{text}");
assert_eq!(text.matches("B_SPLINE_SURFACE(").count(), 2, "{text}");
// No point of the file (control points and placements included) lies past the part's ends.
for line in text.lines().filter(|l| l.contains("CARTESIAN_POINT")) {
let Some(xyz) = line.split("((").nth(1).and_then(|r| r.split("))").next()) else { continue };
+26 -3
View File
@@ -1518,7 +1518,10 @@ mod tests {
/// Off a doubly curved face (a saddle patch over a cup's rim) its normal turns along a
/// straight edge: the strip is ruled to a far curve of its own, from corner to corner, which
/// its handles move.
/// its handles move. Lifting every handle (the far curve's interior control points) 1 mm in z
/// gives the far curve those control points and the same corners, so it rises by
/// 1 − R₀ − Rₙ (its end basis functions) inside and not at all at the corners; the strip built
/// with them has that curve for its far edge, away from where the default strip's runs.
#[test]
fn a_strip_off_a_curved_face_is_ruled_to_its_far_curve() {
let b = box_solid(Vec3::new(-14.0, -14.0, 0.0), Vec3::new(14.0, 14.0, 20.0)).unwrap();
@@ -1533,9 +1536,29 @@ mod tests {
assert!(s.is_surface() && s.face_count() == 1);
let handles = ruled_far_handles(&cover, &edge, &r).unwrap();
let [Some(h)] = handles.as_slice() else { panic!("one free strip: {handles:?}") };
assert!(!h.is_empty(), "the far curve has interior control points to move");
let lifted: Vec<Vec3> = h.iter().map(|p| *p + Vec3::new(0.0, 0.0, 1.0)).collect();
let moved = ruled_surface_with(&cover, &edge, &r, &[Some(lifted)]).unwrap();
assert!(measure(&moved).unwrap().bbox.max.z > measure(&s).unwrap().bbox.max.z, "the handles move the far curve");
let moved = ruled_surface_with(&cover, &edge, &r, &[Some(lifted.clone())]).unwrap();
// The plan takes the handles as they are, and keeps the corners.
let (plain, given) = (planned(&cover, &edge, &r, &[]).unwrap(), planned(&cover, &edge, &r, &[Some(lifted.clone())]).unwrap());
let (far, far_moved) = (&plain.strips[0].top, &given.strips[0].top);
let ctrl = |c: &CurveN<4>| c.ctrl.iter().map(|h| Vec3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3])).collect::<Vec<_>>();
let (before, after) = (ctrl(far), ctrl(far_moved));
assert_eq!(after.len(), lifted.len() + 2);
assert!(after[1..after.len() - 1].iter().zip(&lifted).all(|(a, b)| a.dist(*b) < 1e-12), "{after:?} vs {lifted:?}");
assert!(before[0].dist(after[0]) < 1e-12 && before[before.len() - 1].dist(after[after.len() - 1]) < 1e-12);
// The built strip's far edge is that curve (its edges' polylines within 1e-4 of their
// curves), and its middle is well off the default strip's edges.
let tol = 1e-4;
for i in 0..=32 {
let p = point(far_moved, f64::from(i) / 32.0).unwrap();
let (_, d) = moved.nearest_edge(p, tol).unwrap().unwrap();
assert!(d < 10.0 * tol, "the far curve at {i}/32, {p:?}, is {d} from the strip's edges");
}
let (mid, rose) = (point(far_moved, 0.5).unwrap(), point(far_moved, 0.5).unwrap().dist(point(far, 0.5).unwrap()));
assert!(rose > 0.1, "the middle rose {rose}");
let (_, d) = s.nearest_edge(mid, tol).unwrap().unwrap();
assert!(d > 0.5 * rose, "the default strip has an edge {d} from the moved middle (it rose {rose})");
}
/// Each strip is made in place of the edge it stands on; a corner face in place of the two
+10 -11
View File
@@ -1,6 +1,6 @@
use super::*;
fn wedge() -> (Body, RadiusSpline) {
fn wedge() -> Body {
use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
let outer = Loop2::polygon(&[Vec2::new(0., 0.), Vec2::new(40., 0.), Vec2::new(0., 20.)]);
let body = crate::extrude(&Plane::XY, &[Region2 { outer, holes: vec![] }], 0., 15.).unwrap().pop().unwrap();
@@ -9,23 +9,22 @@ fn wedge() -> (Body, RadiusSpline) {
// is built over the wedge's cliffs (the blend-overflow decision), so a tapered fillet no
// longer tapers it.
let t = taper(&body, at, 16.).unwrap();
(fillet_variable_spline(&body, at, t.start, &t.spline).unwrap(), t.spline)
}
fn expected(law: &RadiusSpline) -> f64 {
let n = 20_000;
let integral = (0..n).map(|i| law.eval((i as f64 + 0.5) / n as f64).powi(2)).sum::<f64>() / n as f64;
6000. - (1. - std::f64::consts::FRAC_PI_4) * 40. * integral
fillet_variable_spline(&body, at, t.start, &t.spline).unwrap()
}
/// The display mesh of a fillet tapering to zero at a wedge's tip converges to the B-rep: each
/// mesh lies within its chord tolerance of the faces, so its volume is within the body's area
/// times that tolerance of the exact one (SMLib's, integrated on the surfaces, to 1e-8). Only
/// the mesher is under test here; the taper's own law is `taper_follows_the_room_along_the_edge`'s.
#[test]
fn collapsed_taper_mesh_stays_accurate_as_tolerance_decreases() {
let (body, law) = wedge();
let wanted = expected(&law);
let body = wedge();
let exact = crate::measure(&body).unwrap();
for tol in [0.002, 0.001, 0.0005, 0.0002] {
let mesh = body.mesh(&crate::MeshTolerance::chord(tol)).unwrap();
assert!(mesh.positions.iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()));
let got = mesh.measure().volume;
assert!((got - wanted).abs() / wanted < 1e-4, "tol={tol}: {got} vs {wanted}");
let bound = exact.area * tol;
assert!((got - exact.volume).abs() <= bound, "tol={tol}: mesh {got} vs exact {} (within {bound})", exact.volume);
}
}
+47 -5
View File
@@ -15,7 +15,7 @@ const MAX_DEPTH: u32 = 24;
/// The most of its curve's turn one segment may span (a quarter turn, with rounding room): the
/// boundary of every face stays a polygon with the face's area, as a closed curve's first four
/// segments keep it.
const QUARTER_TURN: f64 = std::f64::consts::FRAC_PI_2 * (1.0 + 1e-9);
pub(crate) const QUARTER_TURN: f64 = std::f64::consts::FRAC_PI_2 * (1.0 + 1e-9);
/// An edge's nodes, from its start vertex (interval min) to its end vertex (interval max).
pub(crate) struct Nodes {
@@ -23,6 +23,10 @@ pub(crate) struct Nodes {
/// The curve's parameter at each node (the edge's interval, ends included): where each
/// face's pcurve of the edge gives the node's (u, v).
pub params: Vec<f64>,
/// The parameters of the nodes that are another edge's node, where the two edges touch
/// within the chord tolerance (see [`snap`]): in a face that runs both edges such a node is
/// the other's point of the face, a pinch, not a crossing.
pub snapped: Vec<f64>,
}
/// Nodes of edge `ei` of `b` from its start to its end: every chord within the tolerance of
@@ -56,7 +60,7 @@ pub(crate) fn sample_edge(b: &brep::Brep, ei: usize, rules: &Rules, h: f64) -> R
*p = back;
*t = t1;
}
return Ok(Nodes { points: pts, params });
return Ok(Nodes { points: pts, params, snapped: Vec::new() });
}
let curve = CurveEval::new(edge.parameters()).map_err(|e| fail(e.to_string()))?;
let at =
@@ -115,7 +119,7 @@ pub(crate) fn sample_edge(b: &brep::Brep, ei: usize, rules: &Rules, h: f64) -> R
if let Some(p) = out.last_mut() {
*p = (t1, back);
}
Ok(Nodes { points: out.iter().map(|p| p.1).collect(), params: out.iter().map(|p| p.0).collect() })
Ok(Nodes { points: out.iter().map(|p| p.1).collect(), params: out.iter().map(|p| p.0).collect(), snapped: Vec::new() })
}
/// Edge `ei`'s nodes with each of its segments `segs` (counted from its start) halved at the
@@ -158,12 +162,50 @@ pub(crate) fn split_segments(b: &brep::Brep, ei: usize, nodes: &mut Nodes, segs:
points.push(pm);
params.push(m);
}
*nodes = Nodes { points, params };
nodes.points = points;
nodes.params = params;
Ok(())
}
/// Edge `ei`'s nodes with `add` (each a parameter strictly inside a segment and the point there)
/// put in, in order, each marked as snapped: the point is another edge's node within the chord
/// tolerance of this edge's chord there (the edges touch), so the two edges share it. A parameter
/// that is not strictly between its segment's two (a node already there) is left out. More than
/// [`MAX_EDGE_NODES`] nodes is an error naming the edge.
pub(crate) fn snap(ei: usize, nodes: &mut Nodes, add: &[(f64, Vec3)]) -> Result<()> {
let mut add: Vec<(f64, Vec3)> = add.iter().copied().filter(|(t, p)| t.is_finite() && p.is_finite()).collect();
add.sort_by(|a, b| a.0.total_cmp(&b.0));
add.dedup_by(|a, b| a.0 == b.0);
if nodes.points.len() + add.len() > MAX_EDGE_NODES {
return Err(KernelError::Failed(format!("tessellation: edge {ei}: more than {MAX_EDGE_NODES} nodes")));
}
let n = nodes.points.len().min(nodes.params.len());
let (mut points, mut params) = (Vec::with_capacity(n + add.len()), Vec::with_capacity(n + add.len()));
let mut next = add.iter().peekable();
for k in 0..n {
let (Some(&p), Some(&t)) = (nodes.points.get(k), nodes.params.get(k)) else { continue };
points.push(p);
params.push(t);
let Some(&u) = nodes.params.get(k + 1) else { continue };
while let Some(&&(m, q)) = next.peek() {
if m >= u {
break;
}
next.next();
if m > t {
points.push(q);
params.push(m);
nodes.snapped.push(m);
}
}
}
nodes.points = points;
nodes.params = params;
Ok(())
}
/// Angle (radians) between two directions; zero when either is empty.
fn turn(a: Vec3, b: Vec3) -> f64 {
pub(crate) fn turn(a: Vec3, b: Vec3) -> f64 {
let (la, lb) = (a.len(), b.len());
if !(la > 0.0 && lb > 0.0) {
return 0.0;
+220 -1
View File
@@ -196,7 +196,7 @@ pub(crate) fn plan(b: &brep::Brep, tol: f64, turn: Option<size::Turn>) -> Result
};
let mut boundaries: Vec<Boundary> =
crate::par::map("face boundaries", &indexed, curved >= PARALLEL_FACES, |&fi| face_boundary(fi, &nodes)).into_iter().collect::<Result<_>>()?;
let tangled = untangle(b, &evals, &edge_faces, &mut nodes, &mut boundaries, &face_boundary)?;
let tangled = untangle(b, &evals, &edge_faces, rules.tol, &mut nodes, &mut boundaries, &face_boundary)?;
let planned = crate::par::map("face tessellation", &indexed, curved >= PARALLEL_FACES, |&fi| {
let (Some(face), Some(eval), Some(size), Some(fb)) = (faces.get(fi), evals.get(fi), sizes.get(fi), boundaries.get(fi)) else {
return Err(unsupported(format!("face {fi}: missing")));
@@ -288,10 +288,19 @@ fn boundary(
let mut out = Boundary { loops: Vec::with_capacity(face.loops.len()), segments: Vec::with_capacity(face.loops.len()), reach };
// Each vertex's parameters, from the first edge use of the face to start there.
let mut at_vertex: std::collections::HashMap<u32, [f64; 2]> = std::collections::HashMap::new();
// The vertex pairs an edge of the face joins.
let joined: std::collections::HashSet<(u32, u32)> = face_edges(face)
.filter_map(|oe| b.edges.get(oe.edge as usize))
.map(|e| (e.vertices[0].min(e.vertices[1]), e.vertices[0].max(e.vertices[1])))
.collect();
let vertex_point = |v: u32| b.vertices.get(v as usize).map(|x| (Vec3::new(x.point[0], x.point[1], x.point[2]), x.tolerance.max(0.0)));
// Each loop's nodes that are another edge's node (see [`edges::snap`]).
let mut snapped: Vec<Vec<bool>> = Vec::with_capacity(face.loops.len());
for l in &face.loops {
let Loop::Edges { edges } = l else { continue };
let (mut pts, mut uvs): (Vec<Vec3>, Vec<[f64; 2]>) = (Vec::new(), Vec::new());
let mut segs: Vec<(u32, u32)> = Vec::new();
let mut shared: Vec<bool> = Vec::new();
// Where the previous edge ended, and the periods its pcurve was moved by.
let (mut end, mut shift): (Option<[f64; 2]>, [f64; 2]) = (None, [0.0; 2]);
for oe in edges {
@@ -306,6 +315,7 @@ fn boundary(
// The edge's own tolerance: how far its curve may stand off the face.
let accept = (rules.tol * 10.0).max(1e-6) + edge.tolerance.max(0.0);
let mut ep: Vec<Vec3> = n.points.clone();
let mut es: Vec<bool> = n.params.iter().map(|t| n.snapped.contains(t)).collect();
let mut eq: Vec<[f64; 2]> = Vec::with_capacity(ep.len());
for (k, (t, p)) in n.params.iter().zip(&n.points).enumerate() {
let q = oe.pcurve.eval(t.clamp(p0, p1)).ok_or_else(|| fail(oe.edge, format!("its pcurve does not evaluate at t = {t}")))?;
@@ -320,6 +330,7 @@ fn boundary(
if !oe.forward {
ep.reverse();
eq.reverse();
es.reverse();
}
if let (Some(e), Some(&start)) = (end, eq.first()) {
for d in 0..2 {
@@ -341,6 +352,24 @@ fn boundary(
}
}
None => {
// Another vertex of the face within the tolerance of both (and of the
// chord tolerance), and not joined to this one by an edge (which makes
// them two points however near: a step that small), is the same point:
// the record's corners a hair apart (a planar boolean's, where a cut-out's
// corner touches another loop's corner) are one point of the face, so its
// loops touch there instead of crossing.
let same = vertex_point(v).and_then(|(p, tv)| {
at_vertex.iter().filter(|(w, _)| **w != v && !joined.contains(&(v.min(**w), v.max(**w)))).find_map(|(w, wq)| {
let (pw, tw) = vertex_point(*w)?;
(p.dist(pw) <= tv.max(tw).min(rules.tol)).then_some(*wq)
})
});
if let Some(mut w) = same.filter(|w| !(0..2).any(|d| pole_along(*w, d) || pole_along(*q, d))) {
for d in 0..2 {
w[d] = uv::unwrap(w[d], q[d], dom.period[d]);
}
*q = w;
}
at_vertex.insert(v, *q);
}
}
@@ -348,11 +377,13 @@ fn boundary(
end = eq.last().copied();
ep.pop();
eq.pop();
es.pop();
// The segment from each node on: the edge's own, counted from its start.
let m = ep.len() as u32;
segs.extend((0..m).map(|j| (oe.edge, if oe.forward { j } else { m - 1 - j })));
pts.extend(ep);
uvs.extend(eq);
shared.extend(es);
}
let n = uvs.len();
let pole = |q: &[f64; 2]| (0..2).any(|d| pole_along(*q, d));
@@ -367,10 +398,37 @@ fn boundary(
uvs.rotate_left(k);
pts.rotate_left(k);
segs.rotate_left(k);
shared.rotate_left(k);
}
if pts.len() >= 2 {
out.loops.push(seam::Loop { uv: uvs, pts });
out.segments.push(segs);
snapped.push(shared);
}
}
// A node snapped from another edge is that edge's node, the same point: where the face runs
// that edge too, the node takes the other's parameters, so the face's boundary passes one
// point of its (u, v) twice (a pinch) and does not cross itself there. Its own pcurve puts it
// within the chord tolerance of that point, not on it.
for (l, flags) in snapped.iter().enumerate() {
for (k, _) in flags.iter().enumerate().filter(|(_, f)| **f) {
let Some((&p, &q)) = out.loops.get(l).and_then(|lp| lp.pts.get(k).zip(lp.uv.get(k))) else { continue };
let partner = out
.loops
.iter()
.zip(&snapped)
.flat_map(|(lp, fs)| lp.pts.iter().zip(&lp.uv).zip(fs))
.filter(|((r, _), f)| !**f && **r == p)
.map(|((_, w), _)| *w)
.min_by(|a, b| (a[0] - q[0]).hypot(a[1] - q[1]).total_cmp(&(b[0] - q[0]).hypot(b[1] - q[1])));
if let (Some(mut w), Some(slot)) = (partner, out.loops.get_mut(l).and_then(|lp| lp.uv.get_mut(k))) {
for d in 0..2 {
if dom.period[d].is_some() {
w[d] = uv::unwrap(w[d], q[d], dom.period[d]);
}
}
*slot = w;
}
}
}
Ok(out)
@@ -394,10 +452,12 @@ struct Boundary {
/// so every face of the edge gets the new nodes; the faces of every edge split are checked again,
/// until no chords cross. Boundaries that still cross after [`MAX_UNTANGLE`] rounds, or would
/// put more than [`edges::MAX_EDGE_NODES`] on an edge, are an error naming the face and edges.
#[allow(clippy::too_many_arguments)]
fn untangle(
b: &brep::Brep,
evals: &[EvalSurface],
edge_faces: &[Vec<usize>],
tol: f64,
nodes: &mut [edges::Nodes],
boundaries: &mut [Boundary],
face_boundary: &(dyn Fn(usize, &[edges::Nodes]) -> Result<Boundary> + Sync),
@@ -419,6 +479,10 @@ fn untangle(
return Ok(Vec::new());
}
if round == MAX_UNTANGLE {
// Halving cannot part two curves that touch or cross: where they come within the chord
// tolerance of each other, they share nodes.
let faces: Vec<usize> = tangled.iter().map(|(fi, _)| *fi).collect();
tangled = snap_touches(evals, edge_faces, tol, nodes, boundaries, face_boundary, &faces)?;
// Each face still crossing, with why: planned leniently, and named (`plan_or_fill`).
return Ok(tangled
.iter()
@@ -459,6 +523,161 @@ fn untangle(
Ok(Vec::new())
}
/// Rounds of [`snap_touches`] before a face that still crosses itself is refused.
const MAX_SNAP: u32 = 8;
/// The faces `faces` whose boundaries cross themselves where two curves touch or cross (halving
/// their chords does not part them, see [`untangle`]), with every node that lies within the chord
/// tolerance `tol` of a crossing chord of another edge put onto that edge as well (see
/// [`edges::snap`]): the two edges share the point, the face's boundary passes it twice (a pinch,
/// as at a vertex two loops share), and the chords meet there instead of crossing. Where the
/// curves run within the tolerance of each other for a stretch (a sliver between two touches),
/// the nodes on either side are shared in turn, so the boundary runs out and back along one
/// polyline there: a slit, which bounds the face on neither side. A node is not snapped where the
/// pinch would turn part of its loop inside out by more than the tolerance (two curves crossing
/// at an angle: the boundary is wrong there, not within the tolerance). Every face of a changed
/// edge has its boundary built again. Returns the faces whose boundaries still cross, with the
/// crossing segments.
#[allow(clippy::too_many_arguments)]
fn snap_touches(
evals: &[EvalSurface],
edge_faces: &[Vec<usize>],
tol: f64,
nodes: &mut [edges::Nodes],
boundaries: &mut [Boundary],
face_boundary: &(dyn Fn(usize, &[edges::Nodes]) -> Result<Boundary> + Sync),
faces: &[usize],
) -> Result<Vec<(usize, Vec<(u32, u32)>)>> {
let crossing = |fi: usize, fb: &Boundary| -> Vec<(usize, usize)> {
let Some(s) = evals.get(fi) else { return Vec::new() };
tangle::crossing(s, fb.reach, &fb.loops)
};
let mut tangled: Vec<usize> = faces.to_vec();
for _ in 0..MAX_SNAP {
let mut add: HashMap<u32, Vec<(f64, Vec3)>> = HashMap::new();
for &fi in &tangled {
let Some(fb) = boundaries.get(fi) else { continue };
for (l, k) in crossing(fi, fb) {
let Some(&(e, j)) = fb.segments.get(l).and_then(|s| s.get(k)) else { continue };
if let Some((t, p)) = touch(fb, nodes, (l, k), (e, j), tol) {
add.entry(e).or_default().push((t, p));
}
}
}
if add.is_empty() {
break;
}
let mut redo: Vec<usize> = Vec::new();
for (e, points) in &add {
let Some(slot) = nodes.get_mut(*e as usize) else { continue };
edges::snap(*e as usize, slot, points)?;
redo.extend(edge_faces.get(*e as usize).into_iter().flatten().copied());
}
redo.extend(tangled.iter().copied());
redo.sort_unstable();
redo.dedup();
tangled.clear();
for fi in redo {
let fb = face_boundary(fi, nodes)?;
let crosses = !crossing(fi, &fb).is_empty();
if let Some(slot) = boundaries.get_mut(fi) {
*slot = fb;
}
if crosses {
tangled.push(fi);
}
}
if tangled.is_empty() {
return Ok(Vec::new());
}
}
Ok(tangled
.into_iter()
.filter_map(|fi| {
let fb = boundaries.get(fi)?;
let c: Vec<(u32, u32)> = crossing(fi, fb).into_iter().filter_map(|(l, k)| fb.segments.get(l)?.get(k).copied()).collect();
(!c.is_empty()).then_some((fi, c))
})
.collect())
}
/// The node of face boundary `fb` nearest the crossing chord `at` (loop, node) of its boundary,
/// segment `seg` (edge, segment from its start) of that edge, within `tol` of the chord strictly
/// between its ends, on another edge, and not yet on this one; with the parameter on the edge
/// where it projects onto the chord. `None` when there is none, or snapping it would turn part
/// of its loop inside out by more than the tolerance (see [`snap_touches`]).
fn touch(fb: &Boundary, nodes: &[edges::Nodes], at: (usize, usize), seg: (u32, u32), tol: f64) -> Option<(f64, Vec3)> {
let (e, j) = seg;
let n = nodes.get(e as usize)?;
let j = j as usize;
let (a, c) = (*n.points.get(j)?, *n.points.get(j + 1)?);
let (ta, tc) = (*n.params.get(j)?, *n.params.get(j + 1)?);
let ac = c - a;
let len2 = ac.dot(ac);
if !(len2 > 0.0) {
return None;
}
let mut best: Option<(f64, f64, Vec3)> = None;
for (l, lp) in fb.loops.iter().enumerate() {
let segs = fb.segments.get(l)?;
let m = lp.pts.len();
for (k, &p) in lp.pts.iter().enumerate() {
// The node's edges: the segment starting at it and the one ending there.
let edges_at = [segs.get(k).map(|s| s.0), segs.get((k + m - 1) % m).map(|s| s.0)];
if edges_at.contains(&Some(e)) || n.points.contains(&p) {
continue;
}
let f = (p - a).dot(ac) / len2;
let d = p.dist_to_segment(a, c);
if !(f > 1e-6 && f < 1.0 - 1e-6 && d <= tol) || best.is_some_and(|(bd, _, _)| bd <= d) {
continue;
}
if l == at.0 && inside_out(lp, at.1, k, tol) {
continue;
}
best = Some((d, ta + f * (tc - ta), p));
}
}
best.map(|(_, t, p)| (t, p))
}
/// Whether pinching loop `lp` at node `k` and a new node (the same point) on its chord from node
/// `at` would turn either part inside out by more than `tol`: a part whose winding in (u, v) is
/// against the loop's, and whose area is more than `tol` across (twice its area in 3D over its
/// length).
fn inside_out(lp: &seam::Loop, at: usize, k: usize, tol: f64) -> bool {
let m = lp.uv.len();
if m < 3 {
return false;
}
// The two parts: from the node after the chord's start round to `k`, and from `k` round to the
// chord's start.
let part = |from: usize, to: usize| -> Vec<usize> {
let mut out = Vec::new();
let mut i = from % m;
loop {
out.push(i);
if i == to % m || out.len() > m {
break;
}
i = (i + 1) % m;
}
out
};
let whole = area2(&lp.uv);
[part(at + 1, k), part(k, at)].iter().any(|ids| {
let uv: Vec<[f64; 2]> = ids.iter().filter_map(|&i| lp.uv.get(i).copied()).collect();
let pts: Vec<Vec3> = ids.iter().filter_map(|&i| lp.pts.get(i).copied()).collect();
if uv.len() < 3 || area2(&uv) * whole >= 0.0 {
return false;
}
// Newell's vector: twice the area of the polygon in 3D.
let twice = pts.iter().zip(pts.iter().cycle().skip(1)).fold(Vec3::ZERO, |acc, (p, q)| acc + p.cross(*q)).len();
let length: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(p, q)| p.dist(*q)).sum();
twice > tol * length
})
}
/// Bounded work for the facet angle: a face whose boundary would get more than
/// [`size::MAX_ANGLE_BOUNDARY`] segments has its curved edges sampled again at twice the angle,
/// as often as it takes, down to the tolerance alone (a plate with a thousand small holes is
+41 -14
View File
@@ -5,6 +5,7 @@
use solidcraft_geom::tess::EvalSurface;
pub(crate) use solidcraft_geom::tess::uv::{Domain, degenerate_within, domain, unwrap};
use super::edges::{QUARTER_TURN, turn};
use super::size::Rules;
/// Division of `range` along direction `d` so that between neighbouring lines the surface sags
@@ -16,19 +17,10 @@ pub(crate) fn divide(s: &EvalSurface, d: usize, range: (f64, f64), across: (f64,
if !(a1 > a0) {
return vec![a0, a1];
}
let flat = limits(s, d, across, rules, h);
// Start from quarter turns at most, so a closed iso-line is not taken for a flat one (a
// plane's parameters are lengths and its lines are never closed).
let initial = if matches!(s, EvalSurface::Plane { .. }) { 1 } else { ((a1 - a0) / std::f64::consts::FRAC_PI_2).ceil().clamp(1.0, 64.0) as u32 };
// Both ends exactly (a0 + (a1 − a0) · 1 may round away from a1): the end lines are the
// face's own parameter box, which the boundary nodes sit on.
let starts: Vec<f64> = (0..=initial)
.map(|i| {
let t = f64::from(i) / f64::from(initial);
a0 * (1.0 - t) + a1 * t
})
.collect();
split(&starts, &flat, max_lines)
// The whole range first: the limits split it, and no interval spans more than a quarter
// turn of its iso-lines, so a closed iso-line is never taken for a flat one. Both ends
// exactly: the end lines are the face's own parameter box, which the boundary nodes sit on.
split(&[a0, a1], &limits(s, d, across, rules, h), max_lines)
}
/// `lines` (increasing, ends included) with every interval that fails the same limits as
@@ -80,8 +72,14 @@ pub(crate) fn fine_between(s: &EvalSurface, rules: &Rules, h: f64, a: [f64; 2],
}
}
/// An iso-line's extent below which it is a point, as a fraction of the chord tolerance (which
/// is never finer than a millionth of the body, so this is far above rounding).
const POINT: f64 = 1e-6;
/// Whether the surface between the iso-lines at `a` and `b` (direction `d`, sampled along
/// iso-lines across `across`) is within the tolerance, the side length `h` and the facet angle.
/// iso-lines across `across`) is within the tolerance, the side length `h` and the facet angle,
/// and spans at most a quarter turn of each iso-line (as an edge segment does, see
/// [`QUARTER_TURN`]): a turn read from the points, since a spline's parameter is no angle.
fn limits<'a>(s: &'a EvalSurface, d: usize, across: (f64, f64), rules: &'a Rules, h: f64) -> impl Fn(f64, f64) -> bool + 'a {
let tol = rules.tol;
let uv = move |x: f64, y: f64| if d == 0 { (x, y) } else { (y, x) };
@@ -105,6 +103,15 @@ fn limits<'a>(s: &'a EvalSurface, d: usize, across: (f64, f64), rules: &'a Rules
if sag > tol {
return false;
}
// The two half chords of an arc turning θ differ by θ/2; a closed iso-line's by π.
// An iso-line within a millionth of the tolerance of one point (a pole) turns no
// amount: its directions are rounding.
if let Some(pm) = at(0.5 * (a + b), y)
&& pa.dist(pm).max(pm.dist(pb)) > POINT * tol
&& 2.0 * turn(pm - pa, pb - pm) > QUARTER_TURN
{
return false;
}
// At a pole the normal is undefined: take it from just inside the segment.
let na = normal(a, y).or_else(|| normal(a + 1e-4 * (b - a), y));
let nb = normal(b, y).or_else(|| normal(b - 1e-4 * (b - a), y));
@@ -147,6 +154,26 @@ mod tests {
assert_eq!(along.len(), 9);
}
/// A quarter of a cylinder as a rational quadratic spline (as SMLib holds a bend), its range a
/// rounding over π/2 as a boundary's pcurves give it: the quarter turn is read from the
/// surface, not the parameter, so at a tolerance above its sag it is one interval; and a whole
/// turn is still divided into quarters however coarse the tolerance.
#[test]
fn a_quarter_turn_is_read_from_the_surface_not_the_parameter() {
let w = std::f64::consts::FRAC_1_SQRT_2;
let q = std::f64::consts::FRAC_PI_2;
let s = EvalSurface::nurbs(
[1, 2],
[vec![0.0, 0.0, 40.0, 40.0], vec![0.0, 0.0, 0.0, q, q, q]],
[2, 3],
vec![[1.0, 0.0, 0.0, 1.0], [1.0, 0.0, 40.0, 1.0], [w, w, 0.0, w], [w, w, 40.0 * w, w], [0.0, 1.0, 0.0, 1.0], [0.0, 1.0, 40.0, 1.0]],
);
let coarse = Rules { tol: 3.0, max_len: f64::INFINITY, turn: None };
assert_eq!(divide(&s, 1, (-6.7e-13, q), (0.0, 40.0), &coarse, f64::INFINITY, 10_000), vec![-6.7e-13, q]);
let whole = divide(&cylinder(), 1, (0.0, std::f64::consts::TAU), (0.0, 1.0), &Rules { tol: 100.0, ..coarse }, f64::INFINITY, 10_000);
assert_eq!(whole.len(), 5, "{whole:?}");
}
/// The first and last lines are the range's ends to the last bit: the boundary nodes sit on
/// them, and a line a rounding inside would be taken for an interior one (a drill point's
/// cone, where a0 + (a1 − a0) is not a1).
+156 -341
View File
@@ -287,37 +287,6 @@ fn fillet_ending_across_two_faces() {
assert!((lost - removed).abs() < 0.07, "{lost} vs {removed}");
}
#[test]
fn loop_fillet_as_tall_as_its_wall_consumes_it() {
// The removed cross-section (a square of side r less a quarter disc) and its centroid's
// distance from the wall: r(10 − 3π) / (3(4 − π)).
let spandrel = |r: f64| ((1.0 - PI / 4.0) * r * r, r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)));
// #190: a disc 13 in radius and 2 high, its top circle rounded by 2. Pappus for the ring.
let disc = cylinder(Vec3::ZERO, Vec3::Z, 13.0, 2.0).unwrap();
let f = fillet(&disc, &[Vec3::new(0.0, 13.0, 2.0), Vec3::new(0.0, -13.0, 2.0)], 2.0).unwrap();
let (a, c) = spandrel(2.0);
let want = PI * 169.0 * 2.0 - a * 2.0 * PI * (13.0 - c);
let m = measure(&f).unwrap();
assert!(rel(m.volume, want) < 2e-4, "{} vs {want}", m.volume);
// Top, round and bottom: the wall is gone.
assert_eq!(m.merged.faces, 3, "{:?}", m.merged);
assert!(f.validity().is_empty(), "{:?}", f.validity());
// A 40 x 30 x 5 plate, its whole top outline rounded by 5 (mitred at the corners).
let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 5.0)).unwrap();
let top = [Vec3::new(20.0, 0.0, 5.0), Vec3::new(40.0, 15.0, 5.0), Vec3::new(20.0, 30.0, 5.0), Vec3::new(0.0, 15.0, 5.0)];
let f = fillet(&plate, &top, 5.0).unwrap();
let (a, c) = spandrel(5.0);
let want = 6000.0 - a * 2.0 * ((40.0 - 2.0 * c) + (30.0 - 2.0 * c));
let m = measure(&f).unwrap();
assert!(rel(m.volume, want) < 2e-4, "{} vs {want}", m.volume);
assert!(f.validity().is_empty(), "{:?}", f.validity());
// Taller than the wall: still refused, the body unchanged.
for r in [2.0 + 1e-3, 2.5] {
let e = fillet(&disc, &[Vec3::new(0.0, 13.0, 2.0), Vec3::new(0.0, -13.0, 2.0)], r).unwrap_err();
assert!(e.to_string().contains("taller than the walls"), "{r}: {e}");
}
}
#[test]
fn fillet_consuming_a_side_face_makes_a_full_round() {
// 14 x 6 x 10: r = 3 on the four vertical edges uses up both 6 mm end faces (#199).
@@ -371,63 +340,6 @@ fn fillet_max_finds_the_largest_radius_that_works() {
assert_eq!(fillet_max(&b, &[Vec3::new(500.0, 0.0, 5.0)], 1.0).unwrap_err().to_string(), e.to_string());
}
/// Rounds past the bottom of a wall (a cliff) are built as if the wall went on and cut from the
/// part (the blend-overflow decision, 237f0ae74), never refused as too large: a disc's top edge
/// past its 2 mm wall, and a block's top outline past the 7 mm wall over a notch.
#[test]
fn rounds_past_the_bottom_of_a_wall_are_cut_from_the_part() {
// A 2 mm disc's top edge at 2.5 runs past the wall's bottom edge (a cliff): the round is
// built as if the wall went on down and cut from the disc (the blend-overflow decision,
// 237f0ae74), not refused. Its section in (ρ, z), the 2.5 square at the edge outside the
// circle about (10.5, -0.5) above z = 0, turned about the axis: with t = z + 0.5 =
// 2.5 sin θ, the round's inner radius ρ(θ) = 10.5 + 2.5 cos θ, the disc keeps
// π (169·2 − ∫ (169 − ρ²) dz) (2 mm: Pappus, as `loop_fillet_as_tall_as_its_wall_consumes_it`).
use std::f64::consts::FRAC_PI_2;
let disc = cylinder(Vec3::ZERO, Vec3::Z, 13.0, 2.0).unwrap();
let top = [Vec3::new(0.0, 13.0, 2.0), Vec3::new(0.0, -13.0, 2.0)];
let past = fillet(&disc, &top, 2.5).unwrap();
let (n, lo) = (20000, (0.5f64 / 2.5).asin());
let taken: f64 = (0..n)
.map(|i| {
let th = lo + (i as f64 + 0.5) * (FRAC_PI_2 - lo) / n as f64;
let rho = 10.5 + 2.5 * th.cos();
(169.0 - rho * rho) * 2.5 * th.cos()
})
.sum::<f64>()
* (FRAC_PI_2 - lo)
/ n as f64;
let want = PI * (169.0 * 2.0 - taken);
assert!(rel(measure(&past).unwrap().volume, want) < 1e-6, "{} vs {want}", measure(&past).unwrap().volume);
// Walls of different heights, a 7 mm one over a notch: R7 uses that wall up (a round may),
// and R8 runs past its bottom edge into the notch (a cliff) and is cut by it. The outline's
// mitred round takes (1 − π/4) r² along the outline less 8 times its centroid's distance
// from the faces, r (10 − 3π) / (3 (4 − π)); at R8 less its part inside the notch
// [35, 40] × [0, 5] × [2, 3], where each of the corner's two rounds reaches g = 8 − √(64 − t²)
// in from its face at t = z − 2 on its side of the mitre: ∫₀¹ 2 (5g − g²/2) dt.
let notched = boolean(
&box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap(),
&box_solid(Vec3::new(35.0, -1.0, -1.0), Vec3::new(41.0, 5.0, 3.0)).unwrap(),
BoolOp::Cut,
)
.unwrap()
.unwrap();
let outline = [Vec3::new(20.0, 0.0, 10.0), Vec3::new(40.0, 15.0, 10.0), Vec3::new(20.0, 30.0, 10.0), Vec3::new(0.0, 15.0, 10.0)];
let mitred = |r: f64| (1.0 - PI / 4.0) * r * r * (140.0 - 8.0 * r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)));
let in_notch: f64 = (0..n)
.map(|i| {
let t = (i as f64 + 0.5) / n as f64;
let g = 8.0 - (64.0 - t * t).sqrt();
2.0 * (5.0 * g - g * g / 2.0)
})
.sum::<f64>()
/ n as f64;
for (r, want) in [(7.0, 11925.0 - mitred(7.0)), (8.0, 11925.0 - (mitred(8.0) - in_notch))] {
let b = fillet(&notched, &outline, r).unwrap();
assert!(b.validity().is_empty(), "{r}: {:?}", b.validity());
assert!(rel(measure(&b).unwrap().volume, want) < 1e-6, "{r}: {} vs {want}", measure(&b).unwrap().volume);
}
}
/// Edges that share no face get their own largest radius: a 2 mm fin's top edge takes at most
/// its thickness, while a corner of the block it stands on, far from it, keeps the 4 asked for.
/// Edges that limit each other (the post's four, sharing faces) still share one.
@@ -461,24 +373,14 @@ fn fillet_max_each_reduces_only_where_the_radius_does_not_fit() {
assert_eq!(fillet_max_each(&post, &mids, 3.5).unwrap().map(|x| x.0), Some(vec![3.0; 4]));
}
/// A corner's rounds too large for its faces are refused as too large, so a fit can reduce
/// them, also where only the corner build finds it (the edge-by-edge blend failing otherwise).
/// A corner's rounds with a radius per edge, one wider than its faces, are refused as too large,
/// so a fit can reduce them. (The same corner at one radius as wide as the faces, and its fit,
/// are the rig's fillets/477-fillet-cube-corner-rounds-as-wide-as-faces-* cases; no command
/// takes a radius per edge.)
#[test]
fn corner_rounds_larger_than_their_faces_are_too_large() {
let (l, eps) = (20.0, 1e-9);
let b = box_solid(Vec3::ZERO, Vec3::new(l, l, l)).unwrap();
let b = box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap();
let corner = [Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 0.0, 10.0)];
// As wide as the faces: the first edge's round uses up its neighbour, then the edge-by-edge
// blend can't find it; the corner build is what says the radius is too large.
let e = fillet(&b, &corner, l).unwrap_err();
assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
let (r, body) = fillet_max(&b, &corner, l).unwrap().unwrap();
assert!((r - 19.99).abs() < eps, "{r}");
assert!(body.validity().is_empty(), "{:?}", body.validity());
// Three rounds along the edges past the corner cube, and the cube less its sphere octant.
let removed = 3.0 * (1.0 - PI / 4.0) * r * r * (l - r) + r * r * r * (1.0 - PI / 6.0);
assert!(rel(measure(&body).unwrap().volume, l * l * l - removed) < 2e-4);
// Different radii per edge, one wider than its faces.
let sel: Vec<(Vec3, f64)> = corner.iter().copied().zip([21.0, 5.0, 5.0]).collect();
let e = crate::blend_corner::fillet_radii(&b, &sel).unwrap_err();
assert!(matches!(e, KernelError::TooLarge(_)), "{e}");
@@ -668,28 +570,47 @@ fn tapered_extrude_of_cubics_is_close_to_the_true_offset() {
assert!(rel(m.volume, v) < 5e-4, "{} vs {v}", m.volume);
}
/// A wedge whose tip is a flat line far shorter than the taper moves its sides in: the tip line
/// goes, the two long sides meet, and its side is the flat triangle up to there. The solid is a
/// prismatoid, its volume h/6 · (A₀ + 4·A_mid + A₁).
/// A wedge whose tip is a flat line far shorter than the taper moves its sides in: every wall,
/// the tip's too, leans by the taper, so the tip's wall is a triangle that closes where the two
/// long sides meet across it (z* ≈ 0.126 of h = 2), and above that the long sides meet each
/// other along a ridge. The section at height z is the profile's lines moved in by z·tan(a): a
/// quadrilateral below z*, a triangle above, each with an area quadratic in z, so the volume is
/// exact as Simpson's rule on each of the two pieces.
#[test]
fn tapered_extrude_swallows_a_short_tip() {
let (h, a) = (2.0, 5f64.to_radians());
let d = h * a.tan();
let pts = [Vec2::new(0.0, -2.0), Vec2::new(20.0, -0.01), Vec2::new(20.0, 0.01), Vec2::new(0.0, 2.0)];
let b = extrude_tapered(&Plane::XY, &Region2 { outer: Loop2::polygon(&pts), holes: vec![] }, h, 1.0, -a, crate::DraftCorner::default()).unwrap();
// The top: the three long lines moved in by d (to their left, the loop running
// counter-clockwise), meeting each other.
let moved = |p: Vec2, q: Vec2| {
let t = (q - p).normalized().unwrap();
(p + t.perp() * d, t)
// Side i (from pts[i] to the next) moved in by t (to its left, the loop running
// counter-clockwise), as a point and its direction.
let moved = |i: usize, t: f64| {
let (p, q) = (pts[i], pts[(i + 1) % pts.len()]);
let u = (q - p).normalized().unwrap();
(p + u.perp() * t, u)
};
let meet = |(p0, t0): (Vec2, Vec2), (p1, t1): (Vec2, Vec2)| p0 + t0 * ((p1 - p0).cross(t1) / t0.cross(t1));
let (low, high, left) = (moved(pts[0], pts[1]), moved(pts[2], pts[3]), moved(pts[3], pts[0]));
let top = [meet(left, low), meet(low, high), meet(high, left)];
let area = |q: &[Vec2]| solidcraft_geom::Ring::from(q.to_vec()).signed_area();
// Halfway up, each side edge's midpoint (the two tip corners both run to the top's tip).
let mid = [pts[0].lerp(top[0], 0.5), pts[1].lerp(top[1], 0.5), pts[2].lerp(top[1], 0.5), pts[3].lerp(top[2], 0.5)];
let v = h / 6.0 * (area(&pts) + 4.0 * area(&mid) + area(&top));
// Where the long sides meet, measured off the moved tip line (into the solid positive): it
// runs linearly with t, and its root is the offset at which the tip's wall closes.
let past_tip = |t: f64| {
let (q, u) = moved(1, t);
(meet(moved(0, t), moved(2, t)) - q).cross(u)
};
let d = h * a.tan();
let closes = d * past_tip(0.0) / (past_tip(0.0) - past_tip(d));
let z_closes = closes / a.tan();
assert!(z_closes > 0.0 && z_closes < h, "the tip's wall closes partway up, at {z_closes}");
let section = |z: f64| -> Vec<Vec2> {
let t = z * a.tan();
if t <= closes {
(0..4).map(|i| meet(moved((i + 3) % 4, t), moved(i, t))).collect()
} else {
let (low, high, left) = (moved(0, t), moved(2, t), moved(3, t));
vec![meet(left, low), meet(low, high), meet(high, left)]
}
};
let area = |z: f64| solidcraft_geom::Ring::from(section(z)).signed_area();
let simpson = |z0: f64, z1: f64| (z1 - z0) / 6.0 * (area(z0) + 4.0 * area(0.5 * (z0 + z1)) + area(z1));
let v = simpson(0.0, z_closes) + simpson(z_closes, h);
let m = measure(&b).unwrap();
assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume);
assert_eq!(m.merged.faces, 6, "bottom, top, three sides and the tip's triangle");
@@ -719,10 +640,11 @@ fn tapered_extrude_between_with_a_foot() {
);
}
/// A taper steeper than a profile's details is refused, and says why: a slot narrower than the
/// taper closes; a ring's hole smaller than it closes.
/// A taper steeper than a profile's details: a slot narrower than the taper closes partway up
/// and the solid builds, the slot's walls meeting above where its end wall closes to a point; a
/// ring's hole smaller than the taper closes the whole hole and is refused, saying why.
#[test]
fn tapered_extrude_refuses_a_taper_steeper_than_the_details() {
fn tapered_extrude_closes_a_narrow_slot_and_refuses_a_closing_hole() {
let slot = Loop2::polygon(&[
Vec2::new(0.0, 0.0),
Vec2::new(10.0, 0.0),
@@ -733,9 +655,18 @@ fn tapered_extrude_refuses_a_taper_steeper_than_the_details() {
Vec2::new(4.9, 10.0),
Vec2::new(0.0, 10.0),
]);
let e = extrude_tapered(&Plane::XY, &Region2 { outer: slot, holes: vec![] }, 2.0, 1.0, 10f64.to_radians(), crate::DraftCorner::default())
.unwrap_err();
assert!(e.to_string().contains("the taper closes the profile"), "{e}");
let a = 10f64.to_radians();
let b = extrude_tapered(&Plane::XY, &Region2 { outer: slot, holes: vec![] }, 2.0, 1.0, a, crate::DraftCorner::default()).unwrap();
assert!(b.validity().is_empty(), "{:?}", b.validity());
// Every wall moves out of the material by z·t at height z (t = tan 10°): the 10 mm square
// grows to 10 + 2zt, so the solid without the slot is ∫₀² (10 + 2zt)² dz
// = ((10 + 4t)³ − 1000) / (6t). The slot narrows to 0.2 − 2zt, its length staying 8 (its end
// wall and the square's side both move up by zt), and it closes at z = 0.1/t (0.567, below
// the top): it takes ∫ 8 (0.2 − 2zt) dz over 0..0.1/t = 0.08/t.
let t = a.tan();
let v = ((10.0 + 4.0 * t).powi(3) - 1000.0) / (6.0 * t) - 0.08 / t;
let m = measure(&b).unwrap();
assert!(rel(m.volume, v) < 1e-6, "{} vs {v}", m.volume);
let ring = Region2 { outer: Loop2::circle(Vec2::ZERO, 5.0), holes: vec![Loop2::circle(Vec2::ZERO, 0.3).reversed()] };
let e = extrude_tapered(&Plane::XY, &ring, 2.0, 1.0, 10f64.to_radians(), crate::DraftCorner::default()).unwrap_err();
assert!(e.to_string().contains("the taper closes the profile"), "{e}");
@@ -1173,34 +1104,14 @@ fn chamfer_sloped_basin_rim() {
assert!(mesh.contains(Vec3::new(50.0, 3.5, 28.0)));
}
/// The removal of an equal-distance chamfer `d` of the rim edge at y = `margin` of
/// `chamfer_sloped_basin_rim`'s basin, cut from the slab as if its top went on past y = 0 (the
/// blend-overflow decision, 237f0ae74): the triangle between the edge (margin, 30), the top's
/// contact (margin − d, 30) and the wall's contact d down the wall towards (20, 10), clipped to
/// y >= 0, times the chamfer's length at its depth h, 60 − h between the sloped end walls:
/// area · (30 + z̄) over the clipped polygon (shoelace).
fn basin_rim_chamfer_removed(margin: f64, d: f64) -> f64 {
let len = ((20.0 - margin).powi(2) + 400.0).sqrt();
let (e, t) = ((margin, 30.0), (margin - d, 30.0));
let w = (margin + d * (20.0 - margin) / len, 30.0 - d * 20.0 / len);
let poly = if t.0 >= 0.0 {
vec![e, t, w]
} else {
let s = -t.0 / (w.0 - t.0);
vec![e, (0.0, 30.0), (0.0, t.1 + s * (w.1 - t.1)), w]
};
let (mut area, mut moment) = (0.0, 0.0);
for i in 0..poly.len() {
let ((y0, z0), (y1, z1)) = (poly[i], poly[(i + 1) % poly.len()]);
let c = y0 * z1 - y1 * z0;
area += c / 2.0;
moment += (z0 + z1) * c / 6.0;
}
area.abs() * 30.0 + moment.abs()
}
/// A chamfer wider than a basin's thin rim (`chamfer_sloped_basin_rim`'s basin with the rim
/// `margin` wide at the top) would run its leg off the rim's top, over the slab's front edge; as
/// wide as the rim it would use the rim's top up. Both are refused as too large, the kind a fit
/// can reduce, the body unchanged (the owner's blend-overflow ruling, 2026-10-30). The largest
/// size that fits is named by the doc layer (`with_largest_fit`) and graded, with the chamfers
/// that fit, by the rig's fillets/1080-chamfer-sloped-basin-* cases.
#[test]
fn chamfer_wider_than_sloped_basin_rim_is_cut_and_a_full_width_one_refused() {
fn chamfer_wider_than_sloped_basin_rim_is_refused() {
let rectangle = |x0, y0, x1, y1| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]);
let basin = |margin: f64| {
let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap();
@@ -1209,29 +1120,15 @@ fn chamfer_wider_than_sloped_basin_rim_is_cut_and_a_full_width_one_refused() {
.unwrap();
boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap()
};
// The formula reads the fitting chamfer of `chamfer_sloped_basin_rim` as it does.
let drop = 2.0 / (1.0 + 0.8f64.powi(2)).sqrt();
assert!(rel(basin_rim_chamfer_removed(4.0, 2.0), drop * (60.0 - drop / 3.0)) < 1e-12);
// Wider than the rim: the chamfer runs over the slab's front edge (a cliff) and is cut.
for (margin, distance) in [(1.0, 2.0), (1.0, 3.0), (0.5, 4.0)] {
for (margin, distance) in [(1.0, 2.0), (1.0, 3.0), (0.5, 4.0), (0.5, 0.5), (1.0, 1.0)] {
let b = basin(margin);
let before = measure(&b).unwrap().volume;
let made = chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], distance).unwrap_or_else(|e| panic!("{margin}, {distance}: {e}"));
assert!(made.validity().is_empty(), "{margin}, {distance}: {:?}", made.validity());
let want = before - basin_rim_chamfer_removed(margin, distance);
assert!(rel(measure(&made).unwrap().volume, want) < 1e-8, "{margin}, {distance}: {} vs {want}", measure(&made).unwrap().volume);
}
// As wide as the rim it would use the rim's top up: a full-width chamfer is refused, the
// body unchanged. A smaller chamfer on the same thin rim is still supported.
for margin in [0.5, 1.0] {
let b = basin(margin);
let before = measure(&b).unwrap();
let error = chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], margin).unwrap_err();
assert!(matches!(error, KernelError::TooLarge(_)), "{margin}: {error}");
assert_eq!(measure(&b).unwrap().volume, before.volume);
let smaller = chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], margin * 0.5).unwrap();
assert!(smaller.validity().is_empty());
assert!(measure(&smaller).unwrap().volume < before.volume);
match chamfer(&b, &[Vec3::new(50.0, margin, 30.0)], distance) {
Err(KernelError::TooLarge(_)) => {}
Err(e) => panic!("{margin}, {distance}: refused, but not as too large: {e}"),
Ok(_) => panic!("{margin}, {distance}: a chamfer whose leg runs off the rim was built"),
}
assert_eq!(measure(&b).unwrap().volume, before);
}
}
@@ -1474,25 +1371,44 @@ fn shell_non_convex() {
assert!(rel(v, outer - cavity) < 1e-6, "{v} vs {}", outer - cavity);
}
/// A basin: a slab with a tapered pocket and a 4 mm front rim, shelled from below. A wall
/// thicker than the rim (with the pocket's slope) would turn the top face inside out: refused,
/// not a body with wrong mass properties.
/// A basin: a 100 × 60 × 30 slab with a tapered pocket (60 × 46 at the top, 4 mm from the front,
/// 40 × 20 at its floor 20 down) shelled from below, each wall moved in by t with sharp edges.
/// The cavity is the slab shrunk by t (open at z = 0) less the pocket grown by t, each sloped side
/// moved out along its normal; the volume, slab − pocket − cavity, is a cubic in z integrated by
/// hand. From t ≈ 2.70 the front side's offset passes the front wall's below the 4 mm rim, and
/// the rim stays solid: the cavity's front stops at y = t (from z = (28 − (1 + √1.64) t)/0.8 up).
#[test]
fn shell_thicker_than_a_rim_is_refused() {
fn shell_of_a_basin_past_its_rim_keeps_the_rim_solid() {
let slab = box_solid(Vec3::ZERO, Vec3::new(100.0, 60.0, 30.0)).unwrap();
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)]);
let at = |z: f64| Plane::new(Vec3::new(0.0, 0.0, z), Vec3::X, Vec3::Y).unwrap();
let pocket = loft(&[(at(30.0), rect(20.0, 4.0, 80.0, 50.0)), (at(10.0), rect(30.0, 20.0, 70.0, 40.0))]).unwrap();
let basin = boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap();
let open = [Vec3::new(50.0, 30.0, 0.0)];
let e = shell(&basin, &open, 6.0).unwrap_err().to_string();
assert!(e.contains("rim or ledge"), "{e}");
let (whole, thin) = (measure(&basin).unwrap(), measure(&shell(&basin, &open, 1.0).unwrap()).unwrap());
assert!(thin.volume > 0.0 && thin.volume < whole.volume, "{} vs {}", thin.volume, whole.volume);
let (lo, hi) = (thin.bbox.min, thin.bbox.max);
let c = thin.centroid;
assert!(c.x > lo.x && c.x < hi.x && c.y > lo.y && c.y < hi.y && c.z > lo.z && c.z < hi.z, "{c:?}");
assert!((c.x - 50.0).abs() < 1e-3, "{c:?}");
// The pocket grown by t at height z: x from 35 − z/2 − t√5/2 to 65 + z/2 + t√5/2, y from
// 28 − 0.8 z − t√1.64 (or y = t, where that is less) to 35 + z/2 + t√5/2, for
// z = 10 − t … 30 − t; its sides stay inside the shrunk slab in x and at the back for t ≤ 6.
let (r5, r164) = (5f64.sqrt(), 1.64f64.sqrt());
let integral = |c: [f64; 3], lo: f64, hi: f64| c[0] * (hi - lo) + c[1] * (hi * hi - lo * lo) / 2.0 + c[2] * (hi.powi(3) - lo.powi(3)) / 3.0;
// (w0 + z)(h0 + h1 z) as coefficients in z.
let product = |w0: f64, h0: f64, h1: f64| [w0 * h0, w0 * h1 + h0, h1];
let grown = |t: f64| {
let (lo, hi, w0) = (10.0 - t, 30.0 - t, 30.0 + r5 * t);
let full = product(w0, 7.0 + t * (r5 / 2.0 + r164), 1.3);
let z0 = ((28.0 - r164 * t - t) / 0.8).clamp(lo, hi);
integral(full, lo, z0) + integral(product(w0, 35.0 + (r5 / 2.0 - 1.0) * t, 0.5), z0, hi)
};
let volume = |t: f64| 100.0 * 60.0 * 30.0 - grown(0.0) - (100.0 - 2.0 * t) * (60.0 - 2.0 * t) * (30.0 - t) + grown(t);
let whole = measure(&basin).unwrap();
assert!(rel(whole.volume, 180_000.0 - grown(0.0)) < 1e-9, "{}", whole.volume);
for (t, want) in [(1.0, 17_105.624_041_5), (4.0, 63_560.249_228_4), (6.0, 90_113.920_210_1)] {
assert!(rel(volume(t), want) < 1e-12, "the closed form at {t}: {}", volume(t));
let m = measure(&shell(&basin, &open, t).unwrap()).unwrap();
assert!(rel(m.volume, want) < 1e-6, "t {t}: {} vs {want}", m.volume);
let (lo, hi, c) = (m.bbox.min, m.bbox.max, m.centroid);
assert!(c.x > lo.x && c.x < hi.x && c.y > lo.y && c.y < hi.y && c.z > lo.z && c.z < hi.z, "{c:?}");
assert!((c.x - 50.0).abs() < 1e-3, "{c:?}");
}
}
#[test]
@@ -1896,6 +1812,22 @@ fn fillet_sharp_arc_and_arc_loop() {
assert!(rel(removed, want) < 1e-3, "{removed} vs {want}");
}
/// The area of the tabbed plate's outline (`fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole`)
/// with the R25 arc moved in by `da` and the tab's run (its sides, R2 corners and top) by `dt`,
/// each element parallel to itself, by Green's theorem: an arc about c of radius ρ from a to b
/// gives ½ (ρ² (b − a) + ρ (cx (sin b − sin a) − cy (cos b − cos a))), a segment p→q ½ (p × q).
/// At the concave corners (±4, y) the moved elements meet where they cross: where one side moves
/// the round runs into the other wall, where both do the two rounds are mitred (the owner's
/// ruling for rounds meeting at a concave corner beside an unpicked sharp edge, 2026-10-30).
fn tabbed_plate_area(da: f64, dt: f64) -> f64 {
let cy = 280.0 / 9.0;
let (big, rho) = (25.0 - da, 2.0 - dt);
let tab = rho * rho * PI + 2.0 * rho * (2.0 + cy) + 4.0 * (cy + rho);
let yc = (big * big - (4.0 - dt).powi(2)).sqrt();
let at = yc.atan2(4.0 - dt);
0.5 * (big * big * (PI + 2.0 * at) + tab) + (4.0 - dt) * (cy - yc)
}
#[test]
fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() {
use solidcraft_geom::Seg2;
@@ -1918,7 +1850,20 @@ fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() {
};
let body =
extrude(&Plane::XY, &[Region2 { outer: outline, holes: vec![Loop2::circle(Vec2::new(0.0, hole_y), 1.5)] }], 0.0, 2.0).unwrap().pop().unwrap();
let inner = fillet(&body, &[Vec3::new(1.5, hole_y, 2.0)], 0.5).unwrap();
let r = 0.5;
// The section a round takes off, (1 − π/4) r², and its centroid's distance from both faces.
let (spandrel, centroid) = ((1.0 - PI / 4.0) * r * r, r * (10.0 - 3.0 * PI) / (3.0 * (4.0 - PI)));
// The outline's area (Green's theorem, checked against the disc, the tab's rectangle and its
// two R2 corners), the plate its prism 2 high less the hole.
let outline_area = tabbed_plate_area(0.0, 0.0);
let parts = 312.5 * (PI + 2.0 * theta) + 4.0 * y + 8.0 * (corner_y - y) + 8.0 + 2.0 * PI;
assert!(rel(outline_area, parts) < 1e-14, "{outline_area} vs {parts}");
assert!(rel(measure(&body).unwrap().volume, 2.0 * (outline_area - PI * 2.25)) < 1e-9);
// The hole's rim round (Pappus: the spandrel about the hole's axis at 1.5 + its centroid).
let inner = fillet(&body, &[Vec3::new(1.5, hole_y, 2.0)], r).unwrap();
let rim = spandrel * 2.0 * PI * (1.5 + centroid);
let holed = measure(&inner).unwrap().volume;
assert!(rel(measure(&body).unwrap().volume - holed, rim) < 1e-5, "{} vs {rim}", measure(&body).unwrap().volume - holed);
let edges = [
Vec3::new(-24.91935125502191, -2.0064727829797544, 2.0),
Vec3::new(24.919351255429795, -2.006472777913911, 2.0),
@@ -1928,6 +1873,30 @@ fn fillet_tabbed_plate_outer_loop_and_partial_selection_after_hole() {
Vec3::new(-3.4142135648720653, 32.52532467287703, 2.0),
Vec3::new(-4.0000000025087745, 27.89451823429679, 2.0),
];
// The selections that end only at the sharp concave corners at (±4, y): the R25 arc (its two
// edges, tangent at the bottom), the tab's run (tangent through its R2 corners), and both.
// Each takes off the outline's section less the section moved in by d = r (1 − cos φ) at the
// height r sin φ into the round, integrated over that height (midpoint rule in φ).
let removed = |arc: bool, tab: bool, steps: u32| {
let dphi = (PI / 2.0) / f64::from(steps);
(0..steps)
.map(|i| {
let phi = (f64::from(i) + 0.5) * dphi;
let d = r * (1.0 - phi.cos());
(outline_area - tabbed_plate_area(if arc { d } else { 0.0 }, if tab { d } else { 0.0 })) * r * phi.cos() * dphi
})
.sum::<f64>()
};
for (mask, arc, tab) in [(0b0000011_u32, true, false), (0b1111100, false, true), (0b1111111, true, true)] {
let want = removed(arc, tab, 8192);
assert!((want - removed(arc, tab, 4096)).abs() < 1e-7 * want, "the reference quadrature must converge");
let picks: Vec<_> = edges.iter().enumerate().filter(|(i, _)| mask & (1 << i) != 0).map(|(_, p)| *p).collect();
let blended = fillet(&inner, &picks, r).unwrap_or_else(|e| panic!("{picks:?}: {e}"));
assert!(blended.validity().is_empty(), "{picks:?}: {:?}", blended.validity());
// Exact volumes (SMLib's, to 1e-8); the blend's surfaces are SMLib's fits.
let got = holed - measure(&blended).unwrap().volume;
assert!(rel(got, want) < 1e-5, "arc {arc}, tab {tab}: removed {got}, expected {want}");
}
// All 127 nonempty subsets: the whole rim, each individual edge, and every
// contiguous or disjoint partial selection of the issue's seven picks.
for mask in 1_u32..(1 << edges.len()) {
@@ -2019,8 +1988,8 @@ fn fillet_mixed_arc_and_line_removed_volume_converges() {
}
let blended = fillet(&body, &[Vec3::new(0.0, 10.0, 15.0), Vec3::new(5.0, 0.0, 15.0)], r).unwrap();
// The removal from the exact volumes (SMLib's, to 1e-8): the reference to a hundred
// thousandth (the blend's surfaces are SMLib's fits; their section error is
// fillet_mixed_arc_and_line_joint_preserves_both_section_radii's).
// thousandth (the blend's surfaces are SMLib's fits; the rig's
// fillets/485-fillet-d-prism-top-outline-arc-and-flat grades the same round).
let done = measure(&blended).unwrap();
let exact = source.volume - done.volume;
assert!(rel(exact, want) < 1e-5, "r={r}: removed {exact}, expected {want}");
@@ -2034,42 +2003,6 @@ fn fillet_mixed_arc_and_line_removed_volume_converges() {
}
}
#[test]
fn fillet_mixed_arc_and_line_joint_preserves_both_section_radii() {
let r = 0.5;
let body = mixed_arc_and_line_prism();
let blended = fillet(&body, &[Vec3::new(0.0, 10.0, 15.0), Vec3::new(5.0, 0.0, 15.0)], r).unwrap();
crate::guard("inspect mixed fillet mitres", || {
let rec = blended.record();
let mut mitres = std::collections::HashSet::new();
for (id, edge) in rec.edges.iter().enumerate() {
let a = Vec3::from(rec.vertices[edge.vertices[0] as usize].point);
let b = Vec3::from(rec.vertices[edge.vertices[1] as usize].point);
// Only the two corner profiles join the top contact to the wall contact.
if (a.z - b.z).abs() < r - 1e-8 || a.z.min(b.z) < 15.0 - r - 1e-8 || a.x * b.x <= 0.0 {
continue;
}
if !mitres.insert(id) {
continue;
}
let curve = solidcraft_geom::brep::eval::CurveEval::new(edge.parameters()).unwrap();
let [lo, hi] = edge.interval;
for i in 0..=257 {
let p = curve.point(lo + (hi - lo) * f64::from(i) / 257.0).unwrap();
// The joint lies on both the cylindrical line blend and the toroidal
// arc blend, not their tangent-plane approximation.
let radius2 = (p.y - r).powi(2) + (p.z - (15.0 - r)).powi(2);
assert!((radius2 - r * r).abs() < 1e-7, "distorted line section at {p:?}: radius squared {radius2}");
let radius2 = (p.x.hypot(p.y) - (10.0 - r)).powi(2) + (p.z - (15.0 - r)).powi(2);
assert!((radius2 - r * r).abs() < 1e-7, "distorted arc section at {p:?}: radius squared {radius2}");
}
}
assert_eq!(mitres.len(), 2, "both arc/line corners must be checked");
Ok(())
})
.unwrap();
}
#[test]
fn fillet_partial_mixed_arc_and_line_perimeter_run() {
let body = partial_mixed_run_prism();
@@ -2470,124 +2403,6 @@ fn orientation_mesh_reuses_missing_face_check_at_matching_tolerance() {
}
}
/// A trough whose floor falls about 1° toward a central drain, the fall starting right at the
/// trough edges: four faces meet at each bottom corner (two walls, two fall facets) and at the
/// drain (four facets). A tab on one end makes the body non-convex. The moved planes of four
/// faces don't meet at one point, so each such corner of the cavity becomes two corners joined
/// by a short edge. Checked against the volume integrated by hand.
#[test]
fn shell_where_four_faces_meet_at_a_corner() {
let (w, l, ht, t) = (100.0, 60.0, 40.0, 2.0);
// Drain depth: the long facets fall 1°.
let h = 30.0 * 1f64.to_radians().tan();
let facet = |n: Vec3, p: Vec3| {
let n = n.normalized().unwrap();
HalfSpace { n, d: n.dot(p) }
};
let facets = [
facet(Vec3::new(0.0, -h, -30.0), Vec3::ZERO),
facet(Vec3::new(0.0, h, -30.0), Vec3::new(0.0, l, 0.0)),
facet(Vec3::new(-h, 0.0, -50.0), Vec3::ZERO),
facet(Vec3::new(h, 0.0, -50.0), Vec3::new(w, 0.0, 0.0)),
];
let mut hs = vec![
HalfSpace { n: -Vec3::X, d: 0.0 },
HalfSpace { n: Vec3::X, d: w },
HalfSpace { n: -Vec3::Y, d: 0.0 },
HalfSpace { n: Vec3::Y, d: l },
HalfSpace { n: Vec3::Z, d: ht },
];
hs.extend(facets);
let trough = convex_polyhedron(&hs).unwrap();
let pyramid = w * l * h / 3.0;
assert!(rel(measure(&trough).unwrap().volume, w * l * ht + pyramid) < 1e-9);
let tab = box_solid(Vec3::new(w, 20.0, 20.0), Vec3::new(w + 20.0, 40.0, ht)).unwrap();
let body = boolean(&trough, &tab, BoolOp::Union).unwrap().unwrap();
let s = shell(&body, &[Vec3::new(50.0, 30.0, ht)], t).unwrap();
// The cavity: the walls in by t, above the floor facets moved in by t (midpoint rule; the
// floor is linear between its creases).
let floor = |x: f64, y: f64| facets.iter().map(|f| (f.d - t - f.n.x * x - f.n.y * y) / f.n.z).fold(f64::NEG_INFINITY, f64::max);
let (nx, ny) = (960, 560);
let (dx, dy) = ((w - 2.0 * t) / nx as f64, (l - 2.0 * t) / ny as f64);
let mut cavity = 0.0;
for i in 0..nx {
for j in 0..ny {
cavity += (ht - floor(t + (i as f64 + 0.5) * dx, t + (j as f64 + 0.5) * dy)) * dx * dy;
}
}
let tab_cavity = 20.0 * (20.0 - 2.0 * t) * (20.0 - t);
let want = w * l * ht + pyramid + 8000.0 - cavity - tab_cavity;
let m = measure(&s).unwrap();
assert!(rel(m.volume, want) < 1e-5, "{} vs {want}", m.volume);
}
/// The same trough cut as a pocket into a slab (four faces meet at each concave corner of the
/// pocket floor), shelled with its top open.
#[test]
fn shell_of_a_pocket_whose_floor_falls_to_a_drain() {
let (px, py, pw, pl, top, depth, t) = (20.0, 15.0, 100.0, 60.0, 50.0, 30.0, 3.0);
let h = 30.0 * 1f64.to_radians().tan();
let z0 = top - depth;
let facet = |n: Vec3, p: Vec3| {
let n = n.normalized().unwrap();
HalfSpace { n, d: n.dot(p) }
};
let facets = [
facet(Vec3::new(0.0, -h, -30.0), Vec3::new(px, py, z0)),
facet(Vec3::new(0.0, h, -30.0), Vec3::new(px, py + pl, z0)),
facet(Vec3::new(-h, 0.0, -50.0), Vec3::new(px, py, z0)),
facet(Vec3::new(h, 0.0, -50.0), Vec3::new(px + pw, py, z0)),
];
let mut hs = vec![
HalfSpace { n: -Vec3::X, d: -px },
HalfSpace { n: Vec3::X, d: px + pw },
HalfSpace { n: -Vec3::Y, d: -py },
HalfSpace { n: Vec3::Y, d: py + pl },
HalfSpace { n: Vec3::Z, d: top + 10.0 },
];
hs.extend(facets);
let pocket = convex_polyhedron(&hs).unwrap();
let slab = box_solid(Vec3::ZERO, Vec3::new(140.0, 90.0, top)).unwrap();
let basin = boolean(&slab, &pocket, BoolOp::Cut).unwrap().unwrap();
let pocket_vol = pw * pl * depth + pw * pl * h / 3.0;
assert!(rel(measure(&basin).unwrap().volume, 140.0 * 90.0 * top - pocket_vol) < 1e-9);
let s = shell(&basin, &[Vec3::new(5.0, 5.0, top)], t).unwrap();
// The cavity's columns: from t up to the top, or up to the pocket floor moved down by t
// inside the pocket's walls moved out by t.
let floor = |x: f64, y: f64| facets.iter().map(|f| (f.d + t - f.n.x * x - f.n.y * y) / f.n.z).fold(f64::NEG_INFINITY, f64::max);
let (nx, ny) = (1340, 840);
let (dx, dy) = ((140.0 - 2.0 * t) / nx as f64, (90.0 - 2.0 * t) / ny as f64);
let mut cavity = 0.0;
for i in 0..nx {
for j in 0..ny {
let (x, y) = (t + (i as f64 + 0.5) * dx, t + (j as f64 + 0.5) * dy);
let inside = x > px - t && x < px + pw + t && y > py - t && y < py + pl + t;
let roof = if inside { floor(x, y) } else { top };
cavity += (roof - t) * dx * dy;
}
}
let want = 140.0 * 90.0 * top - pocket_vol - cavity;
let m = measure(&s).unwrap();
assert!(rel(m.volume, want) < 1e-4, "{} vs {want}", m.volume);
}
#[test]
fn shell_open_beside_a_round_as_large_as_the_wall_is_refused() {
// Opening the bottom of a box whose bottom outline is rounded: the cavity's side walls stand
// the thickness in from the outside, where a round at least that large meets the bottom, so
// the rim would have no thickness. Smaller rounds leave a rim.
let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap();
let loop_ = [Vec3::new(20.0, 0.0, 0.0), Vec3::new(40.0, 15.0, 0.0), Vec3::new(20.0, 30.0, 0.0), Vec3::new(0.0, 15.0, 0.0)];
let bottom = [Vec3::new(20.0, 15.0, 0.0)];
for r in [2.0, 2.4] {
let f = fillet(&b, &loop_, r).unwrap();
let e = shell(&f, &bottom, 2.0).unwrap_err();
assert!(e.to_string().starts_with("the operation failed: not supported yet: the rim"), "{r}: {e}");
}
let f = fillet(&b, &loop_, 1.5).unwrap();
assert!(shell(&f, &bottom, 2.0).unwrap().validity().is_empty());
}
#[test]
fn loft_joined_onto_a_box_top_is_one_shell() {
// #396: a loft from a Ø12 circle on the box top (z = 20) to a hexagon at z = 35. The union
+4 -2
View File
@@ -144,12 +144,14 @@ fn thread_display_mesh_stays_on_its_surfaces() {
let [a, b2, c] = t.map(|i| mesh.positions[i as usize]);
let (ra, rb, rcn) = (r(a), r(b2), r(c));
let centre = r((a + b2 + c) * (1.0 / 3.0));
// An end disc is flat: its triangles are its boundary's, and one with its three
// corners on the rim (at r = rc) lies on the disc, not on a cylinder.
let end_disc = [a, b2, c].iter().all(|v| v.z.abs() < 1e-9) || [a, b2, c].iter().all(|v| (v.z - (turns + 2.0) * p).abs() < 1e-9);
for want in [rc, rm] {
if [ra, rb, rcn].iter().all(|x| (x - want).abs() < 1e-4) {
if !end_disc && [ra, rb, rcn].iter().all(|x| (x - want).abs() < 1e-4) {
assert!(centre > want - 2.0 * tol, "{name}: triangle {ti} on the r = {want} cylinder cuts in to {centre}");
}
}
let end_disc = [a, b2, c].iter().all(|v| v.z.abs() < 1e-9) || [a, b2, c].iter().all(|v| (v.z - (turns + 2.0) * p).abs() < 1e-9);
assert!(end_disc || (centre > rc - 2.0 * tol && centre < rm + 1e-6), "{name}: triangle {ti} at radius {centre}, outside {rc}…{rm}");
}
// A mesh within the tolerance of the surfaces is within area × tolerance of the volume.
+8 -8
View File
@@ -1,10 +1,10 @@
# Rust target, SHA-256 of smlib-<target>.tar.gz in the release prebuilt-<SMLIB_REV> of
# tangency-labs/smlib. Written by scripts/fetch-smlib.sh --pin; never edited by hand.
aarch64-apple-darwin 0cc77e26edf71fdd25881bc2b27a37d7eae6e4983939ce7769e47cdd88b7d142
aarch64-pc-windows-msvc f6802ecb6d21bad7c8e23a0371aaa4d79cac9d75f271f00900067a1777353b39
aarch64-unknown-linux-gnu 0c9b9f8fe3522e1baab52d04f8f003da94b73b7837c60d8ec4d7bd8b34d32889
i686-pc-windows-msvc 1a430d114c38010eefbbd0b89cd060d36abc5262dbfafbbb08f09fefc1258c30
wasm32-unknown-unknown 53f03772528182d2cc9398eaaebcae1c643ca6d2ff5553b19db69e713a84579e
x86_64-apple-darwin 26cfc2cd85d049159893972c2dbdcdf08ad4f88e57d54a9e23146e86d4d3b8ca
x86_64-pc-windows-msvc ec9b082bb11a00b25c967a3f4cf8f497d5e69cf6a7f009ecff387d41697f162f
x86_64-unknown-linux-gnu d75936dadf5553e5d3e45b9b8136323285b1ee040fcaf1d6e2df6754c99e02c6
aarch64-apple-darwin 449768fb27dddbc2613bba876e96a762fd4dc36f8ce43e498679a98c3a9c03f1
aarch64-pc-windows-msvc 1ce7c9e59d390c855c8d73688340fb747ae6e00fe969065ba646980735abc447
aarch64-unknown-linux-gnu 014ba0b4734de8fb8665b58394624a68dced523b09a804f2258a3808cfcda7b2
i686-pc-windows-msvc 38ff5885eaba1f0681eb2be777b16fdfdb986ca66c0496c4f4235ec3dc045e84
wasm32-unknown-unknown 7227d3b5f208122d39dfab0b9573efc4037d0ea9fd0bfec6f91dba27a9434fe0
x86_64-apple-darwin cde31baadd1a807f6a58b3ab17815a939940e2bf82ee032c3a526ecf6d0a41d4
x86_64-pc-windows-msvc c0d02f0e0e59c977fd134d872e049d7eb3e027be4ea9c888418fea0cbabd675c
x86_64-unknown-linux-gnu edc4a1e08d3263bafbcd44dbd243a7815ca4d535dc308a89b1844126c0bea613
+1 -1
View File
@@ -1 +1 @@
1ccd461266aa36470d29a5e2634cf6c622830dc8
985faaeed0311d5eaf5e6f091f62ac55c382597c
+1 -1
View File
@@ -16,7 +16,7 @@ use super::{ERR_ARG, RawBrep, new_brep};
pub const CURVE_LINE: i64 = 1;
pub const CURVE_ARC: i64 = 2;
pub const CURVE_NURBS: i64 = 3;
pub const CURVE_MAX_CURVES: usize = 4096;
pub const CURVE_MAX_CURVES: usize = 16_384;
pub const CURVE_MAX_DEGREE: usize = 25;
pub const CURVE_MAX_POINTS: usize = 100_000;
+120 -11
View File
@@ -77,8 +77,11 @@ thread_local! {
/// The inference the cursor snapped to last (label, sketch point), for the hint.
static SNAP: RefCell<Option<(&'static str, Vec2)>> = const { RefCell::new(None) };
static PREV: Cell<Option<Vec2>> = const { Cell::new(None) };
/// Curvature comb teeth (foot, tip) shown while the comb tool is active.
static COMBS: RefCell<Vec<Vec<[Vec3; 2]>>> = const { RefCell::new(Vec::new()) };
/// The curvature combs shown while the comb tool is active: each pick (the command's
/// parameters for the curve or edge clicked) and its combs' teeth (foot, tip).
static COMBS: RefCell<Vec<(Value, Vec<Vec<[Vec3; 2]>>)>> = const { RefCell::new(Vec::new()) };
/// The comb tool's options: comb length (a multiplier on the automatic length) and teeth.
static COMB_OPTIONS: Cell<CombOptions> = const { Cell::new(CombOptions::DEFAULT) };
/// The image file a Canvas or Decal tool places.
static IMAGE: RefCell<Option<String>> = const { RefCell::new(None) };
/// Analysis markers shown while an analysis tool is active: (where, label).
@@ -364,6 +367,117 @@ fn v3(v: &Value) -> Option<Vec3> {
Some(Vec3::new(v.get(0)?.as_f64()?, v.get(1)?.as_f64()?, v.get(2)?.as_f64()?))
}
/// The Curvature Comb tool's options: how long the teeth are, as a multiple of the automatic
/// length (`inspect.curvature_comb`'s `length`), and how many each comb has (`density`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct CombOptions {
pub length: f64,
pub teeth: usize,
}
impl CombOptions {
const DEFAULT: CombOptions = CombOptions { length: 1.0, teeth: 40 };
const LENGTH: std::ops::RangeInclusive<f64> = 0.25..=8.0;
const TEETH: std::ops::RangeInclusive<usize> = 4..=200;
}
/// The comb tool's options now.
pub(crate) fn comb_options() -> CombOptions {
COMB_OPTIONS.with(Cell::get)
}
/// The combs shown, each as its teeth (foot, tip).
#[cfg(test)]
pub(crate) fn shown_combs() -> Vec<Vec<[Vec3; 2]>> {
COMBS.with(|c| c.borrow().iter().flat_map(|(_, combs)| combs.clone()).collect())
}
/// Run the comb command for `pick` with the tool's options: its combs' teeth (foot, tip), or
/// nothing when it fails (the status line says why).
fn comb_teeth(app: &mut SolveApp, pick: &Value) -> Option<Vec<Vec<[Vec3; 2]>>> {
let options = comb_options();
let mut params = pick.clone();
params["density"] = json!(options.teeth);
params["length"] = json!(options.length);
let v = app.run("inspect.curvature_comb", params).ok()?;
Some(
v["combs"]
.as_array()
.into_iter()
.flatten()
.map(|comb| comb["teeth"].as_array().into_iter().flatten().filter_map(|t| Some([v3(t.get(0)?)?, v3(t.get(1)?)?])).collect())
.collect(),
)
}
/// Show the comb of `pick` (the comb command's parameters for a curve or an edge) beside those
/// already shown.
fn add_comb(app: &mut SolveApp, pick: Value) {
if let Some(teeth) = comb_teeth(app, &pick) {
COMBS.with(|c| c.borrow_mut().push((pick, teeth)));
}
}
/// Change the comb tool's options and run the comb again on every curve already shown.
pub(crate) fn set_comb_options(app: &mut SolveApp, options: CombOptions) {
let options = CombOptions {
length: options.length.clamp(*CombOptions::LENGTH.start(), *CombOptions::LENGTH.end()),
teeth: options.teeth.clamp(*CombOptions::TEETH.start(), *CombOptions::TEETH.end()),
};
if COMB_OPTIONS.with(|o| o.replace(options)) == options {
return;
}
let picks: Vec<Value> = COMBS.with(|c| c.borrow().iter().map(|(pick, _)| pick.clone()).collect());
let shown: Vec<(Value, Vec<Vec<[Vec3; 2]>>)> = picks.into_iter().filter_map(|pick| comb_teeth(app, &pick).map(|teeth| (pick, teeth))).collect();
COMBS.with(|c| *c.borrow_mut() = shown);
}
/// The comb tool's options at the top left of the free viewport while it runs (the analysis and
/// continuity legends keep the lower left): Comb length and Teeth. Changing either draws the
/// combs shown again.
fn comb_options_card(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) {
if app.tool.as_ref().map(|t| t.cmd) != Some("inspect.curvature_comb") {
return;
}
let tk = crate::theme::Tokens::get();
let available = crate::shell::workspace_content(app, crate::shell::content_rect(app, proj.rect));
let width = tk.form_card_width.min(available.width() - 2.0 * tk.space_16).max(0.0);
let mut options = comb_options();
let (length_tip, teeth_tip) = (app.tr("ui.comb_length_tip").to_string(), app.tr("ui.comb_teeth_tip").to_string());
let shown = crate::ui_kit::Container::new(ctx, crate::ui_kit::Surface::Canvas)
.area(egui::Id::new("sc_comb_options"))
.fixed_pos(available.left_top() + egui::vec2(tk.space_16, tk.space_16))
.order(egui::Order::Foreground)
.show(ctx, |ui| {
crate::ui_kit::Container::popup_frame(ui.style()).fill(tk.dialog_body).inner_margin(tk.space_8).show(ui, |ui| {
crate::ui_kit::scope(ui, |ui| {
ui.set_width(width);
let length = crate::ui_kit::row(ui, "ui.comb_length", |ui| {
let format = |v: f64| format!("{v:.2}\u{d7}");
crate::ui_kit::slider(
ui,
&mut options.length,
CombOptions::LENGTH,
crate::ui_kit::Slider { step: Some(0.25), format, ..Default::default() },
)
});
length.on_hover_text(&length_tip);
let teeth = crate::ui_kit::row(ui, "ui.comb_teeth", |ui| {
crate::ui_kit::slider(
ui,
&mut options.teeth,
CombOptions::TEETH,
crate::ui_kit::Slider { integer: true, format: |v| format!("{v:.0}"), ..Default::default() },
)
});
teeth.on_hover_text(&teeth_tip);
});
});
});
crate::scenario::publish_rect("comb_options", shown.response.rect);
set_comb_options(app, options);
}
/// Curvature combs: teeth and the envelope through their tips.
fn combs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {
if app.tool.as_ref().map(|t| t.cmd) != Some("inspect.curvature_comb") {
@@ -372,7 +486,7 @@ fn combs(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {
}
let tk = crate::theme::Tokens::get();
COMBS.with(|c| {
for comb in c.borrow().iter() {
for comb in c.borrow().iter().flat_map(|(_, combs)| combs) {
let mut tips: Vec<Pos2> = Vec::new();
for [a, b] in comb {
let (Some(p), Some(q)) = (proj.to_screen(*a), proj.to_screen(*b)) else { continue };
@@ -837,14 +951,8 @@ pub fn on_click(app: &mut SolveApp, tool: &mut Tool, proj: &Proj, pos: Pos2) {
Hit::Edge { mid, .. } => Some(json!({"edges": [[mid.x, mid.y, mid.z]]})),
_ => None,
});
if let Some(p) = params
&& let Ok(v) = app.run(cmd, p)
{
for comb in v["combs"].as_array().into_iter().flatten() {
let teeth: Vec<[Vec3; 2]> =
comb["teeth"].as_array().into_iter().flatten().filter_map(|t| Some([v3(t.get(0)?)?, v3(t.get(1)?)?])).collect();
COMBS.with(|c| c.borrow_mut().push(teeth));
}
if let Some(p) = params {
add_comb(app, p);
}
}
Mode::ModelRef if cmd == "inspect.isocurve" => {
@@ -1528,6 +1636,7 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P
glyphs(app, painter, proj, ui.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(proj.rect)));
snap_hint(app, painter, proj);
combs(app, painter, proj);
comb_options_card(app, ui.ctx(), proj);
if DEFERRED.with(|d| d.replace(false)) {
analysis(app, "inspect.center_of_mass", json!({}));
}
@@ -607,3 +607,46 @@ fn frame_rate_readout_stays_beside_a_right_pane() {
in_corner(&h);
}
}
/// The Curvature Comb tool's options card (Comb length, Teeth) shows while the tool runs, and
/// moving either slider draws the combs already shown again: their teeth as long as the length
/// says (a multiple of the automatic length), as many as Teeth says. Using the card picks nothing.
#[test]
fn comb_options_draw_the_combs_shown_again() {
use crate::sketch_tools::{comb_options, shown_combs};
let mut h = Harness::new();
h.app.home.open = false;
h.app.run("solid.cylinder", json!({"radius": 10, "height": 20})).unwrap();
h.settle();
h.step(&json!({"start": "inspect.curvature_comb"})).unwrap();
h.frame();
assert!(crate::scenario::rect_of("comb_options").is_some(), "the options card is drawn");
assert_eq!((comb_options().length, comb_options().teeth), (1.0, 40));
h.step(&json!({"click": {"world": [10, 0, 20]}})).unwrap();
let combs = shown_combs();
assert_eq!(combs.len(), 1, "{:?}", h.app.status);
assert_eq!(combs[0].len(), 40);
let tooth = |c: &[[solidcraft_engine::geom::Vec3; 2]]| c[0][0].dist(c[0][1]);
let auto = tooth(&combs[0]);
assert!(auto > 0.0);
let slider = |name: &str| crate::scenario::rect_of(&format!("dialog:slider_track:{name}")).unwrap_or_else(|| panic!("no slider {name}"));
// Comb length to its right end: 8 × the automatic length.
let track = slider("ui.comb_length");
h.step(&json!({"drag": [[track.center().x, track.center().y], [track.right() + 40.0, track.center().y]]})).unwrap();
h.frame();
assert_eq!(comb_options().length, 8.0);
let combs = shown_combs();
assert_eq!(combs.len(), 1, "the card's drag picked nothing");
assert!((tooth(&combs[0]) - 8.0 * auto).abs() < 1e-9 * auto, "{} vs 8 × {auto}", tooth(&combs[0]));
// Teeth to its left end: 4.
let track = slider("ui.comb_teeth");
h.step(&json!({"drag": [[track.center().x, track.center().y], [track.left() - 40.0, track.center().y]]})).unwrap();
h.frame();
assert_eq!(comb_options().teeth, 4);
let combs = shown_combs();
assert_eq!((combs.len(), combs[0].len()), (1, 4));
// The tool ends: the combs and the card go.
h.step(&json!({"key": "Escape"})).unwrap();
h.frames(2);
assert!(shown_combs().is_empty() && crate::scenario::rect_of("comb_options").is_none());
}
+6 -3
View File
@@ -322,9 +322,12 @@ accelerations are finite differences between samples, central inside and one-sid
so they are as smooth as the samples are dense (up to 1000, one per step by default). Angles are
unwrapped, so a joint that turns on past half a turn keeps counting.
`motion.interference {study, occurrences?, against?, contact_sets?, samples?}` answers each
colliding pair with its `first_step`, `last_step`, the `steps` ranges where they overlap, how
far into each other (`depth_mm`, the most at `deepest_step`) and their shared `volume_mm3`
there (null when it is not cheap to work out). It plays the study as `motion.play` does, but
colliding pair with its `first_step`, `last_step`, the `steps` ranges where they overlap, the
most volume they share at a sample (`volume_mm3`, worked out exactly from the bodies), the first
sample sharing that much (`deepest_step`) and how far into each other they reach (`depth_mm`, an
estimate from points of the bodies' contact meshes). When the volume could not be worked out at
every sample they overlap (more than 16 colliding pairs, or past the check's 256 body
intersections), `volume_mm3` and `deepest_step` are null and `not_measured` says why. It plays the study as `motion.play` does, but
contact sets don't stop it, and parts are tested at the samples only: a part that passes right
through another between two samples is missed. Parts are told apart by occurrence, as contact
sets tell them apart: an occurrence inside a sub-assembly placed twice is one part, so its two
+19 -16
View File
@@ -8,25 +8,28 @@ description: "Use when writing, placing or running tests in SolidCraft: a regres
The long form is `docs/book/src/dev/testing.md`.
## Placement
- A regression test goes into the existing test file for its area (booleans, blends, shell, sweep, STEP, naming, ...), never a new file named after the bug (#3226).
- Engine tests sit next to the code or in `*_tests.rs` files; they measure the result (volume, area, face/edge/vertex counts) against a value you can derive.
- UI scenarios are JSON in `crates/ui-egui/tests/scenarios/*.json`; a new file is picked up automatically. Put `{"pending": "why"}` in a scenario that records a bug before it is fixed, and remove it in the fixing PR.
- Reference tests are `tests/oracle/<case>/recipe.json` with an `expected.json` beside it, run by `cargo xtask oracle`. Expected values are worked out in closed form (`tools/oracle-analytic/`) or computed by FreeCAD run as a separate program (`tools/freecad-oracle/`). A case that fails on a known bug names its issue (`"known_failure": "#123"`). Never change an expected value to match SolidCraft's output, and never take one from a commercial CAD product.
- Crash fixes: a regression test, started from the crash report's `design.solidcraft` and `replay.json` (`skills/solidcraft-crash-safety/SKILL.md`).
- A regression test goes into its area's existing test file (booleans, blends, shell, STEP, naming, ...), never a new file named after the bug (#3226).
- Engine tests sit next to the code or in `*_tests.rs` files, measured against a value you can derive.
- UI scenarios are JSON in `crates/ui-egui/tests/scenarios/*.json`. Put `{"pending": "why"}` in a scenario that records a bug before it is fixed, and remove it in the fixing PR.
- Reference tests are `tests/oracle/<case>/recipe.json` with an `expected.json` beside it, run by `cargo xtask oracle`, expected values in closed form (`tools/oracle-analytic/`) or from FreeCAD as a separate program (`tools/freecad-oracle/`). A known failure names its issue (`"known_failure": "#123"`). Never change an expected value to match SolidCraft's output, and never take one from a commercial CAD product.
- Crash fixes: a regression test from the report's `design.solidcraft` and `replay.json` (`skills/solidcraft-crash-safety/SKILL.md`).
## Unit test or rig case
- Unit tests assert the code's logic: which edges a chain picks, name resolution, history labels, refusal wording, hostile input, parsing and saving (`corner_rounds_larger_than_their_faces_are_too_large`: per-edge radii, which no command takes, refused as `TooLarge`).
- The rig (`tests/kernel-cases/`) asserts geometry: exact volumes, shapes, seam continuity, geometric refusals, through commands with a hand-derived answer, so it survives a kernel swap (`fillets/190-fillet-disc-rim-past-its-2mm-wall`). A test doing both keeps only its logic.
## A failing test needs its fix
A failing test without its fix cannot merge: it turns `main` red for everyone. Include the fix in the same PR, or mark the test `#[ignore = "fails until #123 is fixed"]` and remove that line in the PR that fixes it.
A failing test cannot merge without its fix (it turns `main` red): include the fix, or mark the test `#[ignore = "fails until #123 is fixed"]` and remove that line in the PR that fixes it.
## Running
- `cargo xtask test` builds with the `ci` profile and runs every test binary at once; arguments after `--` go to each binary (`cargo xtask test -- shell`). Use the `ci` profile: it builds several times faster than `--release`, and debug assertions are off because truck's reject valid geometry. If a test fails only in a plain debug build, say so in the PR.
- `SOLIDCRAFT_TEST_JOBS=N` bounds concurrent commands on a shared machine.
- `cargo xtask ci` is the gate before a commit: fmt, assets, icons, licences, lists, layers, ui-containers, clippy `-D warnings`, tests and the wasm check.
- Every test runs in its own process: do not rely on state left by another test, or on wall-clock timing.
- `cargo xtask test` builds with the `ci` profile and runs every test binary at once; arguments after `--` go to each binary (`cargo xtask test -- shell`). It builds several times faster than `--release`; a test failing only in a debug build: say so in the PR.
- `SOLIDCRAFT_TEST_JOBS=N` bounds concurrent commands. `cargo xtask ci` is the gate before a commit (fmt, lints, clippy `-D warnings`, tests, wasm).
- Tests run in their own processes: no shared state, no wall-clock timing.
## Goldens, matrices and skipped tests
- The reference for what the kernel builds is the kernel-cases ladder (`tests/kernel-cases/ladder/`, `cargo xtask kernel-cases --ladder`, `docs/kernel-ladder.md`).
- Kernel PRs run `kernel-rig.yml`: the areas the diff reaches (`PATHS`) against `KNOWN_FAILING`, the ladder against its golden. In the same PR a fix removes its line, a new failing case adds one, a changed ladder result is re-recorded (`--record "why"`), a new command gets a case or an `EXEMPT` line; see `tests/kernel-cases/README.md`.
- Maintainers' PRs run the native, GPU path and reference tests on the affected packages; others wait for `approved-for-ci`. `release-gate.yml` runs everything in full before develop replaces main.
- The action matrix is a ratchet: record a newly passing action with `cargo xtask action-matrix --bless` (`docs/action-matrix.md`).
- Pull requests skip a few heavy tests, which run in the merge queue, nightly and on `main`. Check that validation after merging. The list is in `.config/nextest.toml` and the testing page.
- Mutation testing finds what the suites miss: `docs/mutation-testing.md`.
- The kernel's reference is the ladder (`tests/kernel-cases/ladder/`, `cargo xtask kernel-cases --ladder`, `docs/kernel-ladder.md`).
- Kernel PRs run `kernel-rig.yml` (areas by `PATHS` against `KNOWN_FAILING`, the ladder against its golden). In the same PR a fix drops its line, a new failing case adds one, a changed ladder result is re-recorded (`--record "why"`), a new command gets a case or an `EXEMPT` line (`tests/kernel-cases/README.md`).
- Maintainers' PRs run native, GPU and reference tests on affected packages; others wait for `approved-for-ci`. `release-gate.yml` runs all before develop replaces main.
- The action matrix is a ratchet: bless a newly passing action (`cargo xtask action-matrix --bless`, `docs/action-matrix.md`).
- PRs skip a few heavy tests, run in the merge queue, nightly and on `main`. Check them after merging (`.config/nextest.toml`).
- Mutation testing: `docs/mutation-testing.md`.
@@ -2,3 +2,5 @@
# rig gate (.github/workflows/kernel-rig.yml) fails on a case that fails and is not listed here,
# and on a listed case that passes: a fix removes its line in the same pull request.
# Baseline: not seeded yet; seeded from a develop run after the SMLib pin bump.
cov-patch-g1-caps-an-opened-tube-end not supported yet: the general fill refuses the cap (it folds)
cov-patch-g2-caps-an-opened-tube-end not supported yet: the general fill refuses the cap (it folds)
@@ -0,0 +1,19 @@
{
"sources": [
"tangency-labs/solidcraft#759"
],
"what": "a cylinder r10 x 30 with its top face taken off, the open rim patched g1 (Tangent) and stitched: a dome over the tube that closes it",
"source": "invariants",
"method": "the patch meets the cylinder's wall along the rim circle: at G1 the dome's tangent plane is the wall's (vertical), so the cap rises from the rim. The dome's shape is the fill's own: no volume; one closed valid solid whose rim seam reaches g1 is the right answer.",
"body_count": 1,
"continuity": {
"order": "g1",
"edges": [
[
10,
0,
30
]
]
}
}
@@ -0,0 +1,50 @@
{
"commands": [
{
"command": "solid.cylinder",
"params": {
"radius": 10,
"height": 30,
"body_name": "Tube"
}
},
{
"command": "face.delete",
"params": {
"body": "Tube",
"faces": [
[
0,
0,
30
]
],
"heal": false
}
},
{
"command": "surface.patch",
"params": {
"body": "Tube",
"edges": [
[
10,
0,
30
]
],
"continuity": "g1",
"body_name": "Cap"
}
},
{
"command": "surface.stitch",
"params": {
"bodies": [
"Tube",
"Cap"
]
}
}
]
}
@@ -0,0 +1,19 @@
{
"sources": [
"tangency-labs/solidcraft#759"
],
"what": "a cylinder r10 x 30 with its top face taken off, the open rim patched g2 (Curvature) and stitched: a dome over the tube that closes it",
"source": "invariants",
"method": "the patch meets the cylinder's wall along the rim circle: at G2 the dome's tangent plane is the wall's (vertical), so the cap rises from the rim, and its curvature across the rim is the wall's (0 along the axis). The dome's shape is the fill's own: no volume; one closed valid solid whose rim seam reaches g2 is the right answer.",
"body_count": 1,
"continuity": {
"order": "g2",
"edges": [
[
10,
0,
30
]
]
}
}
@@ -0,0 +1,50 @@
{
"commands": [
{
"command": "solid.cylinder",
"params": {
"radius": 10,
"height": 30,
"body_name": "Tube"
}
},
{
"command": "face.delete",
"params": {
"body": "Tube",
"faces": [
[
0,
0,
30
]
],
"heal": false
}
},
{
"command": "surface.patch",
"params": {
"body": "Tube",
"edges": [
[
10,
0,
30
]
],
"continuity": "g2",
"body_name": "Cap"
}
},
{
"command": "surface.stitch",
"params": {
"bodies": [
"Tube",
"Cap"
]
}
}
]
}
@@ -0,0 +1,25 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "all four top rim edges of a basin whose walls all slope 10 over 20, its front rim 1 mm wide, chamfered 0.5, mitred at the rim's corners",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 11)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 140333.333333. Each blend's section at height z spans from its wall to its arc (or chamfer line), inside its rim; its edge runs between its neighbours' walls (the sloped end walls extended), so it takes Int width(z) length(z) dz. At a re-entrant corner of two picked edges the blends meet in a mitre (the owner's ruling of 2026-10-30): each runs on past the corner and the quadrant beyond both walls loses what both take, Int width_1(z) width_2(z) dz. Removed 24.455545. V = 140308.877788",
"body_count": 1,
"volume_mm3": 140308.87778784672,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
}
}
@@ -0,0 +1,105 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
11
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
1,
30
],
[
80,
27,
30
],
[
50,
50,
30
],
[
20,
27,
30
]
],
"distance": 0.5
}
}
]
}
@@ -0,0 +1,10 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "all four top rim edges of a basin whose walls all slope 10 over 20, its front rim 1 mm wide, chamfered 2: the front chamfer's leg runs off the rim, so it is refused, naming the largest distance that fits",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 11)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 140333.333333. The front chamfer's leg on the 1 mm rim would reach y = -1, over the slab's front face: refused (the owner's ruling of 2026-10-30).",
"outcome": "refused",
"refusal": "the largest distance that fits is"
}
@@ -0,0 +1,105 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
11
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
1,
30
],
[
80,
27,
30
],
[
50,
50,
30
],
[
20,
27,
30
]
],
"distance": 2
}
}
]
}
@@ -0,0 +1,10 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 0.5 mm front rim of a sloped basin's top chamfered 4: its leg on the top runs off the rim over the slab's front face, so it is refused, naming the largest distance that fits",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. The chamfer's leg on the rim's top (0.5 mm wide) would reach y = -3.5, off the rim and over the slab's front face y = 0, lowering that face: the owner's ruling of 2026-10-30 refuses a chamfer whose leg runs off the face beside its edge, naming the largest distance that fits.",
"outcome": "refused",
"refusal": "the largest distance that fits is"
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
0.5
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
0.5,
30
]
],
"distance": 4
}
}
]
}
@@ -0,0 +1,10 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 0.5 mm front rim of a sloped basin's top chamfered 0.5: as wide as the rim, the chamfer would use the rim's top up: refused",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. A chamfer as wide as the face beside its edge uses it up: full-width chamfers are refused (the owner's ruling of 2026-10-30).",
"outcome": "refused",
"refusal": "the largest distance that fits is"
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
0.5
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
0.5,
30
]
],
"distance": 0.5
}
}
]
}
@@ -0,0 +1,25 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 0.5 mm front rim of a sloped basin's top chamfered 0.25, half the rim's width: it fits",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. The chamfer's triangle in (y, z): the edge (0.5, 30), its leg on the top to (0.25, 30) and d down the wall to (0.5 + d (20-0.5)/L, 30 - 20 d/L), L = sqrt((20-0.5)^2 + 400). At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed (shoelace for the area and its first moment) 1.341165. V = 144265.325501",
"body_count": 1,
"volume_mm3": 144265.32550144705,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
}
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
0.5
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
0.5,
30
]
],
"distance": 0.25
}
}
]
}
@@ -0,0 +1,10 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 1 mm front rim of a sloped basin's top chamfered 2: its leg on the top runs off the rim over the slab's front face, so it is refused, naming the largest distance that fits",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's leg on the rim's top (1 mm wide) would reach y = -1, off the rim and over the slab's front face y = 0, lowering that face: the owner's ruling of 2026-10-30 refuses a chamfer whose leg runs off the face beside its edge, naming the largest distance that fits.",
"outcome": "refused",
"refusal": "the largest distance that fits is"
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
1,
30
]
],
"distance": 2
}
}
]
}
@@ -0,0 +1,10 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 1 mm front rim of a sloped basin's top chamfered 3: its leg on the top runs off the rim over the slab's front face, so it is refused, naming the largest distance that fits",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's leg on the rim's top (1 mm wide) would reach y = -2, off the rim and over the slab's front face y = 0, lowering that face: the owner's ruling of 2026-10-30 refuses a chamfer whose leg runs off the face beside its edge, naming the largest distance that fits.",
"outcome": "refused",
"refusal": "the largest distance that fits is"
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
1,
30
]
],
"distance": 3
}
}
]
}
@@ -0,0 +1,10 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 1 mm front rim of a sloped basin's top chamfered 1: as wide as the rim, the chamfer would use the rim's top up: refused",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. A chamfer as wide as the face beside its edge uses it up: full-width chamfers are refused (the owner's ruling of 2026-10-30).",
"outcome": "refused",
"refusal": "the largest distance that fits is"
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
1,
30
]
],
"distance": 1
}
}
]
}
@@ -0,0 +1,25 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 1 mm front rim of a sloped basin's top chamfered 0.5, half the rim's width: it fits",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The chamfer's triangle in (y, z): the edge (1, 30), its leg on the top to (0.5, 30) and d down the wall to (1 + d (20-1)/L, 30 - 20 d/L), L = sqrt((20-1)^2 + 400). At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed (shoelace for the area and its first moment) 5.426545. V = 144527.906788",
"body_count": 1,
"volume_mm3": 144527.9067880851,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
}
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.chamfer",
"params": {
"edges": [
[
50,
1,
30
]
],
"distance": 0.5
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "all four top rim edges of a basin whose walls all slope 10 over 20, its front rim 1 mm wide, rounded R 0.5, mitred at the rim's corners",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 11)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 140333.333333. Each blend's section at height z spans from its wall to its arc (or chamfer line), inside its rim; its edge runs between its neighbours' walls (the sloped end walls extended), so it takes Int width(z) length(z) dz. At a re-entrant corner of two picked edges the blends meet in a mitre (the owner's ruling of 2026-10-30): each runs on past the corner and the quadrant beyond both walls loses what both take, Int width_1(z) width_2(z) dz. Removed 3.517697. V = 140329.815636",
"body_count": 1,
"volume_mm3": 140329.8156362336,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,105 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
11
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
1,
30
],
[
80,
27,
30
],
[
50,
50,
30
],
[
20,
27,
30
]
],
"radius": 0.5
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "all four top rim edges of a basin whose walls all slope 10 over 20, its front rim 1 mm wide, rounded R 4, mitred at the rim's corners: past the rim the front round runs over the slab's front face and is cut from the slab",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 11)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 140333.333333. Each blend's section at height z spans from its wall to its arc (or chamfer line), the front one not past y = 0, the slab's face; its edge runs between its neighbours' walls (the sloped end walls extended), so it takes Int width(z) length(z) dz. At a re-entrant corner of two picked edges the blends meet in a mitre (the owner's ruling of 2026-10-30): each runs on past the corner and the quadrant beyond both walls loses what both take, Int width_1(z) width_2(z) dz. Removed 218.598188. V = 140114.735145",
"body_count": 1,
"volume_mm3": 140114.73514508773,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,105 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
11
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
1,
30
],
[
80,
27,
30
],
[
50,
50,
30
],
[
20,
27,
30
]
],
"radius": 4
}
}
]
}
@@ -0,0 +1,13 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "a 40 x 30 x 10 block with a 5 x 5 x 3 notch at a bottom corner, its top outline rounded R7: the round uses up the 7 mm wall over the notch",
"source": "analytic",
"method": "block 12000 less the notch 75: 11925. The outline's mitred round takes (1-pi/4) r^2 (140 - 8c), c = r (10-3pi)/(3(4-pi)) (the prisms ending on the 45 deg mitres). R7 reaches z = 3, the notch's top: it uses the 7 mm wall over the notch up and none of it lies in the notch. V = 10584.365507",
"body_count": 1,
"volume_mm3": 10584.365507210565,
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,55 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 40,
"width": 30,
"height": 10
}
},
{
"command": "solid.box",
"params": {
"length": 6,
"width": 6,
"height": 4,
"corner": [
35,
-1,
-1
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
20,
0,
10
],
[
40,
15,
10
],
[
20,
30,
10
],
[
0,
15,
10
]
],
"radius": 7,
"tangent_chain": false
}
}
]
}
@@ -0,0 +1,13 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "a 40 x 30 x 10 block with a 5 x 5 x 3 notch at a bottom corner, its top outline rounded R8: the round runs past the 7 mm wall over the notch into the notch and is cut by it",
"source": "analytic",
"method": "block 12000 less the notch 75: 11925. The outline's mitred round takes (1-pi/4) r^2 (140 - 8c), c = r (10-3pi)/(3(4-pi)) (the prisms ending on the 45 deg mitres). R8 reaches z = 2, into the notch [35,40] x [0,5] x [0,3]: at z = 2 + t each round's strip is g = 8 - sqrt(64 - t^2) in from its face, the two strips' union in the notch's 5 x 5 square 2(5g - g^2/2); its part in the notch, Int_0^1 2(5g - g^2/2) dt = 0.208039, is not material and is not taken. V = 10198.718039",
"body_count": 1,
"volume_mm3": 10198.718038815705,
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,55 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 40,
"width": 30,
"height": 10
}
},
{
"command": "solid.box",
"params": {
"length": 6,
"width": 6,
"height": 4,
"corner": [
35,
-1,
-1
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
20,
0,
10
],
[
40,
15,
10
],
[
20,
30,
10
],
[
0,
15,
10
]
],
"radius": 8,
"tangent_chain": false
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 0.5 mm front rim of a sloped basin's top rounded R0.25: it fits on the rim",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. The wall leans (20-0.5) out over 20 down: the faces meet at 134.2748 deg, so the round's contacts lie r cot(t/2) = 0.105412 from the edge, on the top at y = 0.394588 and down the wall, its centre under the top contact at z = 30 - r. At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed 0.084803. V = 144266.581864",
"body_count": 1,
"volume_mm3": 144266.58186392413,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
0.5
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
0.5,
30
]
],
"radius": 0.25
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "all four of the top rim edges of a sloped basin with a 0.5 mm front rim rounded R4, mitred at the rim's corners: past the thin rim the front round runs over the slab's front face and is cut from the slab",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. Each blend's section at height z spans from its wall to its arc (or chamfer line), the front one not past y = 0, the slab's face; its edge runs between its neighbours' walls (the sloped end walls extended), so it takes Int width(z) length(z) dz. At a re-entrant corner of two picked edges the blends meet in a mitre (the owner's ruling of 2026-10-30): each runs on past the corner and the quadrant beyond both walls loses what both take, Int width_1(z) width_2(z) dz. Removed 182.348561. V = 144084.318105",
"body_count": 1,
"volume_mm3": 144084.31810540144,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,105 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
0.5
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
0.5,
30
],
[
80,
27,
30
],
[
50,
50,
30
],
[
20,
27,
30
]
],
"radius": 4
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 0.5 mm front rim of a sloped basin's top rounded R4: the round runs over the rim's top past the slab's front face (a cliff) and is cut from the slab",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 0.5)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144266.666667. The wall leans (20-0.5) out over 20 down: the faces meet at 134.2748 deg, so the round's contacts lie r cot(t/2) = 1.686591 from the edge, on the top at y = -1.186591 and down the wall, its centre under the top contact at z = 30 - r. The round is built as if the top went on past y = 0 and cut from the slab (a round past a face on its tangent side builds: the owner's ruling of 2026-10-30), so its section counts only at y >= 0. At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed 17.395317. V = 144249.271350",
"body_count": 1,
"volume_mm3": 144249.27134953788,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
0.5
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
0.5,
30
]
],
"radius": 4
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "all four of the top rim edges of a sloped basin with a 1 mm front rim rounded R0.5, mitred at the rim's corners",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. Each blend's section at height z spans from its wall to its arc (or chamfer line), inside its rim; its edge runs between its neighbours' walls (the sloped end walls extended), so it takes Int width(z) length(z) dz. At a re-entrant corner of two picked edges the blends meet in a mitre (the owner's ruling of 2026-10-30): each runs on past the corner and the quadrant beyond both walls loses what both take, Int width_1(z) width_2(z) dz. Removed 2.905424. V = 144530.427909",
"body_count": 1,
"volume_mm3": 144530.42790890092,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,105 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
1,
30
],
[
80,
27,
30
],
[
50,
50,
30
],
[
20,
27,
30
]
],
"radius": 0.5
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the 1 mm front rim of a sloped basin's top rounded R0.5: it fits on the rim",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. The wall leans (20-1) out over 20 down: the faces meet at 133.5312 deg, so the round's contacts lie r cot(t/2) = 0.214656 from the edge, on the top at y = 0.785344 and down the wall, its centre under the top contact at z = 30 - r. At height z the blend runs between the sloped end walls x = 20 + (30-z)/2 and 80 - (30-z)/2 extended, which cut it: its length there is 30 + z, so it takes Int Int (30 + z) dy dz over its section (y, z). Removed 0.356729. V = 144532.976604",
"body_count": 1,
"volume_mm3": 144532.976604295,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,90 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
1,
30
]
],
"radius": 0.5
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "the front and right of the top rim edges of a sloped basin with a 1 mm front rim rounded R4, mitred at the rim's corners: past the thin rim the front round runs over the slab's front face and is cut from the slab",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. Each blend's section at height z spans from its wall to its arc (or chamfer line), the front one not past y = 0, the slab's face; its edge runs between its neighbours' walls (the sloped end walls extended), so it takes Int width(z) length(z) dz. At a re-entrant corner of two picked edges the blends meet in a mitre (the owner's ruling of 2026-10-30): each runs on past the corner and the quadrant beyond both walls loses what both take, Int width_1(z) width_2(z) dz. Removed 72.136985. V = 144461.196348",
"body_count": 1,
"volume_mm3": 144461.19634789118,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,95 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
1,
30
],
[
80,
27,
30
]
],
"radius": 4
}
}
]
}
@@ -0,0 +1,28 @@
{
"sources": [
"tangency-labs/solidcraft#1080"
],
"what": "all four of the top rim edges of a sloped basin with a 1 mm front rim rounded R4, mitred at the rim's corners: past the thin rim the front round runs over the slab's front face and is cut from the slab",
"source": "analytic",
"method": "slab 100 x 60 x 30 less the loft from the rectangle (20, 1)-(80, 50) at z = 30 to (30, 20)-(70, 40) at z = 10 (planar walls, a prismatoid: 20/6 (A_top + A_bottom + 4 A_mid)): V0 = 144533.333333. Each blend's section at height z spans from its wall to its arc (or chamfer line), the front one not past y = 0, the slab's face; its edge runs between its neighbours' walls (the sloped end walls extended), so it takes Int width(z) length(z) dz. At a re-entrant corner of two picked edges the blends meet in a mitre (the owner's ruling of 2026-10-30): each runs on past the corner and the quadrant beyond both walls loses what both take, Int width_1(z) width_2(z) dz. Removed 186.007516. V = 144347.325818",
"body_count": 1,
"volume_mm3": 144347.32581768231,
"bbox": {
"min": [
0,
0,
0
],
"max": [
100,
60,
30
]
},
"tolerance": {
"rel": 1e-06
},
"continuity": {
"order": "g1"
}
}
@@ -0,0 +1,105 @@
{
"commands": [
{
"command": "solid.box",
"params": {
"length": 100,
"width": 60,
"height": 30,
"body_name": "Slab"
}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 30,
"name": "Top"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
20,
1
],
"p1": [
80,
50
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "sketch.create",
"params": {
"plane": "XY",
"offset": 10,
"name": "Bottom"
}
},
{
"command": "sketch.rectangle.two_point",
"params": {
"p0": [
30,
20
],
"p1": [
70,
40
]
}
},
{
"command": "sketch.finish",
"params": {}
},
{
"command": "solid.loft",
"params": {
"sections": [
{
"sketch": "Top"
},
{
"sketch": "Bottom"
}
],
"operation": "cut"
}
},
{
"command": "solid.fillet",
"params": {
"edges": [
[
50,
1,
30
],
[
80,
27,
30
],
[
50,
50,
30
],
[
20,
27,
30
]
],
"radius": 4
}
}
]
}
Loaded 100 of 325 files, more files were not shown because too many files have changed in this diff. Show more