An intersect that would leave nothing is refused instead of deleting the body (#5295) (#5303)

* claim: #5295

* An empty intersect is refused instead of deleting the body (#5295)

An intersect whose boolean came out empty removed the target body and
reported success. The shared evaluator now refuses it when nothing of a
named target would remain, when nothing of any target would remain, or
when the tools meet a target and the result is still empty. An unnamed
target the tools miss altogether is still removed, as an intersect with
every body does (#5160). Sheet metal flat machining follows the same rule.

* Sheet metal: an intersect with already removed material is refused (#5295)
This commit is contained in:
raykholo
2026-10-23 13:50:47 +00:00
committed by GitHub
parent 4b42ef50c7
commit 17bac141c8
4 changed files with 151 additions and 15 deletions
+50
View File
@@ -2427,6 +2427,33 @@ fn clear_tools_as_one(tools: Vec<Traced>) -> Vec<Traced> {
}
}
/// An intersect never deletes a body by accident (#5295): it is refused when nothing of a named
/// target would remain, when nothing of any target would remain, or when the tools meet a target
/// and the boolean still came out empty. Only an unnamed target the tools miss altogether is
/// removed, as an intersect with every body does (#5160).
pub(crate) fn empty_intersection(bodies: &[&str]) -> DocError {
let body = match bodies {
[one] => format!("`{one}`"),
[first, rest @ ..] => format!("`{first}` and {} more", rest.len()),
[] => "the target body".to_string(),
};
DocError::Invalid(format!("the intersection is empty: nothing of {body} would remain; check that the profile overlaps the body"))
}
/// The bodies a feature's boolean takes part in, and whether they were named rather than taken
/// by default (every body, or the feature's component).
pub(crate) fn boolean_scope(state: &ModelState, f: &Feature, targets: &[String]) -> (bool, Vec<String>) {
let effective = if targets.is_empty() { &f.participants } else { targets };
let all = effective.len() == 1 && effective.first().is_some_and(|t| t == "*");
let names = state
.bodies
.iter()
.filter(|b| all || if effective.is_empty() { b.component == f.component || b.feature == f.id } else { effective.contains(&b.name) })
.map(|b| b.name.clone())
.collect();
(!all && !effective.is_empty(), names)
}
/// [`apply_op`] with tools whose lineage is known: the bodies it makes or changes keep theirs.
fn apply_traced(state: &mut ModelState, f: &Feature, tools: Vec<Traced>, op: Operation, targets: &[String]) -> Result<()> {
let tools = if op == Operation::Intersect { intersection_tool_union(tools)? } else { tools };
@@ -2434,6 +2461,7 @@ fn apply_traced(state: &mut ModelState, f: &Feature, tools: Vec<Traced>, op: Ope
// of its component (and what it made itself): other components are left alone.
let targets: &[String] = if targets.is_empty() { &f.participants } else { targets };
let all = targets.len() == 1 && targets.first().is_some_and(|t| t == "*");
let named = !all && !targets.is_empty();
let target_idx: Vec<usize> = if all {
(0..state.bodies.len()).collect()
} else if targets.is_empty() {
@@ -2568,6 +2596,24 @@ fn apply_traced(state: &mut ModelState, f: &Feature, tools: Vec<Traced>, op: Ope
None => None,
};
}
if op == Operation::Intersect && acc.as_ref().is_none_or(|b| b.body.face_count() == 0) {
let Some(mb) = state.bodies.get(ti) else { continue };
// A tool that meets the body yet leaves nothing is a failed boolean, not an empty result.
let mut met = false;
if !named && !mb.body.is_mesh() {
for t in &tools {
if mb.body.meets(&tool_in(t, into)?.body)? {
met = true;
break;
}
}
}
if named || met {
return Err(empty_intersection(&[mb.name.as_str()]));
}
remove.push(ti);
continue;
}
match acc {
Some(b) => {
if let Some(mb) = state.bodies.get_mut(ti) {
@@ -2577,6 +2623,10 @@ fn apply_traced(state: &mut ModelState, f: &Feature, tools: Vec<Traced>, op: Ope
None => remove.push(ti),
}
}
if op == Operation::Intersect && target_idx.iter().all(|i| remove.contains(i)) {
let names: Vec<&str> = target_idx.iter().filter_map(|i| state.bodies.get(*i)).map(|b| b.name.as_str()).collect();
return Err(empty_intersection(&names));
}
let mut i = 0;
state.bodies.retain(|_| {
let keep = !remove.contains(&i);
+11
View File
@@ -1345,6 +1345,9 @@ fn sheet_prism_cut(
} else {
let material = sh.flat_material()?;
if material.is_empty() {
if operation == Operation::Intersect && super::boolean_scope(st, f, targets).0 {
return Err(super::empty_intersection(&[sh.body.as_str()]));
}
// Empty exact material removes geometry and metadata together. Budget or
// topology errors propagate; they are never mistaken for an empty blank.
plans.push((sh.body.clone(), None));
@@ -1356,6 +1359,14 @@ fn sheet_prism_cut(
}
}
}
if operation == Operation::Intersect {
// Flat material is exact: an empty one is a true miss, removed only while some target remains.
let (_, scope) = super::boolean_scope(st, f, targets);
let emptied: Vec<&str> = plans.iter().filter(|(_, r)| r.is_none()).map(|(name, _)| name.as_str()).collect();
if !emptied.is_empty() && scope.iter().all(|b| emptied.contains(&b.as_str())) {
return Err(super::empty_intersection(&emptied));
}
}
let handled = plans.iter().map(|(name, _)| name.clone()).collect();
if !notes.is_empty() {
append_warning(warning, notes.join("; "));
@@ -1223,3 +1223,78 @@ fn extrude_cut_into_a_rounded_block_top() {
let v = before - volume(&cut, "Body1");
assert!((v - taken).abs() < 0.05, "took {v}, expected {taken}");
}
#[test]
fn empty_intersection_is_refused_without_changing_the_design() -> crate::Result<()> {
for command in ["solid.extrude", "solid.box", "solid.combine"] {
for x in [5, 20] {
let mut s = Session::default();
s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Base"}))?;
s.execute("solid.box", &json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":"Tool","operation":"new"}))?;
s.execute("sketch.create", &json!({"plane":"XY"}))?;
s.execute("sketch.rectangle.two_point", &json!({"p0":[x,0],"p1":[x+10,10]}))?;
s.execute("sketch.finish", &json!({}))?;
let before = s.doc.to_json();
let params = match command {
"solid.combine" => json!({"target":"Base","tools":["Tool"],"operation":"intersect"}),
"solid.box" => json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"operation":"intersect","targets":["Base"]}),
_ => json!({"distance":10,"operation":"intersect","targets":["Base"]}),
};
let result = s.execute(command, &params);
if x == 20 {
let error = result.err().ok_or_else(|| crate::EngineError::Other(format!("{command} accepted an empty intersection")))?;
assert!(
error.to_string().contains("the intersection is empty: nothing of `Base` would remain; check that the profile overlaps the body"),
"{error}"
);
assert_eq!(s.doc.to_json(), before);
assert_eq!(s.model.state().bodies.len(), 2);
assert!((volume(&s, "Base") - 1000.0).abs() < 1e-6);
assert!((volume(&s, "Tool") - 1000.0).abs() < 1e-6);
} else {
result?;
assert!((volume(&s, "Base") - 500.0).abs() < 1e-6);
}
}
}
Ok(())
}
#[test]
fn empty_intersection_in_a_saved_design_fails_and_keeps_the_target() -> crate::Result<()> {
let mut s = Session::default();
s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Base"}))?;
s.execute("solid.box", &json!({"length":10,"width":10,"height":40,"body_name":"Tall","operation":"new"}))?;
s.execute("sketch.create", &json!({"plane":"XY","offset":5}))?;
s.execute("sketch.rectangle.two_point", &json!({"p0":[0,0],"p1":[10,10]}))?;
s.execute("sketch.finish", &json!({}))?;
let result = s.execute("solid.extrude", &json!({"distance":10,"operation":"intersect","targets":["Tall","Base"]}))?;
let id = result["feature"].as_u64().ok_or_else(|| crate::EngineError::Other("missing feature id".into()))?;
assert!((volume(&s, "Base") - 500.0).abs() < 1e-6);
let mut doc = solidcraft_doc::Document::from_json(&s.doc.to_json())?;
if let Some(f) = doc.feature_mut(id)
&& let solidcraft_doc::FeatureKind::Extrude { extent, .. } = &mut f.kind
{
extent.start_offset = Some("20 mm".into());
}
let reopened = Session::new(solidcraft_doc::Document::from_json(&doc.to_json())?);
assert!(reopened.model.result(id).and_then(|r| r.error.as_ref()).is_some_and(|e| e.contains("the intersection is empty")));
assert_eq!(reopened.model.state().bodies.len(), 2);
assert!((volume(&reopened, "Tall") - 4000.0).abs() < 1e-6);
assert!((volume(&reopened, "Base") - 1000.0).abs() < 1e-6);
Ok(())
}
#[test]
fn intersect_with_every_body_still_drops_the_ones_it_misses() -> crate::Result<()> {
let mut s = Session::default();
s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Near"}))?;
s.execute("solid.box", &json!({"corner":[30,0,0],"length":10,"width":10,"height":10,"body_name":"Far","operation":"new"}))?;
s.execute("sketch.create", &json!({"plane":"XY"}))?;
s.execute("sketch.rectangle.two_point", &json!({"p0":[0,0],"p1":[5,10]}))?;
s.execute("sketch.finish", &json!({}))?;
s.execute("solid.extrude", &json!({"distance":10,"operation":"intersect"}))?;
assert_eq!(s.model.state().bodies.len(), 1);
assert!((volume(&s, "Near") - 500.0).abs() < 1e-6);
Ok(())
}
+15 -15
View File
@@ -247,15 +247,16 @@ fn unsupported_sheet_machining_is_atomic_but_true_no_change_is_allowed() {
}
#[test]
fn empty_sheet_intersection_removes_geometry_and_metadata_together() {
fn empty_sheet_intersection_keeps_geometry_and_metadata_together() {
let mut s = Session::default();
base(&mut s, 100.0, 60.0);
rectangle_tool(&mut s, "Outside", [120.0, 20.0], [130.0, 30.0]);
run(&mut s, "solid.extrude", json!({"sketch":"Outside","through_all":true,"direction":"symmetric","operation":"intersect"}));
assert!(s.model.state().bodies.is_empty());
assert!(s.model.state().sheets.is_empty());
assert!(s.execute("sheet.unfold", &json!({})).is_err());
run(&mut s, "edit.undo", json!({}));
let before = s.doc.to_json();
let result = s.execute("solid.extrude", &json!({"sketch":"Outside","through_all":true,"direction":"symmetric","operation":"intersect"}));
assert!(result.as_ref().err().is_some_and(|e| e.to_string().contains("the intersection is empty")), "{result:?}");
assert_eq!(s.doc.to_json(), before);
assert_eq!(s.model.state().bodies.len(), 1);
assert_eq!(s.model.state().sheets.len(), 1);
assert!((volume(&mut s) - 15000.0).abs() < 1e-6);
}
@@ -390,8 +391,8 @@ fn deleting_sheet_material_prunes_cosmetic_threads_and_undo_restores_them() {
run(&mut s, "sheet.flange", json!({"sketch":"ThreadPlate","profiles":[{"point":[10,10]}]}));
run(&mut s, "solid.thread", json!({"face":[55,30,1],"designation":"M10"}));
assert_eq!(s.model.state().threads.len(), 1);
rectangle_tool(&mut s, "Outside", [120.0, 20.0], [130.0, 30.0]);
run(&mut s, "solid.extrude", json!({"sketch":"Outside","through_all":true,"direction":"symmetric","operation":"intersect"}));
rectangle_tool(&mut s, "All", [-10.0, -10.0], [110.0, 70.0]);
run(&mut s, "solid.extrude", json!({"sketch":"All","through_all":true,"direction":"symmetric","operation":"cut"}));
assert!(s.model.state().bodies.is_empty());
assert!(s.model.state().sheets.is_empty());
assert!(s.model.state().threads.is_empty());
@@ -2237,18 +2238,17 @@ fn partial_depth_intersect_keeps_disconnected_tool_islands_and_annular_curves()
}
#[test]
fn partial_depth_intersect_deletes_material_already_removed_by_a_pocket_atomically() {
fn partial_depth_intersect_of_material_already_removed_by_a_pocket_is_refused() {
let mut s = Session::default();
base(&mut s, 100.0, 60.0);
rectangle_tool(&mut s, "Removed", [20.0, 20.0], [30.0, 30.0]);
run(&mut s, "solid.extrude", json!({"sketch":"Removed","distance":1,"operation":"cut"}));
run(&mut s, "solid.extrude", json!({"sketch":"Removed","distance":1,"operation":"intersect"}));
assert!(s.model.state().bodies.is_empty());
assert!(s.model.state().sheets.is_empty());
run(&mut s, "edit.undo", json!({}));
let before = s.doc.to_json();
let result = s.execute("solid.extrude", &json!({"sketch":"Removed","distance":1,"operation":"intersect"}));
assert!(result.as_ref().err().is_some_and(|e| e.to_string().contains("the intersection is empty")), "{result:?}");
assert_eq!(s.doc.to_json(), before);
assert_eq!(s.model.state().sheets.len(), 1);
assert!((volume(&mut s) - 14900.0).abs() < 1e-6);
run(&mut s, "edit.redo", json!({}));
assert!(s.model.state().bodies.is_empty());
}
#[test]