diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index a890f5728..76910333c 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -87,7 +87,8 @@ fn volume(s: &Session, body: &str) -> f64 { /// Dividing one of the cut's intersection edges met a point that projects onto neither surface, /// and the fallback unwrapped that same failed projection: a kernel panic, recorded as a crash. /// Nothing panics now; the box loses the eighth of the ball inside it, or the cut is refused -/// and the box is left whole. +/// and the box is left whole. The side face is picked by its point (the report's face index +/// was truck's order): `p3` is its corner (15, -5, 0) and `l4` the box's upright edge there. #[test] fn revolve_cut_round_a_box_corner_does_not_panic() { use std::sync::Arc; @@ -98,7 +99,7 @@ fn revolve_cut_round_a_box_corner_does_not_panic() { ("sketch.rectangle.two_point", json!({"p0": [-5.4, 7.0], "p1": [15.0, -5.0]})), ("sketch.finish", json!({})), ("solid.extrude", json!({"direction": "positive", "distance": "10 mm", "operation": "new", "profiles": [0], "sketch": 1})), - ("sketch.create", json!({"plane": {"body": "Body1", "face": [12.721266146083186, -5.0, 7.034827173055135], "index": 1, "path": []}})), + ("sketch.create", json!({"plane": {"face": [12.721266146083186, -5.0, 7.034827173055135]}})), ("sketch.circle.center", json!({"center": "p3", "radius": 4.664761515876241})), ("sketch.options", json!({"slice": true})), ("sketch.finish", json!({})), @@ -581,16 +582,24 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/oblique_cuts_through_chamfered_ring.json")).unwrap(); let steps = script.get("commands").and_then(Value::as_array).unwrap(); let mut s = Session::default(); - let mut volumes = Vec::new(); + // The ring after the move and after each cut, and what each cut took away (the ring before it + // less the ring after it: a small body that measures to its own accuracy, where the difference + // of the whole ring's volumes is lost in the integration's 1e-6 of 1149 mm³). + let mut rings: Vec = Vec::new(); for step in steps { let reply = s.execute(step["command"].as_str().unwrap(), &step["params"]).unwrap(); if step["command"] == "solid.extrude" { assert!(reply["warning"].is_null(), "{reply}"); } if matches!(step["command"].as_str(), Some("solid.move" | "solid.extrude")) { - volumes.push(s.model.state().body("R").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume); + rings.push(s.model.state().body("R").unwrap().body.clone()); } } + let taken = |k: usize| -> f64 { + let piece = solidcraft_kernel::boolean(&rings[k], &rings[k + 1], solidcraft_kernel::BoolOp::Cut).unwrap().unwrap(); + solidcraft_kernel::measure(&piece).unwrap().volume + }; + let volumes: Vec = rings.iter().map(|b| b.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume).collect(); // Pappus: the profile's moment about the axis turned through 240°. let profile = [(16.6, 0.0), (17.5, 0.0), (18.5, 1.0), (18.5, 7.0), (17.5, 8.0), (16.6, 8.0), (16.4, 7.8), (16.4, 0.2)]; let moment: f64 = (0..profile.len()) @@ -600,14 +609,14 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { }) .sum(); let ring = moment.abs() * 4.0 * std::f64::consts::PI / 3.0; - let [whole, first, second, notched] = volumes[..] else { panic!("{volumes:?}") }; + let [whole, _, _, _] = volumes[..] else { panic!("{volumes:?}") }; // Volumes from meshes at 1e-5 mm: within a few millionths of the ring's. assert!((whole - ring).abs() < 1e-5 * ring, "{whole} vs {ring}"); // The ring and the two prisms are mirror images across XZ. - let (cut1, cut2) = (whole - first, first - second); - assert!(cut1 > 5.0 && (cut1 - cut2).abs() < 1e-6, "{cut1} vs {cut2}"); - let notch = ring_notch(); - assert!(((second - notched) - notch).abs() < 1e-4, "{} vs {notch}", second - notched); + let (cut1, cut2) = (taken(0), taken(1)); + assert!(cut1 > 5.0 && (cut1 - cut2).abs() < 1e-6 * cut1, "{cut1} vs {cut2}"); + let (notched, notch) = (taken(2), ring_notch()); + assert!((notched - notch).abs() < 1e-5 * notch, "{notched} vs {notch}"); let state = s.model.state(); let body = &state.body("R").unwrap().body; assert!(body.validity().is_empty(), "{:?}", body.validity()); @@ -620,8 +629,7 @@ fn oblique_cuts_through_a_chamfered_ring_are_exact() { ); assert!(coarse < fine && coarse > fine - 2.0, "area meshed at 0.05: {coarse} vs {fine}"); println!( - "ring {whole:.6} / {ring:.6} mm³; cuts {cut1:.6}, {cut2:.6}; notch {:.6} / {notch:.6}; area meshed at 0.05 {coarse:.4} / {fine:.4}", - second - notched + "ring {whole:.6} / {ring:.6} mm³; cuts {cut1:.6}, {cut2:.6}; notch {notched:.6} / {notch:.6}; area meshed at 0.05 {coarse:.4} / {fine:.4}" ); } @@ -633,17 +641,18 @@ fn notch_into_a_ring_chamfer_is_cut_exactly() { let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/oblique_cuts_through_chamfered_ring.json")).unwrap(); let steps = script.get("commands").and_then(Value::as_array).unwrap(); let mut s = Session::default(); - let measure = - |s: &Session| s.model.state().body("R").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-5)).unwrap().measure().volume; s.run_script(&Value::Array(steps[..5].to_vec())).unwrap(); - let before = measure(&s); + let before = s.model.state().body("R").unwrap().body.clone(); // The notch's sketch and its cut. for step in &steps[steps.len() - 4..] { let reply = s.execute(step["command"].as_str().unwrap(), &step["params"]).unwrap(); assert!(reply["warning"].is_null(), "{reply}"); } - let (got, want) = (before - measure(&s), ring_notch()); - assert!((got - want).abs() < 1e-4, "{got} vs {want}"); + // What the cut took: the ring before it less the ring after it, measured as a body of its own + // (the difference of the two rings' volumes is lost in the integration's 1e-6 of 1149 mm³). + let piece = solidcraft_kernel::boolean(&before, &s.model.state().body("R").unwrap().body, solidcraft_kernel::BoolOp::Cut).unwrap().unwrap(); + let (got, want) = (solidcraft_kernel::measure(&piece).unwrap().volume, ring_notch()); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); } /// What the ring's notch takes: a band 0.9 wide about a radius, from 17.6 out along it, and from diff --git a/crates/engine/src/naming_history_tests.rs b/crates/engine/src/naming_history_tests.rs index 4c6fcfb10..97560d42f 100644 --- a/crates/engine/src/naming_history_tests.rs +++ b/crates/engine/src/naming_history_tests.rs @@ -414,10 +414,10 @@ fn named_at(faces: &[(String, bool, [f64; 3])], at: [f64; 3]) -> String { } /// #1209: an arm with a boss at each end (each boss the radius of the arm's round end under it) -/// and a square cut through one. The second boss and the cut are prism booleans sewn slab by -/// slab, where the arm's round end and the boss over it are two pieces of one cylinder: every -/// face keeps exact history, so the cut's walls are its own four faces and the boss's outer -/// cylinder keeps its name, through the fillets on the bore's corners too. +/// and a square cut through one. The arm's round end and the boss over it lie on one cylinder, +/// which SMLib keeps one face, named for the arm's end it began as: every face keeps exact +/// history, so the cut's walls are its own four faces and the boss's outer cylinder keeps its +/// name, through the fillets on the bore's corners too. #[test] fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { let mut s = Session::default(); @@ -437,8 +437,10 @@ fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"distance": 16, "body_name": "Arm"})); run(&mut s, "solid.cylinder", json!({"diameter": 46.0, "height": 22, "base": [0, 0, 0], "operation": "join", "targets": ["Arm"]})); - let boss = named_at(&listed(&mut s, "Arm"), [19.98, -4.24, 19.0]); - assert!(boss.starts_with("F3:side"), "{boss}"); + // A point on the boss's outer wall, above the arm. + let wall = |s: &Session| solidcraft_doc::naming::face_names_at(&s.model.state(), &[Vec3::new(-23.0, 0.0, 19.0)]).pop().unwrap_or_default(); + let boss = wall(&s); + assert!(boss.starts_with("F2:side:a"), "{boss}"); run(&mut s, "solid.cylinder", json!({"diameter": 30.0, "height": 20, "base": [170.0, 0, 0], "operation": "join", "targets": ["Arm"]})); let joined = listed(&mut s, "Arm"); assert!(joined.iter().all(|(_, exact, _)| *exact), "{joined:?}"); @@ -453,47 +455,57 @@ fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() { for (at, line) in [([0.0, -6.35, 11.0], "l1"), ([6.35, 0.0, 11.0], "l2"), ([0.0, 6.35, 11.0], "l3"), ([-6.35, 0.0, 11.0], "l4")] { assert_eq!(named_at(&cut, at), format!("F6:side:{line}")); } - assert_eq!(named_at(&cut, [19.98, -4.24, 19.0]), boss); + assert_eq!(wall(&s), boss); run(&mut s, "solid.fillet", json!({"edges": [[6.35, 6.35, 10], [-6.35, 6.35, 10], [-6.35, -6.35, 10], [6.35, -6.35, 10]], "radius": 1.5})); let filleted = listed(&mut s, "Arm"); let blends = filleted.iter().filter(|(n, _, _)| n.starts_with("F7:blend:")).count(); assert_eq!(blends, 4, "{filleted:?}"); - assert_eq!(named_at(&filleted, [19.98, -4.24, 19.0]), boss); + assert_eq!(wall(&s), boss); } -/// #3902: a torus with a closed, twisted square sweep cut inside it splits the sweep's walls into -/// pieces the kernel returns in a different order on each evaluation. The pieces are numbered by -/// where they lie, so every fresh evaluation gives each piece the same name. +/// A disc whose top a round groove along x splits into two pieces of one name, numbered by +/// place: `F1:top#1` on the -y side, `F1:top#2` on the +y side. +fn grooved_disc() -> Value { + json!([ + {"command": "solid.cylinder", "params": {"radius": 20, "height": 10, "body_name": "Disc"}}, + {"command": "solid.cylinder", "params": {"axis": [1, 0, 0], "base": [-25, 0, 10], "radius": 3, "height": 60, "operation": "cut"}} + ]) +} + +/// #3902: a torus with a closed, twisted square sweep cut inside it split the sweep's walls into +/// pieces truck returned in a different order on each evaluation (SMLib keeps those walls +/// whole), and a grooved disc's top is two pieces of one name. Pieces are numbered by where they +/// lie, so every fresh evaluation gives each face the same name. #[test] fn split_pieces_keep_their_numbers_across_evaluations() { - let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/closed_sweep_torus_cut.json")).unwrap(); - let mut s = Session::default(); - s.run_script(&script).unwrap(); - let body = s.model.state().bodies.first().map(|b| b.name.clone()).expect("a body"); - let named = |s: &mut Session| -> Vec<(String, [i64; 3])> { - let mut faces: Vec<(String, [i64; 3])> = listed(s, &body).into_iter().map(|(n, _, c)| (n, c.map(|x| x.round() as i64))).collect(); - faces.sort(); - faces - }; - let first = named(&mut s); - assert!(first.iter().any(|(n, _)| n.contains('#')), "no split pieces: {first:?}"); - for run in 0..10 { - let mut fresh = Session::new(solidcraft_doc::Document::clone(&s.doc)); - fresh.refresh(); - assert_eq!(named(&mut fresh), first, "evaluation {run}"); + let torus: Value = serde_json::from_str(include_str!("../../../examples/regressions/closed_sweep_torus_cut.json")).unwrap(); + for (script, pieces) in [(torus, false), (grooved_disc(), true)] { + let mut s = Session::default(); + s.run_script(&script).unwrap(); + let body = s.model.state().bodies.first().map(|b| b.name.clone()).expect("a body"); + let named = |s: &mut Session| -> Vec<(String, [i64; 3])> { + let mut faces: Vec<(String, [i64; 3])> = listed(s, &body).into_iter().map(|(n, _, c)| (n, c.map(|x| x.round() as i64))).collect(); + faces.sort(); + faces + }; + let first = named(&mut s); + assert_eq!(first.iter().any(|(n, _)| n.contains('#')), pieces, "split pieces: {first:?}"); + for run in 0..10 { + let mut fresh = Session::new(solidcraft_doc::Document::clone(&s.doc)); + fresh.refresh(); + assert_eq!(named(&mut fresh), first, "evaluation {run}"); + } } } /// #3902: a design saved before the pieces of a face were numbered by place opens with the /// numbers it was saved with, so a reference to `…#1` stays on the piece it was made on. The -/// block cut by the second block here has its side split in two, numbered the other way round -/// by place. +/// grooved disc's top is split in two, numbered the other way round by place. #[test] fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { - let script: Value = serde_json::from_str(include_str!("../../../tests/action_matrix/designs/multi-body-join-cut.json")).unwrap(); let mut s = Session::default(); - s.run_script(&script).unwrap(); - let by_place = listed(&mut s, "Block"); + s.run_script(&grooved_disc()).unwrap(); + let by_place = listed(&mut s, "Disc"); // As a build before the change saved it: its features carry no mark, and the file does not // list the change among those it has. let mut file: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); @@ -509,16 +521,16 @@ fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() { assert!(old.features.iter().all(|f| f.kernel_piece_order), "the features of an older design keep the old numbering"); let mut reopened = Session::new(old); reopened.refresh(); - let kept = listed(&mut reopened, "Block"); + let kept = listed(&mut reopened, "Disc"); let at = |faces: &[(String, bool, [f64; 3])], name: &str| faces.iter().find(|(n, _, _)| n == name).map(|(_, _, c)| *c); // The pieces are numbered differently by place, and the older design keeps its own numbers. - let (old1, new1) = (at(&kept, "F2:side#1").unwrap(), at(&by_place, "F2:side#1").unwrap()); + let (old1, new1) = (at(&kept, "F1:top#1").unwrap(), at(&by_place, "F1:top#1").unwrap()); assert!((0..3).any(|k| (old1[k] - new1[k]).abs() > 1.0), "{kept:?} {by_place:?}"); let mut legacy = solidcraft_doc::Document::clone(&s.doc); legacy.features.iter_mut().for_each(|f| f.kernel_piece_order = true); let mut saved_with = Session::new(legacy); saved_with.refresh(); - assert_eq!(listed(&mut saved_with, "Block"), kept); + assert_eq!(listed(&mut saved_with, "Disc"), kept); } /// The volumes of the design's bodies, by name. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 30cc29c0f..4087cd8ff 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2772,17 +2772,20 @@ fn press_pull_on_curved_faces() { let v1 = volume(&mut s); assert!(rel(v1 - v0, PI * (25.0 - 16.0) * 20.0) < 1e-3, "{v0} {v1}"); // A shell's inner wall behind a fillet (`F3:inner:F2:blend:…`) only names the fillet: it is - // offset like any curved face, not taken for the shell's fillet. (The offset itself is - // refused: the wall is tangent to its neighbours.) + // offset like any curved face, not taken for the shell's fillet. Pulled 0.5 into the cavity + // (radius 3 to 2.5), the wall alone moves, stepping in from its tangent neighbours: the + // quarter ring between the radii, 18 high, is added. let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 20})); run(&mut s, "solid.fillet", json!({"edges": [[40, 40, 10]], "radius": 5})); run(&mut s, "solid.shell", json!({"faces": [[20, 20, 20]], "thickness": 2})); let on = Vec3::new(35.0, 35.0, 10.0) + Vec3::new(1.0, 1.0, 0.0).normalized().unwrap() * 3.0; - let err = - s.execute("solid.press_pull", &json!({"face": [on.x, on.y, on.z], "distance": 0.5})).map(|v| v.to_string()).unwrap_or_else(|e| e.to_string()); - assert!(!err.contains("not a fillet's or a chamfer's"), "{err}"); - assert!(err.contains("offset"), "{err}"); + let v0 = volume(&mut s); + let out = run(&mut s, "solid.press_pull", json!({"face": [on.x, on.y, on.z], "distance": 0.5})); + assert!(out["name"].as_str().is_some_and(|n| n.starts_with("OffsetFace")) && out.get("edited").is_none(), "{out}"); + let ring = PI / 4.0 * (3.0 * 3.0 - 2.5 * 2.5) * 18.0; + // Each volume to the measure's 2e-7. + assert!((volume(&mut s) - v0 - ring).abs() < 4e-7 * v0, "{} vs {ring}", volume(&mut s) - v0); } /// A cut in one component leaves other components' bodies alone unless they are named as @@ -3212,7 +3215,12 @@ fn shell_tangent_chain_that_opens_every_face_explains_how_to_keep_walls() { assert_eq!(s.doc.to_json(), before, "a refused shell must preserve the design"); } run(&mut s, "solid.shell", json!({"faces": [[20,0,30]], "thickness": 2, "tangent_chain": false})); - assert!((volume(&mut s) - 15_305.28).abs() < 0.1); + // The rounded box (its 37 x 27 x 57 core grown by the 1.5 ball) less the cavity, which the + // 2 mm walls leave sharp, open through the front: 36 x 56 x 28. To the measure's 2e-7. + let (a, b, c, r) = (37.0, 27.0, 57.0, 1.5); + let rounded = a * b * c + 2.0 * r * (a * b + b * c + a * c) + PI * r * r * (a + b + c) + 4.0 / 3.0 * PI * r * r * r; + let want = rounded - 36.0 * 56.0 * 28.0; + assert!((volume(&mut s) - want).abs() < 2e-7 * rounded, "{} vs {want}", volume(&mut s)); assert_eq!(s.model.state().bodies.len(), 1); } diff --git a/crates/kernel/src/placement_tests.rs b/crates/kernel/src/placement_tests.rs index e788d39bc..239281cae 100644 --- a/crates/kernel/src/placement_tests.rs +++ b/crates/kernel/src/placement_tests.rs @@ -73,3 +73,25 @@ fn periodic_step_seam_survives_identity_rotation_and_translation() { assert_topology(body, &rigid, [[0., 1., 0., 0.], [-1., 0., 0., 0.], [0., 0., 1., 0.], [10., 10., 30., 1.]]); assert_eq!(crate::step_export(&[body], "source snapshot").unwrap(), unchanged); } + +/// A body mirrored in SMLib reads back from its record as the same valid solid: a plate with a +/// through hole (the hole's cylinder comes out inside out) and a box with two rounds meeting at a +/// corner (their intersection edge has a tolerance of its own, wider than the body's). Read back +/// from the record, the hole's cylinder swept the wrong way about its axis 30 mm off its NURBS, +/// and the rounds' shared edge lost its tolerance to the body's. +#[test] +fn mirrored_bodies_read_back_from_their_records_valid() { + let plate = crate::box_solid(Vec3::ZERO, Vec3::new(30., 40., 20.)).unwrap(); + let hole = crate::cylinder(Vec3::new(20., 20., -5.), Vec3::Z, 5.0, 30.0).unwrap(); + let holed = crate::boolean(&plate, &hole, crate::BoolOp::Cut).unwrap().unwrap(); + let rounded = crate::fillet(&plate, &[Vec3::new(15., 0., 20.), Vec3::new(0., 0., 10.)], 3.0).unwrap(); + // The mirror in x = 30. + let mirror = [[-1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [60., 0., 0., 1.]]; + for (what, body) in [("holed plate", holed), ("rounded box", rounded)] { + let mirrored = transform_matrix(&body, mirror).unwrap(); + let read_back = Body::from_record(mirrored.record().clone()).unwrap(); + assert!(matches!(crate::validity(&read_back).smlib, Some(crate::SmlibCheck::Valid)), "{what}: {:?}", crate::validity(&read_back).smlib); + let (want, got) = (crate::measure(&body).unwrap().volume, crate::measure(&read_back).unwrap().volume); + assert!((got - want).abs() < 1e-6 * want, "{what}: volume {got}, expected {want}"); + } +}