From 4cd4ebfa50f8f861e309396a29db47ad5a1c4eac Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:41:24 -0400 Subject: [PATCH] Wave 314/509: kernel: a planar sheet's loop splits where it passes one vertex twice (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 00faac965 jyviko: kernel: a planar sheet's loop splits where it passes one vertex twice - 5d25684a1 jyviko: sheet tests: the flat pattern as SMLib's exact 2D boolean makes it - 52343ba23 jyviko: Robustness tests: a round's tangent chain and the lid's closed-form volume - bc6d31e60 jyviko: GPU tests build their designs with SMLib, and the GPU jobs fetch it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- .github/workflows/ci.yml | 6 ++ crates/doc/src/sheet.rs | 31 ++++++---- crates/engine/src/boolean_regression_tests.rs | 15 ++++- crates/engine/src/tests/robustness.rs | 18 ++++-- crates/gpu/Cargo.toml | 5 +- crates/kernel/src/prism.rs | 61 +++++++++++++------ .../lid_ribs_flush_with_window.json | 2 +- 7 files changed, 99 insertions(+), 39 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba5596ecf..740ab4c94 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -593,6 +593,9 @@ jobs: with: key: native-gpu save-if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop') && matrix.shard == 1 }} + - name: Fetch SMLib (crates/smlib/SMLIB_REV) + shell: bash + run: scripts/fetch-smlib.sh - name: Set up compiler cache uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: @@ -846,6 +849,9 @@ jobs: with: key: windows-fxc save-if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop' }} + - name: Fetch SMLib (crates/smlib/SMLIB_REV) + shell: bash + run: scripts/fetch-smlib.sh # One test at a time: WARP's shader JIT crashes now and then (a null read in # d3d10warp.dll's JIT optimizer, about 1 run in 60) when several devices compile compute # pipelines at once, which the parallel tests do. Minidumps showed it in WARP itself, not diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 0a9ec0dc9..00c8edff2 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -5425,9 +5425,14 @@ mod tests { let expected = (6000.0 - std::f64::consts::PI * 120.0) * 2.5 - std::f64::consts::PI * 60.0; assert!((vol(&s.solid().unwrap()) - expected).abs() < 0.5, "{}", vol(&s.solid().unwrap())); assert!((vol(&s.flat_solid().unwrap()) - expected).abs() < 0.5, "{}", vol(&s.flat_solid().unwrap())); - // The machining record keeps the pocket's exact outline. + // The machining record keeps the pocket's exact outline: its four conics in their order, + // the loop started at any of them. let machined = s.machining().unwrap(); - assert!(machined.len() == 1 && machined[0].region.outer == pocket.outer, "{} records", machined.len()); + let same_loop = |l: &Loop2| { + let n = pocket.outer.segs.len(); + l.segs.len() == n && (0..n).any(|k| (0..n).all(|i| l.segs[(i + k) % n] == pocket.outer.segs[i])) + }; + assert!(machined.len() == 1 && same_loop(&machined[0].region.outer), "{machined:?}"); } #[test] @@ -7006,10 +7011,12 @@ mod tests { assert!((length - outline).abs() < 1e-9, "{position}: {length} vs {outline}"); assert!((s.base.area() - (whole - below(line))).abs() < 1e-9, "{position}: {} vs {}", s.base.area(), whole - below(line)); // The flat pattern: the base and f.len × (BA + 37) of flange, its outline the base's - // with the flange's two sides (bend and panel, a line each) in place of nothing. + // with the flange's two sides and its end in place of the trimmed line. Each side is + // one line through the bend and the panel: the union of the two has no vertex where + // their sides meet in line. let regions = s.flat_regions().unwrap(); let (arcs, edges, length, shortest) = arcs_and_edges(®ions[0].outer); - assert!(regions[0].outer.is_line_arc() && (arcs, edges) == (4, 12) && shortest > 2.0, "{position}: {:?}", regions[0].outer); + assert!(regions[0].outer.is_line_arc() && (arcs, edges) == (4, 10) && shortest > 2.0, "{position}: {:?}", regions[0].outer); assert!((length - (outline + 2.0 * (ba + panel))).abs() < 1e-9, "{position}: {length}"); let flat = whole - below(line) + f.len * (ba + panel); assert!((regions[0].area() - flat).abs() < 1e-9, "{position}: {} vs {flat}", regions[0].area()); @@ -7168,13 +7175,12 @@ mod tests { } #[test] - fn a_base_trimmed_through_a_free_form_curve_follows_it_with_arcs() { + fn a_base_trimmed_through_a_free_form_curve_keeps_it_exact() { // A 200 x 60 plate under a parabola 40 high: y = 60 + 160·(x/200)·(1 − x/200), a conic // of weight 1. A flange 40 high inside on the right edge trims the base to x = 197, // through the curve's end: 183.564 goes (∫ y from 197 to 200), and the bend runs up the - // line x = 197 to the curve, at y = 62.364. The planar booleans follow a curve they - // cut with tangent arcs within 0.001 mm: over the parabola's 220 mm that is at most - // 0.22 mm² of the base, and 0.001/cos 38° = 0.0013 of the bend where it meets the curve. + // line x = 197 to the curve, at y = 62.364. The planar booleans cut the curve exactly: + // the base keeps what is left of it as one conic, so the strip and the bend are exact. // It used to become about 200 chords. let (ba, quarter) = (std::f64::consts::PI, std::f64::consts::FRAC_PI_2); let crowned = || { @@ -7197,11 +7203,12 @@ mod tests { let mut s = crowned(); let i = s.add_flange(pick, 40.0, quarter, 1.0, "inside", false).unwrap(); let outer = &s.base.outer; - let arcs = outer.segs.iter().filter(|e| matches!(e, Seg2::Arc { .. })).count(); - assert!(outer.is_line_arc() && arcs > 1 && outer.segs.len() == arcs + 3 && arcs < 64, "{what}: {arcs} arcs of {}", outer.segs.len()); - assert!((s.base.area() - (whole - strip)).abs() < 0.22, "{what}: {} vs {}", s.base.area(), whole - strip); + let conics = outer.segs.iter().filter(|e| matches!(e, Seg2::Conic { .. })).count(); + let lines = outer.segs.iter().filter(|e| matches!(e, Seg2::Line { .. })).count(); + assert!((conics, lines) == (1, 3), "{what}: {:?}", outer.segs); + assert!((s.base.area() - (whole - strip)).abs() < 1e-6, "{what}: {} vs {}", s.base.area(), whole - strip); let f = s.flanges[i].clone(); - assert!(f.p.dist(start) < 1e-9 && (f.len - len).abs() < 2e-3, "{what}: {f:?}"); + assert!(f.p.dist(start) < 1e-9 && (f.len - len).abs() < 1e-9, "{what}: {f:?}"); assert!((flat_area(&s) - (s.base.area() + f.len * (ba + 37.0))).abs() < 1e-6, "{what}: {}", flat_area(&s)); holds_the_flat_material(&s, what); let mut c = chorded(&crowned()); diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 961e074cb..0a08e8477 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -409,7 +409,14 @@ fn ribs_flush_with_a_window_change_nothing_away_from_them() { s.run_script(&Value::Array(lid.to_vec())).unwrap(); let measure = |s: &Session| s.model.state().body("Lid").map(|b| solidcraft_kernel::measure(&b.body).unwrap()).unwrap(); let (v0, a0) = (measure(&s).volume, measure(&s).area); - assert!((v0 - 6703.5222).abs() < 1e-3, "{v0}"); + // The plate with its rounded corners, the skirt, less the window, the slot and the notch + // through the skirt: (76.8 × 89.3 - (4 - π) × 9) × 2.4 + (71.5 × 84 - 68.5 × 81) × 3 + // - 68 × 61 × 2.4 - 44 × 10 × 2.4 - 22 × 1.5 × 3. + let lid = (76.8 * 89.3 - (4.0 - std::f64::consts::PI) * 9.0) * 2.4 + (71.5 * 84.0 - 68.5 * 81.0) * 3.0 + - 68.0 * 61.0 * 2.4 + - 44.0 * 10.0 * 2.4 + - 22.0 * 1.5 * 3.0; + assert!((v0 - lid).abs() < 1e-3, "{v0} vs {lid}"); for (i, rib) in ribs.iter().enumerate() { let reply = s.execute(rib["command"].as_str().unwrap(), &rib["params"]).unwrap(); let id = reply["feature"].as_u64().unwrap(); @@ -418,13 +425,15 @@ fn ribs_flush_with_a_window_change_nothing_away_from_them() { assert!(!result.warning.as_deref().unwrap_or_default().contains("tool displacement"), "{:?}", result.warning); let m = measure(&s); let n = (i + 1) as f64; + // The measure's accuracy: SMLib's mass properties come within 2e-7 of a closed form. + let (dv, da) = (2e-7 * m.volume, 2e-7 * m.area); // 1.6 x 6 x 11.7 less the 1.35 x 6 x 3 inside the skirt. - assert!((m.volume - (v0 + n * 88.02)).abs() < 1e-6, "rib {}: {}", i + 1, m.volume - v0); + assert!((m.volume - (v0 + n * 88.02)).abs() < dv, "rib {}: {}", i + 1, m.volume - v0); // Top 9.6, outer side 6 x 8.7 above the skirt, inner side 6 x 11.7 (flush with the // window's side), ends 2 x (1.6 x 11.7 - 1.35 x 3); the skirt top 8.1, its inner side // 18 and 1.5 of the plate go under the rib. let area = 9.6 + 52.2 + 70.2 + 29.34 - 8.1 - 18.0 - 1.5; - assert!((m.area - (a0 + n * area)).abs() < 1e-6, "rib {}: area {} (no slit adds any)", i + 1, m.area - a0); + assert!((m.area - (a0 + n * area)).abs() < da, "rib {}: area {} (no slit adds any)", i + 1, m.area - a0); } let bounds = s.model.state().body("Lid").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap().bounds(); assert!((bounds.max.z - 14.1).abs() < 1e-9, "{}", bounds.max.z); diff --git a/crates/engine/src/tests/robustness.rs b/crates/engine/src/tests/robustness.rs index df49cb5a2..dff5b6130 100644 --- a/crates/engine/src/tests/robustness.rs +++ b/crates/engine/src/tests/robustness.rs @@ -272,21 +272,31 @@ fn shell_after_a_drilled_hole() { /// Rounding a box's edges one at a time: an edge running into an earlier round (of the same /// radius or another) takes off about what each round alone would (the corner where they meet -/// is small). +/// is small). The upright runs on tangentially into the first round's end arc, and that into +/// the top right edge: its tangent chain, which the default (`tangent_chain`) rounds too, taking +/// off about what a round of that edge (38 long, past the first round) would as well. #[test] fn fillet_into_an_earlier_round() { let box_ = json!({"command": "solid.box", "params": {"length": 60, "width": 40, "height": 15}}); + let lost = |r: f64, len: f64| (1.0 - PI / 4.0) * r * r * len; for r2 in [2.0, 3.0] { let s = script(json!([ box_, - {"command": "solid.fillet", "params": {"edges": [[30, 0, 15]], "radius": 2}}, - {"command": "solid.fillet", "params": {"edges": [[60, 0, 7]], "radius": r2}} + {"command": "solid.fillet", "params": {"edges": [[30, 0, 15]], "radius": 2, "tangent_chain": false}}, + {"command": "solid.fillet", "params": {"edges": [[60, 0, 7]], "radius": r2, "tangent_chain": false}} ])); - let lost = |r: f64, len: f64| (1.0 - PI / 4.0) * r * r * len; let want = 36000.0 - lost(2.0, 60.0) - lost(r2, 15.0); let v = total_volume(&s); assert!((v - want).abs() < 2.0, "r2 {r2}: {v} vs {want}"); } + let s = script(json!([ + box_, + {"command": "solid.fillet", "params": {"edges": [[30, 0, 15]], "radius": 2}}, + {"command": "solid.fillet", "params": {"edges": [[60, 0, 7]], "radius": 2}} + ])); + let want = 36000.0 - lost(2.0, 60.0) - lost(2.0, 15.0) - lost(2.0, 38.0); + let v = total_volume(&s); + assert!((v - want).abs() < 2.0, "the upright's tangent chain: {v} vs {want}"); } /// Clean seeds (seed 16: a partial face contact, fused), and the original seed 5 edge contact, diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index f3c8d2a3f..975d01f92 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -26,8 +26,9 @@ wgpu = { workspace = true, features = ["metal", "vulkan", "dx12", "gles"] } [dev-dependencies] image = { workspace = true } solidcraft-kernel = { workspace = true } -# Headless pictures of real designs (capture tests). -solidcraft-engine = { workspace = true, features = ["bundled-render-library"] } +# Headless pictures of real designs (capture tests), built by the real kernel: SMLib +# (scripts/fetch-smlib.sh), as in the apps. +solidcraft-engine = { workspace = true, features = ["bundled-render-library", "smlib"] } solidcraft-io = { workspace = true } serde_json = { workspace = true } # The HLSL the D3D12 backend compiles (tests check it suits FXC). diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rs index 7f7d97dad..05323d84c 100644 --- a/crates/kernel/src/prism.rs +++ b/crates/kernel/src/prism.rs @@ -138,9 +138,12 @@ mod sheets { for r in regions { let (mut material, mut holes) = (Vec::new(), Vec::new()); let loops = std::iter::once(r.outer.ccw()).chain(r.holes.iter().map(|h| h.ccw().reversed())); - for piece in loops.flat_map(|lp| simple_loops(lp, tol * 10.0)) { - let face = face(&piece)?; - if piece.signed_area() > 0.0 { material.push(face) } else { holes.push(face) } + for lp in loops { + let near = tol * 10.0; + for piece in simple_loops(lp.segs.into_iter().map(|s| (s.start(), s)).collect(), |a, b| a.dist(*b) < near) { + let face = face(&piece)?; + if piece.signed_area() > 0.0 { material.push(face) } else { holes.push(face) } + } } let Some(material) = united(material)? else { continue }; sheets.push(match united(holes)? { @@ -174,22 +177,23 @@ mod sheets { Ok(sheets.pop()) } - /// A closed loop split where it passes a point twice (its segments' starts within `near`) - /// into loops that pass every point once. - fn simple_loops(lp: Loop2, near: f64) -> Vec { - let mut todo = vec![lp.segs]; + /// A closed loop, each segment with where it starts, split where it passes a point twice + /// (`same` start for two of its segments) into loops that pass every point once. + fn simple_loops(segs: Vec<(K, Seg2)>, same: impl Fn(&K, &K) -> bool) -> Vec { + let mut todo = vec![segs]; let mut out = Vec::new(); // Each split leaves two shorter loops, so the work is bounded by the segment count. while let Some(segs) = todo.pop() { - let starts: Vec = segs.iter().map(Seg2::start).collect(); - let repeat = (0..starts.len()).find_map(|i| (i + 1..starts.len()).find(|&j| starts[i].dist(starts[j]) < near).map(|j| (i, j))); + let repeat = (0..segs.len()).find_map(|i| (i + 1..segs.len()).find(|&j| same(&segs[i].0, &segs[j].0)).map(|j| (i, j))); match repeat { Some((i, j)) => { - let (inner, rest) = (segs[i..j].to_vec(), [&segs[j..], &segs[..i]].concat()); + let mut rest = segs; + let inner: Vec<(K, Seg2)> = rest.drain(i..j).collect(); + rest.rotate_left(i); todo.push(inner); todo.push(rest); } - None => out.push(Loop2 { segs }), + None => out.push(Loop2 { segs: segs.into_iter().map(|(_, s)| s).collect() }), } } out @@ -224,24 +228,29 @@ mod sheets { // Each loop as it runs in the plane, then split where it passes a point twice (a // cut-out touching the outline, material meeting at a corner): counter-clockwise // pieces are material, the others holes in the material that holds them. + // A loop passes a point twice where it passes one vertex of the record twice: the + // record's vertices, not their places, which may lie closer together than its + // tolerance at the ends of a short edge. let mut pieces = Vec::new(); for lp in &face.loops { let Loop::Edges { edges } = lp else { return Err(failed("face", format!("face {f} has a vertex loop"))) }; let mut segs = Vec::new(); for e in edges { + let edge = record.edges.get(e.edge as usize).ok_or_else(|| failed("edge", format!("edge {} is missing", e.edge)))?; let run = Run::of(&record, e.edge as usize, e.forward).ok_or_else(|| failed("edge", format!("edge {} is missing", e.edge)))?; let read = projected(&run, &Plane::XY, tol, &mut work) .ok_or_else(|| failed("edge", format!("edge {} of face {f} is not read exactly in the plane", e.edge)))?; - segs.extend(read); - } - for e in edges.iter().filter_map(|e| record.edges.get(e.edge as usize)) { - for v in e.vertices { + // The first piece of the edge starts on the use's first vertex. + let start = if e.forward { edge.vertices[0] } else { edge.vertices[1] }; + segs.extend(read.into_iter().enumerate().map(|(k, s)| ((k == 0).then_some(start), s))); + for v in edge.vertices { touching |= *owner.entry(v).or_insert(f) != f; } } // Seen from the face's normal, the outer loop runs counter-clockwise and holes clockwise. - let lp = if up > 0.0 { Loop2 { segs } } else { Loop2 { segs }.reversed() }; - pieces.extend(simple_loops(lp, tol * 10.0)); + for piece in simple_loops(segs, |a, b| a.is_some() && a == b) { + pieces.push(if up > 0.0 { piece } else { piece.reversed() }); + } } let (outers, holes): (Vec, Vec) = pieces.into_iter().partition(|lp| lp.signed_area() > 0.0); let first = out.len(); @@ -331,6 +340,24 @@ mod planar_tests { assert!((result[0].area() - a.area() - b.area()).abs() < 1e-6); } } + #[test] + fn a_ledge_shorter_than_the_record_tolerance_reads_back_as_one_region() { + // A plate with a ledge 0.0001 tall along part of its lower edge: SMLib's record holds a + // tolerance of 2e-5 mm, so the ledge's short side has both ends within ten times that. + // Read back, its outline is one loop of six lines, not split into a loop of one line. + let ledged = Region2 { + outer: Loop2::polygon( + &[(100.0, 3.0), (100.0, 3.0001), (97.0, 3.0001), (97.0, 60.0), (0.0, 60.0), (0.0, 3.0)].map(|(x, y)| Vec2::new(x, y)), + ), + holes: vec![], + }; + let below = rectangle(Vec2::new(0.0, -12.0), Vec2::new(100.0, 0.0)); + let out = planar_regions_boolean(std::slice::from_ref(&ledged), std::slice::from_ref(&below), BoolOp::Union, 1e-7).unwrap(); + assert_eq!(out.len(), 2, "{out:?}"); + let top = out.iter().find(|r| r.outer.contains(Vec2::new(50.0, 30.0))).unwrap(); + assert!(top.outer.segs.len() == 6 && top.outer.is_closed(1e-9), "{top:?}"); + assert!((top.area() - ledged.area()).abs() < 1e-9, "{}", top.area()); + } fn rectangle(a: Vec2, b: Vec2) -> Region2 { Region2 { outer: Loop2::polygon(&[a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)]), holes: vec![] } } diff --git a/examples/regressions/lid_ribs_flush_with_window.json b/examples/regressions/lid_ribs_flush_with_window.json index 4b5c6e28b..48ab7687f 100644 --- a/examples/regressions/lid_ribs_flush_with_window.json +++ b/examples/regressions/lid_ribs_flush_with_window.json @@ -1,5 +1,5 @@ { - "description": "A 76.8 x 89.3 x 2.4 lid plate (corner at x = 100) with its four vertical edges rounded 3 mm, a 1.5 mm skirt ring 3 mm high on it (outside 102.65..174.15 x 2.65..86.65), a 68 x 61 window and a 44 x 10 slot cut through, and a 22 x 6 notch in the skirt. Four 1.6 x 6 x 11.7 ribs are then joined standing on the plate (z = 2.4) over the skirt, each flush with a side of the window (x = 104.4 and x = 172.4). The joins needed retries that displaced the tool, and one left a zero-thickness slit through the skirt and plate at y = 25.5, far from any rib (#616). Each rib adds 1.6*6*11.7 - 1.35*6*3 = 88.02 mm3 and nothing changes away from it: 6703.5222 + 4 * 88.02 mm3.", + "description": "A 76.8 x 89.3 x 2.4 lid plate (corner at x = 100) with its four vertical edges rounded 3 mm, a 1.5 mm skirt ring 3 mm high on it (outside 102.65..174.15 x 2.65..86.65), a 68 x 61 window and a 44 x 10 slot cut through, and a 22 x 6 notch in the skirt. Four 1.6 x 6 x 11.7 ribs are then joined standing on the plate (z = 2.4) over the skirt, each flush with a side of the window (x = 104.4 and x = 172.4). The joins needed retries that displaced the tool, and one left a zero-thickness slit through the skirt and plate at y = 25.5, far from any rib (#616). Each rib adds 1.6*6*11.7 - 1.35*6*3 = 88.02 mm3 and nothing changes away from it: 6703.5344 + 4 * 88.02 mm3.", "commands": [ {"command": "solid.box", "params": {"corner": [100, 0, 0], "length": 76.8, "width": 89.3, "height": 2.4, "body_name": "Lid"}}, {"command": "solid.fillet", "params": {"edges": [[100, 0, 1.2], [176.8, 0, 1.2], [100, 89.3, 1.2], [176.8, 89.3, 1.2]], "radius": 3}},