diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 479a32b3a..7a54aaa05 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4300,8 +4300,8 @@ fn hole_tools( } /// The scale a hole's tools are sized by: the largest body the hole's axis meets (#2904), so a -/// large body elsewhere in the model changes neither the tool's reach above the face (and so -/// the countersink's outline) nor its depth. A hole whose axis meets no body is sized by the +/// large body elsewhere in the model changes neither the tool's reach above the face nor its +/// depth. A hole whose axis meets no body is sized by the /// largest body of the model, as before. fn hole_axis_size(st: &ModelState, position: &Vec3, dir: Vec3) -> f64 { let along = |b: &ModelBody| { @@ -4417,13 +4417,21 @@ fn hole_tools_and_prisms( if !(rc > r && half > 1e-3 && half < std::f64::consts::FRAC_PI_2) { return Err(DocError::Invalid("the countersink must be wider than the hole".into())); } - // Cone from above the face to just inside the hole radius, then the hole. - let r_top = rc + top * half.tan(); + // One revolved tool: the cone from its rim on the face to just inside the hole + // radius, and above the face the rim's cylinder, as the bore's own cylinder runs on + // above it. The cone widening on above the face would cut what stands beside the rim + // (#5041). The cone is the profile's first segment (`csink:side:0`). let r_end = r * 0.9; - let len = (r_top - r_end) / half.tan(); - let top_plane = plane.offset(top); - let csink = kernel::extrude_tapered(&top_plane, &disc(r_top), len, -1.0, -half, kernel::DraftCorner::default())?; - tools.push((crate::lineage::part_tool(csink, "csink"), None)); + let len = (rc - r_end) / half.tan(); + let up = -dir; + let rp = Plane::new(*position, up.any_perp(), up).ok_or_else(|| DocError::Invalid("hole axis".into()))?; + let pts = [Vec2::new(rc, 0.0), Vec2::new(r_end, -len), Vec2::new(0.0, -len), Vec2::new(0.0, top), Vec2::new(rc, top)]; + let region = Region2 { outer: solidcraft_geom::Loop2::polygon(&pts), holes: vec![] }; + tools.extend( + kernel::revolve(&rp, &[region], Vec2::ZERO, Vec2::Y, std::f64::consts::TAU)? + .into_iter() + .map(|tool| (crate::lineage::part_tool(tool, "csink"), None)), + ); tools.extend(bore(tip_angle.as_ref())?); } } diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 90b106ff0..7368c05da 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -579,10 +579,7 @@ pub(super) fn sheet_eval( } let rr = match radius { Some(e) => val(vals, e, Kind::Length)?, - None => { - let rule = st.sheets.get(i).map(|s| s.rule.clone()).unwrap_or_default(); - doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.bend_radius - } + None => sheet_rule_values(doc, vals, st, i)?.bend_radius, }; // The corner relief these flanges ask for in place of the rule's. let relief = sheet::ReliefOverride { @@ -693,10 +690,7 @@ pub(super) fn sheet_eval( let l = val(vals, length, Kind::Length)?; let g = match gap { Some(e) => val(vals, e, Kind::Length)?, - None => { - let rule = st.sheets.get(i).map(|s| s.rule.clone()).unwrap_or_default(); - doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.hem_gap - } + None => sheet_rule_values(doc, vals, st, i)?.hem_gap, }; let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; let picks = sheet_picks(sh, f, &crate::plain(edges), warning); @@ -724,10 +718,7 @@ pub(super) fn sheet_eval( let ang = val(vals, angle, Kind::Angle)?; let rr = match radius { Some(e) => val(vals, e, Kind::Length)?, - None => { - let rule = st.sheets.get(i).map(|s| s.rule.clone()).unwrap_or_default(); - doc.rule_values(vals, &doc.sheet_rule(Some(&rule)))?.bend_radius - } + None => sheet_rule_values(doc, vals, st, i)?.bend_radius, }; // A fixed point that touches no material at all (e.g. far above the sheet) still picks // the side it lies on, so a stored fold keeps recomputing; it says so (#371). @@ -767,7 +758,7 @@ pub(super) fn sheet_eval( FeatureKind::SheetConvert { body, face, rule, bends } if !bends.is_empty() => { let mb = st.body(body).cloned().ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; let r = doc.sheet_rule(rule.as_deref()); - let rv = doc.rule_values(vals, &r)?; + let values = |t: Option| doc.rule_values_at(vals, &r, t); // The bend edges by name first; a name that is gone keeps its point, with a warning. let mut picks = Vec::with_capacity(bends.len()); for (i, p) in bends.iter().enumerate() { @@ -788,7 +779,7 @@ pub(super) fn sheet_eval( } let placement = doc.component_transform(doc.model_body_component(&mb)); let body_to_world = doc.model_body_offset(&mb).map(|offset| crate::mat_mul(&placement, offset)).unwrap_or(placement); - let (mut sh, notes) = sheet::convert_body(&mb, &r.name, &rv, face.0, &picks, &body_to_world)?; + let (mut sh, notes) = sheet::convert_body(&mb, &r.name, &values, face.0, &picks, &body_to_world)?; for note in notes { append_warning(warning, note); } @@ -839,8 +830,7 @@ pub(super) fn sheet_eval( )); } let r = doc.sheet_rule(rule.as_deref()); - let mut rv = doc.rule_values(vals, &r)?; - rv.thickness = t; + let rv = doc.rule_values_at(vals, &r, Some(t))?; let mut sh = sheet::base_flange(body, &r.name, &rv, plane, Region2 { outer: region.outer.clone(), holes: Vec::new() }); sh.holes = region.holes.iter().map(|h| Region2 { outer: h.ccw(), holes: Vec::new() }).collect(); let mut work = sheet::FlatWork::new(); @@ -2180,6 +2170,13 @@ fn sheet_picks(sh: &crate::sheet::SheetBody, f: &Feature, edges: &[Vec3], warnin out } +/// The values of sheet `i`'s rule for that sheet: `Thickness` in them is the sheet's own +/// thickness, which a converted body takes from its walls. +fn sheet_rule_values(doc: &Document, vals: &BTreeMap, st: &ModelState, i: usize) -> Result { + let sh = st.sheets.get(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; + doc.rule_values_at(vals, &doc.sheet_rule(Some(&sh.rule)), Some(sh.t)) +} + /// Tag the flanges a feature just added (`F.`). fn tag_flanges(sh: &mut crate::sheet::SheetBody, from: usize, feature: u64) { for (k, fl) in sh.flanges.iter_mut().enumerate().skip(from) { diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index 652beba1d..40a4025c3 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -476,8 +476,17 @@ impl Document { /// Evaluate a rule: `Thickness` in its expressions is the rule's thickness. pub fn rule_values(&self, vals: &std::collections::BTreeMap, r: &SheetRule) -> Result { + self.rule_values_at(vals, r, None) + } + + /// Evaluate a rule for a sheet `thickness` thick (a converted body's own thickness), or the + /// rule's thickness: `Thickness` in its expressions is the sheet's. + pub fn rule_values_at(&self, vals: &std::collections::BTreeMap, r: &SheetRule, thickness: Option) -> Result { let look = |n: &str| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))); - let t = expr::eval_with(&r.thickness, &look)?.to_kind(Kind::Length)?; + let t = match thickness { + Some(t) => t, + None => expr::eval_with(&r.thickness, &look)?.to_kind(Kind::Length)?, + }; if !(t > 0.0 && t < 1e4) { return Err(DocError::Invalid("the sheet thickness must be positive".into())); } diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rs index ef9fd60ec..90687e8bd 100644 --- a/crates/doc/src/sheet_convert.rs +++ b/crates/doc/src/sheet_convert.rs @@ -691,15 +691,16 @@ pub fn bend_edge_names(st: &crate::ModelState, body: &str, pts: &[Vec3]) -> Vec< pts.iter().zip(crate::naming::edge_names_at(b, pts)).map(|(p, name)| if on(p) { name } else { String::new() }).collect() } -/// Convert body `mb` to a sheet under the rule `rule` with values `rv`: `face` is a point on the -/// fixed face and `bends` are points on the sharp edges that become bends, in the middle of -/// chamfers or on bend cylinders that do (the body's coordinates, mm). See the module docs. -/// `body_to_world` places diagnostic points in world coordinates. Geometry and picks stay local. -/// Returns the sheet and a note for every corner or end of a bend not finished as the rule says. +/// Convert body `mb` to a sheet under the rule `rule`, whose values for a sheet of a thickness +/// (`None`: the rule's own) are `values`: `face` is a point on the fixed face and `bends` are +/// points on the sharp edges that become bends, in the middle of chamfers or on bend cylinders +/// that do (the body's coordinates, mm). See the module docs. `body_to_world` places diagnostic +/// points in world coordinates. Geometry and picks stay local. Returns the sheet and a note for +/// every corner or end of a bend not finished as the rule says. pub fn convert_body( mb: &ModelBody, rule: &str, - rv: &RuleValues, + values: &dyn Fn(Option) -> Result, face: Vec3, bends: &[Vec3], body_to_world: &crate::Mat, @@ -708,9 +709,7 @@ pub fn convert_body( if bends.is_empty() || bends.len() > MAX_BENDS { return err(format!("pick 1…{MAX_BENDS} bend edges")); } - if !(rv.gap >= 0.0 && rv.bend_radius >= 0.0) { - return err("the rule's gap and bend radius must not be negative"); - } + let rv = values(None)?; let (b, mesh) = (&mb.body, mb.mesh()); let size = b.size(); if !(size.is_finite() && size > 0.0) { @@ -763,6 +762,12 @@ pub fn convert_body( .flatten() .collect(); let t = shell.map_or(rv.thickness, |d| (d * 1e9).round() / 1e9); + // A shell's sheet is as thick as its walls: the rule's values that follow its thickness (a + // bend radius of `Thickness`, the gap, the reliefs) follow the walls', not the rule's own. + let rv = if shell.is_some() { values(Some(t))? } else { rv }; + if !(rv.gap >= 0.0 && rv.bend_radius >= 0.0) { + return err("the rule's gap and bend radius must not be negative"); + } let r = rv.bend_radius; let joined = |x: usize, y: usize| { mesh.edge_faces.iter().any(|faces| faces.contains(&(x as u32)) && faces.contains(&(y as u32))) @@ -841,7 +846,7 @@ pub fn convert_body( } panels.insert(g, wall); } - let mut sh = base_flange(&mb.name, rule, &RuleValues { thickness: t, ..*rv }, frame, Region2::default()); + let mut sh = base_flange(&mb.name, rule, &RuleValues { thickness: t, ..rv }, frame, Region2::default()); // How far behind a face of the sheet the body's face `g` starts and ends: a hole's wall // reaches through the sheet, a pocket's ends on its floor, an island's starts at the face. let mut points: BTreeMap> = BTreeMap::new(); diff --git a/crates/engine/src/cmd/sheet_convert_tests.rs b/crates/engine/src/cmd/sheet_convert_tests.rs index 1618b1a24..7bf488583 100644 --- a/crates/engine/src/cmd/sheet_convert_tests.rs +++ b/crates/engine/src/cmd/sheet_convert_tests.rs @@ -632,6 +632,23 @@ fn a_channel_with_its_bends_modelled_folds_back_into_itself_under_its_own_radius assert!((volume(&mut s) - solid).abs() < 1e-3 * solid); } +/// A rule's values follow the sheet's own thickness (#4328): an L shell 2 thick, its bend +/// modelled R 2 inside, converted under the default rule (2.5 thick, bends R `Thickness`) is a +/// sheet 2 thick bent R 2, the solid unchanged; an edge flange added to it bends R 2 as well. +#[test] +fn a_converted_shell_takes_its_rules_values_at_its_own_thickness() { + let mut s = Session::default(); + let (outer, _) = bent_section(&mut s, &[(0.0, 40.0), (0.0, 0.0), (60.0, 0.0)], 2.0, 2.0, 100.0)[0]; + let solid = volume(&mut s); + run(&mut s, "sheet.convert", json!({"body": "Section", "face": [30, 0, 50], "bends": [outer]})); + assert!((volume(&mut s) - solid).abs() < 1e-6 * solid, "{} vs {solid}", volume(&mut s)); + let f = flat(&mut s); + assert_eq!((f["thickness"].as_f64(), f["bends"][0]["radius"].as_f64()), (Some(2.0), Some(2.0)), "{f}"); + run(&mut s, "sheet.flange", json!({"edges": [[0, 40, 50]], "height": 10})); + let f = flat(&mut s); + assert_eq!(f["bends"][1]["radius"].as_f64(), Some(2.0), "{f}"); +} + #[test] fn a_filleted_edge_of_a_solid_block_is_a_bend() { // A block's bottom edge rounded R 5: the faces either side meet at the old sharp edge, diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 94e1f81d4..9e2b401fd 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -5373,6 +5373,63 @@ fn flat_exports(s: &mut Session) -> Vec> { calls.iter().map(|(id, p)| s.execute(id, p).map_err(|e| e.to_string())).collect() } +/// 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. +#[test] +fn a_mirrored_or_patterned_sheet_body_is_sheet_metal_with_its_flat_pattern() { + use solidcraft_geom::Vec3; + let mut s = Session::default(); + run(&mut s, "sheet.manage_rules", json!({"name": "S", "thickness": "2 mm", "active": true, "bend_radius": "2 mm", "k_factor": 0.4})); + base(&mut s, 100.0, 60.0); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 2]], "height": 20})); + rectangle_tool(&mut s, "Pocket", [20.0, 20.0], [30.0, 30.0]); + run(&mut s, "solid.extrude", json!({"sketch": "Pocket", "distance": 1, "operation": "cut"})); + let source = s.model.state().sheets[0].body.clone(); + let before = volume(&mut s); + let blank = run(&mut s, "sheet.flat_pattern", json!({"body": source})); + + run(&mut s, "solid.mirror", json!({"bodies": [source], "plane": "YZ"})); + 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}"); + 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 + // first flange still up on the y = 0 edge and its pocket still from below. + run(&mut s, "sheet.flange", json!({"body": copy, "edges": [[-100, 30, 2]], "height": 10})); + let state = s.model.state(); + let body = &state.body(©).expect("the copy").body; + for (p, inside) in [ + (Vec3::new(-50.0, 1.0, 15.0), true), + (Vec3::new(-50.0, 1.0, -15.0), false), + (Vec3::new(-25.0, 25.0, 0.5), false), + (Vec3::new(-25.0, 25.0, 1.5), true), + (Vec3::new(-99.0, 30.0, 8.0), true), + (Vec3::new(-99.0, 30.0, -8.0), false), + ] { + assert_eq!(body.contains(p), inside, "{p:?}"); + } + drop(state); + + let mut s = Session::default(); + base(&mut s, 100.0, 60.0); + let source = s.model.state().sheets[0].body.clone(); + run(&mut s, "solid.pattern.rectangular", json!({"bodies": [source], "dir1": [1, 0, 0], "count1": 2, "spacing1": 150})); + let state = s.model.state(); + assert_eq!(state.sheets.len(), state.bodies.len(), "every copy is sheet metal"); + let names: Vec = state.bodies.iter().map(|b| b.name.clone()).collect(); + drop(state); + for n in names { + run(&mut s, "sheet.flat_pattern", json!({"body": n})); + } +} + /// A mirror combined into a sheet, or a tab extruded onto it and joined, makes a part its /// flat pattern does not have (the mirrored half, the tab): the flat pattern, the DXF and the /// bend table are refused with the feature's name instead of writing the sheet without it. diff --git a/crates/engine/src/cmd/single_hole_tests.rs b/crates/engine/src/cmd/single_hole_tests.rs index 9249abbee..e967b55dc 100644 --- a/crates/engine/src/cmd/single_hole_tests.rs +++ b/crates/engine/src/cmd/single_hole_tests.rs @@ -133,3 +133,29 @@ fn a_far_body_does_not_change_a_countersunk_hole() { assert_eq!(small_changed, large_changed, "bodies changed"); assert_eq!(large_changed, json!(["lid"]), "only the lid is drilled"); } + +/// #5041: a countersunk Ø6.4 hole (Ø13.7, 90°) 0.15 mm from a wall standing on the plate cuts +/// nothing above the entry face: the countersink's rim (y 29.85) stays clear of the wall (y 30). +/// 10 faces: bottom, the two L-shaped ends, front and back, the plate top, the wall's front and +/// top, the cone and the bore. +#[test] +fn a_countersink_beside_a_wall_stays_below_the_face() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 8, "corner": [0, 0, 0]})); + run(&mut s, "solid.box", json!({"length": 40, "width": 10, "height": 30, "corner": [0, 30, 8], "operation": "join"})); + run( + &mut s, + "solid.hole", + json!({"position": [20, 23, 8], "direction": [0, 0, -1], "diameter": 6.4, "type": "countersink", "cs_diameter": 13.7, "cs_angle": 90}), + ); + let st = s.model.state(); + let [body] = st.bodies.as_slice() else { panic!("one body, got {}", st.bodies.len()) }; + assert_eq!(body.body.face_count(), 10, "the wall is not notched"); + // In the wall's foot, 0.4 mm above the face: still solid. + assert!(solid_at(&s, Vec3::new(20.0, 30.2, 8.4)), "the wall's foot is cut"); + let (rr, r, h) = (6.85_f64, 3.2_f64, 3.65_f64); + let removed = PI * h / 3.0 * (rr * rr + rr * r + r * r) + PI * r * r * (8.0 - h); + let want = 24800.0 - removed; + let got = volume(&mut s); + assert!((got - want).abs() < 1e-3, "volume {got}, want {want}"); +} diff --git a/crates/engine/src/frames_tests.rs b/crates/engine/src/frames_tests.rs index 4003c90d1..8047a3ed1 100644 --- a/crates/engine/src/frames_tests.rs +++ b/crates/engine/src/frames_tests.rs @@ -370,3 +370,28 @@ fn an_explicit_sketch_plane_is_read_in_the_frame_asked_for() { assert!(e.contains(why), "{p}: {e}"); } } + +/// #3383: a root body joined into a body of a component turned a quarter turn about X stays where +/// it is in the world: the join overlaps the plate by 10 x 5 x 5 and is one solid. When the +/// component moves on, the join follows where both bodies are placed. +#[test] +fn a_combine_tool_stays_where_it_is_placed() { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Part"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "body_name": "Plate"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "occurrence.move", json!({"occurrence": "Part:1", "axis": [1, 0, 0], "angle": "90 deg"})); + run(&mut s, "component.capture_position", json!({})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [-5, -5, -25], "operation": "new", "body_name": "Boss"})); + run(&mut s, "solid.combine", json!({"target": "Plate", "tools": ["Boss"]})); + let lumps = |s: &Session| s.model.state().body("Plate").map(|b| b.body.lumps().unwrap().len()); + assert_eq!(lumps(&s), Some(1), "the boss overlaps the plate where it is shown"); + assert!((volume(&mut s) - 16750.0).abs() < 1e-6, "{}", volume(&mut s)); + let (lo, hi) = world_bbox(&s, "Plate"); + assert!(near(lo, Vec3::new(-20.0, -10.0, -25.0)) && near(hi, Vec3::new(20.0, 5.0, 20.0)), "{lo:?} {hi:?}"); + // Raised 10 mm, the plate (z -10..30) clears the boss (z -25..-15). + run(&mut s, "occurrence.move", json!({"occurrence": "Part:1", "translate": [0, 0, 10]})); + run(&mut s, "component.capture_position", json!({})); + assert_eq!(lumps(&s), Some(2), "the boss stays where it is in the world"); + assert!((volume(&mut s) - 17000.0).abs() < 1e-6, "{}", volume(&mut s)); +}