From 98cd67f029d392f44858b1823d4d83e3f19dffc1 Mon Sep 17 00:00:00 2001 From: raykholo Date: Wed, 21 Oct 2026 00:54:09 +0000 Subject: [PATCH] Joins, cuts and intersects meet their tools where they are shown, across placed components (#3383) (#3384) * claim: #3383 * Combine: tools from another component meet the target where they are shown (#3383) Bodies are evaluated in their own component's frame and an occurrence's placement is applied only for display. Combine passed tool bodies to the boolean untouched, so a tool in a component placed differently from the target's was read as if its coordinates were in the target's frame: a join that overlapped on screen gave two separate shells, and cuts and intersects missed the same way. Any placement difference did it, a turn or a plain move, in either direction. Combine now moves each tool by the inverse of the target's placement times the tool's own, the same placement used to show the body, keeping face lineage. A tool placed exactly like the target is left untouched, so combines within one component give the same result as before. Moving an occurrence now re-evaluates a combine that depends on it. * Joins, cuts and intersects draw their tools where they are shown (#3383) A primitive, extrude, revolve, loft, sweep, pipe or coil that joins, cuts or intersects bodies draws its tool in its own component's frame, but each body is kept in its own component's. A target in a component placed differently (an occurrence moved or turned, or a body moved into it) met the tool as if the tool's coordinates were in the target's frame: a join that overlapped on screen gave a separate lump 100 mm away, and cuts missed the same way. While such a feature evaluates, the tool now goes into each body's frame (the inverse of the body's placement times the feature's component's) wherever the join, cut or intersect meets it, and a body joined into one placed differently is moved into its frame. Bodies placed as the feature is are left untouched, so results within one component are unchanged. Features that name the bodies they change re-evaluate when an occurrence moves. This also settles the moved-fastener cut of #439 (Combine, earlier commit). * Through all and an extrude's contact tests see targets where they are shown (#3383) An extrude or revolve measured its through-all length, and tested where its tools meet the targets (a profile on a target's face, coplanar growth, holes over empty space, taper run-on), on the targets as stored in their own component's frame. With the tool now moved into a target placed differently, a through-all cut drawn from the root under a cube in a component moved 100 mm up was cut only as far as the cube is tall in its own frame, and missed it. These features now see the bodies they change that are placed differently moved into their own component's frame, the same moves the tools are taken back through, so the length reaches the target where it is shown. Bodies placed as the feature is are read as before. --- crates/doc/src/eval.rs | 181 +++++++++++++++++++++- crates/engine/src/cmd/occurrence_tests.rs | 72 +++++++++ 2 files changed, 247 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 580316fde..41f17c058 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1163,7 +1163,12 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 { }; // A mirror of placed bodies follows where they are placed. let placed_mirror = matches!(&f.kind, FeatureKind::Mirror { placements, .. } if !placements.is_empty()); - if to_object || placed_mirror { + // A combine moves tools placed differently from its target into the target's frame (#3383). + let combine = matches!(&f.kind, FeatureKind::Combine { .. }); + if !to_object && !combine && drawn_tools_change_bodies(&f.kind) { + return drawn_tools_digest(doc, f); + } + if to_object || placed_mirror || combine { return if doc.occurrences.is_empty() && doc.body_offsets.is_empty() { 0 } else { placements_hash(doc) }; } let FeatureKind::Sketch { plane, sketch } = &f.kind else { return 0 }; @@ -1957,9 +1962,10 @@ fn apply_traced(state: &mut ModelState, f: &Feature, tools: Vec, op: Ope return Ok(()); } if matches!(op, Operation::Cut | Operation::Intersect) { - let bodies: Vec = tools.iter().map(|t| t.body.clone()).collect(); for &i in &target_idx { if let Some(mb) = state.bodies.get(i).filter(|b| state.sheets.iter().any(|s| s.body == b.name)) { + let m = tool_frame(&mb.name); + let bodies: Vec = tools.iter().map(|t| tool_in(t, m).map(|t| t.body)).collect::>()?; sheet_boolean_unchanged(&mb.body, &bodies, op)?; } } @@ -2019,16 +2025,24 @@ fn apply_traced(state: &mut ModelState, f: &Feature, tools: Vec, op: Ope if mb.body.is_mesh() || (!met.is_empty() && sheet) { continue; } - if mb.body.meets(&tool.body)? { + // Each body is met where it is shown: the tool goes into its frame (#3383). + if mb.body.meets(&tool_in(tool, tool_frame(name))?.body)? { met.push(name.clone()); } } let Some(keep) = met.first().or(live.first()).cloned() else { return Ok(()) }; let Some(base) = state.body(&keep).map(ModelBody::traced) else { continue }; - let mut acc = union(&base, tool)?; + let into_keep = tool_frame(&keep); + let mut acc = union(&base, &tool_in(tool, into_keep)?)?; for name in met.iter().skip(1) { if let Some(b) = state.body(name) { - acc = union(&acc, &b.traced())?; + // A body placed differently from the one kept joins it where it is shown. + let from = match tool_frame(name) { + Some(m) => crate::mat_inverse(&m), + None => Some(crate::IDENTITY), + }; + let m = from.map(|from| crate::mat_mul(&into_keep.unwrap_or(crate::IDENTITY), &from)).filter(|m| !crate::is_identity(m)); + acc = union(&acc, &tool_in(&b.traced(), m)?)?; } } let absorbed: std::collections::BTreeSet = met.into_iter().skip(1).collect(); @@ -2051,7 +2065,10 @@ fn apply_traced(state: &mut ModelState, f: &Feature, tools: Vec, op: Ope let mut remove = Vec::new(); for &ti in &target_idx { let Some(mut acc) = state.bodies.get(ti).map(|b| Some(b.traced())) else { continue }; + // The tools meet the target where it is shown: in its frame (#3383). + let into = state.bodies.get(ti).and_then(|b| tool_frame(&b.name)); for t in &tools { + let t = &tool_in(t, into)?; acc = match acc { Some(a) => kernel::boolean(&a.body, &t.body, bop)?.map(|r| Traced::step(r, &[&a, t])), None => None, @@ -3564,6 +3581,9 @@ fn feature_tools_with_constructor( let n = ss.plane.normal(); let tst = if extent.to.is_some() || extent.from.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; + // Through all, and where the tool meets its targets, is measured where they are shown. + let shown = targets_as_shown(st, f, &crate::plain(targets))?; + let st: &ModelState = &shown; // The face names follow `face_points`: To, then From. let name = |k: usize| f.face_names.get(k).map(String::as_str); let (to_name, from_name) = if extent.to.is_some() { (name(0), name(1)) } else { (None, name(0)) }; @@ -3921,6 +3941,9 @@ fn feature_tools_with_constructor( let (o, d) = revolve_axis(&ss, axis)?; // To Object is in this feature's component frame: the model as seen from there. let tst = if to.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; + // Where the tool meets its targets is measured where they are shown (#3383). + let shown = targets_as_shown(st, f, &feature_op(f).1)?; + let st: &ModelState = &shown; let angles = if to.is_some() { (0.0, None) } else { @@ -5150,6 +5173,8 @@ fn chamfer_with( } fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: &mut ModelState, warning: &mut Option) -> Result<()> { + // Its tools meet bodies in other placements where those are shown (#3383). + let _frames = ToolFrames::install(doc, f, st); match &f.kind { FeatureKind::BodyTransfer { bodies, from, to, transform } => { crate::body_transfer::evaluate(doc, st, &crate::plain(bodies), *from, *to, *transform) @@ -5718,10 +5743,26 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: if tools.iter().any(|t| t == target) { return Err(DocError::Invalid("a body cannot be combined with itself".into())); } + // Each body is kept in its own component's frame: a tool placed differently from the + // target is moved into the target's frame, so it is combined where it is shown (#3383). + // A tool placed exactly as the target is left as it is. + let target_world = st.body(target).map(|b| body_world(doc, b)); let mut tb = Vec::new(); for t in tools { match st.body(t) { - Some(b) => tb.push(b.traced()), + Some(b) => { + let traced = b.traced(); + let world = body_world(doc, b); + match target_world.filter(|w| *w != world) { + Some(w) => { + let into_target = crate::mat_inverse(&w) + .ok_or_else(|| DocError::Invalid(format!("`{target}` is placed where it cannot be combined")))?; + let rel = crate::mat_mul(&into_target, &world); + tb.push(Traced::step(kernel::transform_matrix(&b.body, rel)?, &[&traced])); + } + None => tb.push(traced), + } + } // Designs saved before #2247 combined the pieces a cut split off a body that // was already several pieces (`Posts`, `Posts (1)`). A cut keeps them in one // body now: the piece is in `Posts`, which is a tool too or the body joined to. @@ -6006,6 +6047,134 @@ fn plane_reads_geometry(plane: &PlaneRef) -> bool { } } +/// Where a body's geometry is placed in the world: through its component's placement and any +/// offset it was moved into that component with (as [`state_in_frame_at`] places it). +fn body_world(doc: &Document, mb: &ModelBody) -> Mat { + let m = doc.component_transform(doc.model_body_component(mb)); + doc.model_body_offset(mb).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m) +} + +thread_local! { + /// While a feature whose tools are drawn in its own component's frame is evaluated: each body + /// placed differently, with the matrix from that frame into the body's own (#3383). + static TOOL_FRAMES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Whether a feature joins, cuts or intersects with tools drawn in its own component's frame: a +/// primitive, or a solid built from its sketches. (A combine's tools are bodies, each in its own +/// frame; it moves them itself.) +fn drawn_tools_change_bodies(kind: &FeatureKind) -> bool { + match kind { + FeatureKind::Box { operation, .. } + | FeatureKind::Cylinder { operation, .. } + | FeatureKind::Sphere { operation, .. } + | FeatureKind::Torus { operation, .. } + | FeatureKind::Extrude { operation, .. } + | FeatureKind::Revolve { operation, .. } + | FeatureKind::Loft { operation, .. } + | FeatureKind::Sweep { operation, .. } + | FeatureKind::Pipe { operation, .. } + | FeatureKind::Coil { operation, .. } => *operation != Operation::NewBody, + _ => false, + } +} + +/// The frames of [`TOOL_FRAMES`] for the feature being evaluated; what was there before is put +/// back when it is dropped. +struct ToolFrames(Vec<(String, Mat)>); + +impl ToolFrames { + /// For a feature with drawn tools (see [`drawn_tools_change_bodies`]): the bodies placed + /// differently from its component, so its tools meet them where they are shown (#3383). + fn install(doc: &Document, f: &Feature, st: &ModelState) -> Option { + if !drawn_tools_change_bodies(&f.kind) || (doc.occurrences.is_empty() && doc.body_offsets.is_empty()) { + return None; + } + let frame = doc.component_transform(f.component); + let frames: Vec<(String, Mat)> = st + .bodies + .iter() + .filter_map(|b| { + let world = body_world(doc, b); + (world != frame).then(|| crate::mat_inverse(&world).map(|inv| (b.name.clone(), crate::mat_mul(&inv, &frame)))).flatten() + }) + .collect(); + if frames.is_empty() { + return None; + } + Some(ToolFrames(TOOL_FRAMES.with(|t| std::mem::replace(&mut *t.borrow_mut(), frames)))) + } +} + +impl Drop for ToolFrames { + fn drop(&mut self) { + let before = std::mem::take(&mut self.0); + TOOL_FRAMES.with(|t| *t.borrow_mut() = before); + } +} + +/// [`placement_digest`] of a feature with drawn tools: the placements, when it names the bodies +/// it changes (they may lie in another component, where its tools meet them, #3383); nothing +/// otherwise, as it then changes only bodies of its own component. +fn drawn_tools_digest(doc: &Document, f: &Feature) -> u64 { + let targets = match &f.kind { + FeatureKind::Extrude { targets, .. } + | FeatureKind::Revolve { targets, .. } + | FeatureKind::Loft { targets, .. } + | FeatureKind::Sweep { targets, .. } + | FeatureKind::Pipe { targets, .. } + | FeatureKind::Coil { targets, .. } => !targets.is_empty(), + _ => false, + }; + if (!targets && f.participants.is_empty()) || (doc.occurrences.is_empty() && doc.body_offsets.is_empty()) { + return 0; + } + placements_hash(doc) +} + +/// The matrix taking the evaluated feature's drawn tools into body `name`'s frame (`None`: the +/// same frame). +fn tool_frame(name: &str) -> Option { + TOOL_FRAMES.with(|t| t.borrow().iter().find(|(n, _)| n == name).map(|(_, m)| *m)) +} + +/// The model as the evaluated feature's drawn tools meet it: the bodies it changes (`targets`, +/// else the feature's participants; `*` for all) that are placed differently, moved into its +/// component's frame. A through-all extent, and every test of where a tool meets its targets, is +/// measured on it, so a target in another, moved component is met where it is shown (#3383). +/// The model itself when no such body is placed differently. +fn targets_as_shown<'a>(st: &'a ModelState, f: &Feature, targets: &[String]) -> Result> { + let names: &[String] = if targets.is_empty() { &f.participants } else { targets }; + let all = names.iter().any(|n| n == "*"); + let mut out: Option = None; + for (i, b) in st.bodies.iter().enumerate() { + if !(all || names.contains(&b.name)) { + continue; + } + let Some(back) = tool_frame(&b.name).and_then(|m| crate::mat_inverse(&m)) else { continue }; + let shown = out.get_or_insert_with(|| st.clone()); + let mut moved = ModelBody::new(b.name.clone(), kernel::transform_matrix(&b.body, back)?, b.feature); + moved.component = b.component; + moved.transferred = b.transferred; + moved.names = crate::naming::NameCell::same(b); + if let Some(slot) = shown.bodies.get_mut(i) { + *slot = moved; + } + } + Ok(match out { + Some(shown) => std::borrow::Cow::Owned(shown), + None => std::borrow::Cow::Borrowed(st), + }) +} + +/// `tool` moved by `m` (unchanged for `None`). +fn tool_in(tool: &Traced, m: Option) -> Result { + match m { + Some(m) => Ok(Traced::step(kernel::transform_matrix(&tool.body, m)?, &[tool])), + None => Ok(tool.clone()), + } +} + pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std::borrow::Cow<'a, ModelState> { state_in_frame_at(doc, st, comp, doc.component_transform(comp)) } diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index 310a6e8f1..365710557 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -662,3 +662,75 @@ fn matrix_move_orthonormalises_rounding_and_refuses_what_is_not_rigid() { assert_eq!(s.doc.occurrences.iter().find(|o| o.id == occ).unwrap().transform, before); run(&mut s, "occurrence.move", json!({"occurrence": occ, "matrix": rounded, "tolerance": 1e-3})); } + +/// #3383: a combine across components meets the tool where it is shown, not where its numbers +/// would be in the target's own frame. The plate in a component turned a quarter about X sits at +/// y -10..0, z -20..20; the boss in the root overlaps it by 10 x 5 x 5. The reverse (a peg in the +/// turned component cut from a root plate) removes 10 x 10 x 5 of it, not 10 x 10 x 10. +#[test] +fn combine_across_a_turned_occurrence_meets_the_tool_where_it_is_shown() { + let volume = |s: &Session, name: &str| s.model.state().body(name).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).unwrap_or(0.0); + let turned = |s: &mut Session, body: Value| { + created(s, "Part"); + run(s, "solid.box", body); + run(s, "component.activate", json!({"component": "root"})); + run(s, "occurrence.move", json!({"occurrence": "Part:1", "axis": [1, 0, 0], "angle": "90 deg"})); + run(s, "component.capture_position", json!({})); + }; + let mut s = Session::default(); + turned(&mut s, json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "body_name": "Plate"})); + 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"]})); + assert_eq!(s.model.state().body("Plate").map(|b| b.body.shell_count()), Some(1)); + let want = 40.0 * 40.0 * 10.0 + 10.0 * 10.0 * 10.0 - 10.0 * 5.0 * 5.0; + assert!((volume(&s, "Plate") - want).abs() < 1e-6 * want, "{} vs {want}", volume(&s, "Plate")); + + let mut s = Session::default(); + turned(&mut s, json!({"length": 10, "width": 10, "height": 10, "corner": [-5, -5, 0], "body_name": "Peg"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [-20, -20, 0], "operation": "new", "body_name": "Base"})); + run(&mut s, "solid.combine", json!({"target": "Base", "tools": ["Peg"], "operation": "cut"})); + let want = 40.0 * 40.0 * 10.0 - 10.0 * 10.0 * 5.0; + assert!((volume(&s, "Base") - want).abs() < 1e-6 * want, "{} vs {want}", volume(&s, "Base")); +} + +/// #3383: a feature joining into a body of another, placed component draws its tool where the +/// tool is shown, as Combine does. Part is moved 100 mm along x, so its 10 mm cubes sit at x 100..110 +/// and 120..130; a box and an extrude drawn from the root over each add 4 x 4 x 5 to it in one +/// piece, not a separate lump 100 mm further on. A through-all cut is as long as the target is +/// far where it is shown. +#[test] +fn joins_into_a_moved_occurrence_meet_the_tool_where_it_is_shown() { + let volume = |s: &Session, name: &str| s.model.state().body(name).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).unwrap_or(0.0); + let mut s = Session::default(); + created(&mut s, "Part"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "operation": "new", "body_name": "B"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "occurrence.move", json!({"occurrence": "Part:1", "translate": [100, 0, 0]})); + run(&mut s, "component.capture_position", json!({})); + run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 15, "corner": [103, 3, 0], "operation": "join", "targets": ["A"]})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [123, 3], "p1": [127, 7]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 15, "operation": "join", "targets": ["B"]})); + let want = 10.0 * 10.0 * 10.0 + 4.0 * 4.0 * 5.0; + for b in ["A", "B"] { + assert_eq!(s.model.state().body(b).map(|b| b.body.shell_count()), Some(1), "{b}"); + assert!((volume(&s, b) - want).abs() < 1e-6 * want, "{b}: {} vs {want}", volume(&s, b)); + } + + // Through all reaches the target where it is shown: Part moved 100 mm along x and up, a cut + // drawn on the root's XY plane goes 100 mm up through its cube, not 10 mm. + let mut s = Session::default(); + created(&mut s, "Part"); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "C"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "occurrence.move", json!({"occurrence": "Part:1", "translate": [100, 0, 100]})); + run(&mut s, "component.capture_position", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [103, 3], "p1": [107, 7]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"through_all": true, "operation": "cut", "targets": ["C"]})); + let want = 10.0 * 10.0 * 10.0 - 4.0 * 4.0 * 10.0; + assert!((volume(&s, "C") - want).abs() < 1e-6 * want, "C: {} vs {want}", volume(&s, "C")); +}