diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c2e5467cc..aed0e237c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -89,6 +89,45 @@ fn fillet_as_wide_as_a_face_rounds_it_off() { assert!(s.execute("solid.fillet", &json!({"edges": [[21, 0, 10]], "radius": 3.5})).is_err()); } +/// The owner's ruling of 2026-10-30: two edges of a 20 mm box rounded r2 in one fillet (they +/// meet in a mitre at the corner (20, 0, 20), the upright edge there sharp), then the upright edge +/// r3 in a second fillet, whose tangent chain takes the mitre's seam with it. The corner is one +/// smooth patch, the body rounding all three at once makes (kernel `fillet_radii` of the box with +/// each edge's radius: 10 faces, 7928.743041 mm³); the r2 rounds keep their names, and the r3 +/// round and the corner patch are the second fillet's. +#[test] +fn a_later_round_at_a_mitred_corner_is_blended_with_the_rounds_there() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Box"})); + let first = run(&mut s, "solid.fillet", json!({"edges": [[20, 10, 20], [10, 0, 20]], "radius": 2}))["feature"].as_u64().unwrap(); + // A point halfway along each r2 round, at 45° between its faces. + let k = 2.0 - 2.0_f64.sqrt(); + let rounds = [solidcraft_geom::Vec3::new(20.0 - k, 10.0, 20.0 - k), solidcraft_geom::Vec3::new(10.0, k, 20.0 - k)]; + let named = |s: &mut Session, at: solidcraft_geom::Vec3| { + let st = s.model.state(); + let (d, index) = solidcraft_doc::appearance::nearest_face(st.body("Box").unwrap(), at).unwrap(); + // Found on the display mesh, whose facets lie within its chord of the faces. + assert!(d < 0.05, "{at:?} is {d} off the nearest face"); + let faces = run(s, "model.faces", json!({"body": "Box"}))["faces"].as_array().cloned().unwrap_or_default(); + faces.iter().find(|f| f["index"].as_u64() == Some(index as u64)).and_then(|f| f["name"].as_str()).unwrap_or_default().to_string() + }; + let before: Vec = rounds.iter().map(|p| named(&mut s, *p)).collect(); + assert!(before.iter().all(|n| n.starts_with(&format!("F{first}:blend:"))), "{before:?}"); + let second = run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 3}))["feature"].as_u64().unwrap(); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + let v = volume(&mut s); + assert!((v - 7928.743041).abs() < 1e-5, "{v}"); + let faces = run(&mut s, "model.faces", json!({"body": "Box"}))["faces"].as_array().cloned().unwrap_or_default(); + assert_eq!(faces.len(), 10); + let after: Vec = rounds.iter().map(|p| named(&mut s, *p)).collect(); + assert_eq!(after, before); + // The r3 round (halfway up, at 45°) and the corner patch: the two faces the second fillet made. + let k3 = 3.0 - 4.5_f64.sqrt(); + assert!(named(&mut s, solidcraft_geom::Vec3::new(20.0 - k3, k3, 10.0)).starts_with(&format!("F{second}:blend:"))); + let made = faces.iter().filter(|f| f["name"].as_str().is_some_and(|n| n.starts_with(&format!("F{second}:")))).count(); + assert_eq!(made, 2, "{faces:?}"); +} + #[test] fn join_extrude_from_a_chamfered_top_face() { let mut s = Session::default(); diff --git a/crates/engine/src/tests/mesh_convert.rs b/crates/engine/src/tests/mesh_convert.rs index d7df821aa..ee76b3a97 100644 --- a/crates/engine/src/tests/mesh_convert.rs +++ b/crates/engine/src/tests/mesh_convert.rs @@ -141,7 +141,8 @@ fn exported_binary_stl_with_a_bore_reconstructs_analytic_faces() { assert!(!body.is_mesh()); assert!(body.validity().is_empty()); assert_eq!(solidcraft_kernel::measure(body).unwrap().merged.face_types.get("cylinder"), Some(&1)); - assert_eq!(body.faces(0.01).unwrap().len(), 10); + // The L's six sides, the two caps and the bore, one full-turn wall. + assert_eq!(body.faces(0.01).unwrap().len(), 9); std::fs::remove_file(path).unwrap(); } diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs index 79b3512a0..f00f6d35f 100644 --- a/crates/kernel/src/blend_corner.rs +++ b/crates/kernel/src/blend_corner.rs @@ -1,12 +1,249 @@ //! Fillets with a radius per edge. SMLib rounds every picked edge at its own radius in one //! blend, with the corners where the rounds meet: an end in the face beyond, two rounds trimming //! each other, or a corner patch where three meet. +//! +//! A later round at a corner where earlier rounds already meet in a mitre (the owner's ruling of +//! 2026-10-30) makes the corner all of them would have made rounded at once: one smooth patch, +//! the mitre gone. A body made by constant-radius rounds keeps what they were made on and which +//! edges they rounded at which radius ([`Rounds`]); a later round reaching such a corner +//! ([`later_corners`]) blends the earlier rounds' edges, from the earliest of the rounds that +//! meet there on, with the new edges in one SMLib blend of the body before them, and the result's +//! history is put over the body the later round was given ([`rebase`]): an earlier round's face +//! is that face, trimmed anew; the corner patch, and every face the new edges make, is the later +//! round's. The mitre's seam is no edge to round on its own: picked (a tangent chain reaches it +//! from the new edge), it only says the corner is blended again. + +use std::collections::BTreeSet; use solidcraft_geom::Vec3; use crate::body::Body; +use crate::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, History}; use crate::{KernelError, Result}; +/// The constant-radius rounds that made a body ([`crate::fillet`], [`fillet_radii`]): the body +/// they were made on, and each edge they rounded (its index in that body's edge order) with its +/// radius. The body's history is over `before`. +#[derive(Clone, Debug)] +pub(crate) struct Rounds { + pub(crate) before: Body, + pub(crate) edges: Vec<(usize, f64)>, +} + +/// A later round at corners where earlier rounds meet ([`later_corners`]): what is blended in +/// one go, and what puts its history over the body the later round was given. +pub(crate) struct Later { + /// The body before the earliest of the rounds that meet at the new edges' corners. + pub(crate) base: Body, + /// The edges blended on `base` (its edge order) with their radii: the edges of every round + /// from that earliest on, and the new edges. + pub(crate) edges: Vec<(usize, f64)>, + /// The body over `base`: the histories of those rounds composed. + chain: History, + /// The new edges: each one's index in the body, and in `base`. + new: Vec<(usize, usize)>, + /// The body's mitre seams at the new edges' corners, which the corner patches replace. + seams: Vec, +} + +/// The history of `body` over the body `levels` rounds back ([`Rounds::before`] taken that many +/// times), composed; `None` when a step has no record or history, or for no levels. +fn down(body: &Body, levels: usize) -> Option { + let mut at = body.clone(); + let mut composed: Option = None; + for _ in 0..levels { + let rounds = at.rounds.clone()?; + let step = at.history().filter(|h| h.operands == 1)?.clone(); + composed = Some(match composed { + None => step, + Some(h) => h.substituted(0, &step).ok()?, + }); + at = rounds.before.clone(); + } + composed +} + +/// The operand edge `edge` of a result comes from, through `h`, when it is (a piece of) one. +fn edge_origin(h: &History, edge: usize) -> Option { + match h.edges.get(edge).map(|e| e.origins.as_slice()) { + Some([EdgeOrigin::Edge { operand: 0, edge }]) => Some(*edge), + _ => None, + } +} + +/// Faces a blend made in place of edges (rounds, their corner patches), through `h`. +fn rounds_of(h: &History) -> Vec { + h.faces + .iter() + .map(|f| f.change == Change::Generated && !f.origins.is_empty() && f.origins.iter().all(|o| matches!(o, FaceOrigin::Edge { .. }))) + .collect() +} + +/// Is `edge` (its faces through `h`) where the rounds of different edges meet: between two of +/// `rounds` made in place of edges none of which both are (a mitre, or rounds running on into +/// each other), not between a round and its own end cap or a corner patch it is part of? +fn between_rounds(h: &History, rounds: &[bool], edge: usize) -> bool { + let round = |f: usize| rounds.get(f).copied().unwrap_or(false).then(|| h.faces.get(f)).flatten(); + match h.edges.get(edge).map(|e| e.faces.as_slice()) { + Some([f, g]) if f != g => match (round(*f), round(*g)) { + (Some(a), Some(b)) => a.origins.iter().all(|o| !b.origins.contains(o)), + _ => false, + }, + _ => false, + } +} + +/// The later rounds of `picked` (the body's edges, `sizes` their radii, as the blend resolved +/// them) when one of them reaches a corner where rounds that made the body meet: the blend to +/// make in their place, and the new edges (in the body's edge order, with their radii) the +/// body's record of rounds takes. `Ok(None)` when none does, or when the rounds are not on record +/// down to that corner. A picked seam between earlier rounds is refused unless a new edge of +/// the same radius meets it: it has no round of its own. +pub(crate) fn later_corners(body: &Body, picked: &[usize], sizes: &[f64]) -> Result)>> { + // The rounds on record, latest first: each one's body before it and the body over that. + let mut levels: Vec<(Rounds, History)> = Vec::new(); + while let Some(h) = down(body, levels.len() + 1) { + let Some(r) = (match levels.last() { + None => body.rounds.as_deref().cloned(), + Some((r, _)) => r.before.rounds.as_deref().cloned(), + }) else { + break; + }; + levels.push((r, h)); + } + let Some((_, deepest)) = levels.last() else { return Ok(None) }; + let rounds = rounds_of(deepest); + let record = body.record(); + let ends = |e: usize| record.edges.get(e).map(|e| e.vertices).unwrap_or([u32::MAX; 2]); + let (seam_picks, new): (Vec<(usize, f64)>, Vec<(usize, f64)>) = + picked.iter().copied().zip(sizes.iter().copied()).partition(|(e, _)| between_rounds(deepest, &rounds, *e)); + let corners: BTreeSet = new.iter().flat_map(|(e, _)| ends(*e)).collect(); + let seams: Vec = + (0..record.edges.len()).filter(|e| between_rounds(deepest, &rounds, *e) && ends(*e).iter().any(|v| corners.contains(v))).collect(); + for (seam, size) in &seam_picks { + let meets = new.iter().any(|(e, r)| r.to_bits() == size.to_bits() && ends(*e).iter().any(|v| ends(*seam).contains(v))); + if !meets { + return Err(KernelError::Invalid( + "fillet: a picked edge is where earlier rounds meet (a mitre), which has no round of its own: pick the edge that runs \ + into that corner, at its radius, and the corner is rounded again with it" + .into(), + )); + } + } + if seams.is_empty() { + return Ok(None); + } + // The latest round from which on every seam is between rounds on record. + let Some(level) = levels.iter().position(|(_, h)| { + let rounds = rounds_of(h); + seams.iter().all(|s| between_rounds(h, &rounds, *s)) + }) else { + return Ok(None); + }; + let Some((base, chain)) = levels.get(level).map(|(r, h)| (r.before.clone(), h.clone())) else { return Ok(None) }; + // Every round's edges from that level on, in `base`'s edge order. + let mut edges: Vec<(usize, f64)> = Vec::new(); + for (step, (r, _)) in levels.iter().enumerate().take(level + 1) { + let inner = down(&r.before, level - step); + for (e, radius) in &r.edges { + let at = match &inner { + None => Some(*e), + Some(h) => edge_origin(h, *e), + }; + let Some(at) = at else { return Ok(None) }; + edges.push((at, *radius)); + } + } + let mut mapped = Vec::with_capacity(new.len()); + for (e, radius) in &new { + let Some(at) = edge_origin(&chain, *e) else { return Ok(None) }; + mapped.push((*e, at)); + edges.push((at, *radius)); + } + Ok(Some((Later { base, edges, chain, new: mapped, seams }, new))) +} + +/// The history of `result`, the blend `later` made of its base (`h`, over the base), over the +/// body the later round was given (`body`, `later.chain` over the base): a face of the base's +/// faces is the body's face of them, kept where both kept it, else trimmed anew (split or joined +/// where they are several); an earlier round's face is that round's face in the body; a face +/// made in place of a new edge (its round, and a corner patch where it meets earlier rounds) is +/// new, made in place of the new edges and of the body's seams between the rounds it joins. +/// Each edge is the body's edge between the faces it lies between there, else where its faces +/// meet. `None` where a face has no counterpart. +pub(crate) fn rebase(h: &History, later: &Later, body: &Body) -> Option { + let chain = &later.chain; + let set = |p: &FaceProv| p.origins.iter().copied().collect::>(); + let mut faces = Vec::with_capacity(h.faces.len()); + for p in &h.faces { + let origins = set(p); + let new_edges: Vec = later + .new + .iter() + .filter(|(_, at)| origins.contains(&FaceOrigin::Edge { operand: 0, edge: *at })) + .map(|(e, _)| FaceOrigin::Edge { operand: 0, edge: *e }) + .collect(); + if !new_edges.is_empty() { + // The seams between rounds all of whose origins this face takes up. + let replaced = later.seams.iter().filter(|s| { + chain.edges.get(**s).is_some_and(|e| e.faces.iter().all(|f| chain.faces.get(*f).is_some_and(|f| set(f).is_subset(&origins)))) + }); + let mut all = new_edges; + all.extend(replaced.map(|s| FaceOrigin::Edge { operand: 0, edge: *s })); + faces.push(crate::record::generated(all)); + continue; + } + let candidates: Vec = if p.change == Change::Generated { + (0..chain.faces.len()).filter(|f| chain.faces.get(*f).is_some_and(|c| c.change == Change::Generated && set(c) == origins)).collect() + } else { + (0..chain.faces.len()) + .filter(|f| chain.faces.get(*f).is_some_and(|c| c.change != Change::Generated && c.origins.iter().any(|o| origins.contains(o)))) + .collect() + }; + let change = match candidates[..] { + [] => return None, + [f] if p.change == Change::Kept && chain.faces.get(f).is_some_and(|c| c.change == Change::Kept) => Change::Kept, + [_] => Change::Modified, + _ => Change::Merged, + }; + faces.push(FaceProv { origins: candidates.into_iter().map(|face| FaceOrigin::Face { operand: 0, face }).collect(), change }); + } + crate::record::mark_shared_split(&mut faces); + // The body's faces under each result face, and the body's edges by the faces they separate. + let under = |f: usize| -> BTreeSet { + faces + .get(f) + .filter(|p| p.change != Change::Generated) + .map(|p| p.origins.iter().filter_map(|o| if let FaceOrigin::Face { face, .. } = o { Some(*face) } else { None }).collect()) + .unwrap_or_default() + }; + let body_edges = crate::history::edge_faces(body.record()); + let edges = h + .edges + .iter() + .map(|e| { + let sides: Vec> = e.faces.iter().map(|f| under(*f)).collect(); + let same: Vec = if sides.iter().all(|s| !s.is_empty()) { + body_edges + .iter() + .enumerate() + .filter(|(_, between)| { + between.len() == sides.len() + && (between.iter().zip(&sides).all(|(f, s)| s.contains(f)) + || between.iter().rev().zip(&sides).all(|(f, s)| s.contains(f))) + }) + .map(|(edge, _)| EdgeOrigin::Edge { operand: 0, edge }) + .collect() + } else { + Vec::new() + }; + let origins = if same.is_empty() { crate::record::meeting(&e.faces, &faces) } else { same }; + EdgeProv { faces: e.faces.clone(), origins } + }) + .collect(); + Some(History { operands: 1, faces, edges }) +} + /// Fillet each edge nearest a point with its own radius. pub fn fillet_radii(body: &Body, edges: &[(Vec3, f64)]) -> Result { body.require_brep("fillet")?; diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs index 39229c613..04e843881 100644 --- a/crates/kernel/src/blend_smlib.rs +++ b/crates/kernel/src/blend_smlib.rs @@ -204,9 +204,43 @@ mod imp { sizes_ok(what, sizes)?; let picked = resolve(body, edges)?; let next = crate::blend::unfinished_chain(body, edges, &picked.edges, &picked.hidden)?; - let kind = blend_kind(kind); let tol = pick_tolerance(body); - run(body, what, &picked.edges, |b| b.blend(kind, &picked.points, sizes, tol)).map_err(|e| crate::blend::with_continuation(e, next)) + let Kind::Round = kind else { + let kind = blend_kind(kind); + return run(body, what, &picked.edges, |b| b.blend(kind, &picked.points, sizes, tol)) + .map_err(|e| crate::blend::with_continuation(e, next)); + }; + // Constant-radius rounds: the body keeps what they were made on, and a later round at a + // corner where they meet blends them again with it (crate::blend_corner). + let out = match crate::blend_corner::later_corners(body, &picked.edges, sizes)? { + Some((later, new)) => reblend(body, what, &later).map(|b| b.with_rounds(body, new)), + None => run(body, what, &picked.edges, |b| b.blend(Blend::Round, &picked.points, sizes, tol)) + .map(|b| b.with_rounds(body, picked.edges.iter().copied().zip(sizes.iter().copied()).collect())), + }; + out.map_err(|e| crate::blend::with_continuation(e, next)) + } + + /// The blend `later` makes of its base, every round from the earliest meeting the new edges' + /// corners on and the new edges in one, with its history over `body`, the body the later + /// round was given ([`crate::blend_corner::rebase`]). + fn reblend(body: &Body, what: &str, later: &crate::blend_corner::Later) -> Result { + let base = &later.base; + let mesh = base.mesh(&crate::MeshTolerance::chord((base.size() * 2e-3).max(1e-3)))?; + let mut indices = Vec::with_capacity(later.edges.len()); + let mut points = Vec::with_capacity(later.edges.len()); + let mut radii = Vec::with_capacity(later.edges.len()); + for (e, r) in &later.edges { + let line = mesh.edges.get(*e).ok_or_else(|| failed(what, "corner", "an earlier round's edge is not in the body it was made on"))?; + let (mid, _) = crate::body::polyline_mid(line); + indices.push(*e); + points.push([mid.x, mid.y, mid.z]); + radii.push(*r); + } + sizes_ok(what, &radii)?; + let tol = pick_tolerance(base); + let out = run(base, what, &indices, |b| b.blend(Blend::Round, &points, &radii, tol))?; + let history = out.history().and_then(|h| crate::blend_corner::rebase(h, later, body)); + Ok(out.with_checked_history(history, &record::counts(&[body])).inherit_regularization_protection(body)) } /// Rounds with corner setbacks: each corner point picks the body's nearest vertex (within diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 74bfcbd73..6ff7dc1fd 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -59,6 +59,10 @@ pub struct Body { /// check to the end of its feature ([`crate::validation`]): checked there as the step's own /// check would have, then let go. Answers only for this record. pub(crate) unchecked: Option>, + /// The constant-radius rounds that made this body from another, when they did + /// ([`crate::blend_corner::Rounds`]): a later round at a corner where they meet blends them + /// again with it. Anything else that makes a body leaves it out. + pub(crate) rounds: Option>, } /// The meshes made of one record (see [`Body::keeping_meshes`]), by tolerance and angle. They @@ -478,6 +482,7 @@ impl Body { display_of: None, meshes: None, unchecked: None, + rounds: None, } } @@ -638,6 +643,13 @@ impl Body { self } + /// This body as the rounds of `edges` (each an edge of `before`, in its edge order, with its + /// radius) made it from `before` ([`crate::blend_corner::Rounds`]). + pub(crate) fn with_rounds(mut self, before: &Body, edges: Vec<(usize, f64)>) -> Self { + self.rounds = Some(std::sync::Arc::new(crate::blend_corner::Rounds { before: before.clone(), edges })); + self + } + /// This body with no history: an operation whose history is not known. pub(crate) fn without_history(mut self) -> Self { self.history = None; diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 958d890b0..6dcb25660 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -2292,9 +2292,8 @@ fn the_picks_go_with_the_next_message_once() { assert_eq!(script.calls().pop().as_deref(), Some("prompt: and now?")); } -/// Two clicks on two rims are two things, not four edges (a click on a rim selects both halves for -/// the commands; the chat counts and describes what was clicked). The cylinder is a circle drawn -/// as two half arcs, extruded, so each rim is in two halves. +/// Two clicks on two rims are two things (the chat counts and describes what was clicked). The +/// cylinder is a circle drawn as two half arcs, extruded: one wall, each rim one closed edge. #[test] fn a_rim_clicked_once_is_one_item_not_its_pieces() { use solidcraft_engine::Sel; @@ -2314,21 +2313,22 @@ fn a_rim_clicked_once_is_one_item_not_its_pieces() { }; crate::viewport::select(&mut app, Some(Sel::Edge { body: name.clone(), index: top, point: mid_top }), false, false); crate::viewport::select(&mut app, Some(Sel::Edge { body: name, index: bottom, point: mid_bottom }), true, false); - assert_eq!(app.session.selection.len(), 4, "two clicks selected four halves"); + assert_eq!(app.session.selection.len(), 2, "two clicks selected the two rims"); assert_eq!(selected_count(&mut app), 2, "the checkbox counts the two clicks"); app.agent_chat.attach_selection = true; send(&mut app, &ctx, "these two rims".into()); let prompt = script.calls().pop().expect("a prompt"); assert!(prompt.contains("2 item(s)"), "{prompt}"); - assert_eq!(prompt.matches("(2 pieces)").count(), 2, "{prompt}"); - // A rim of radius 10 is about 62.8 mm round (the kernel's own figure), both halves together. - assert!(prompt.contains("Edge 62.") && prompt.contains("mm (2 pieces)"), "{prompt}"); + assert!(!prompt.contains("pieces)"), "{prompt}"); + // A rim of radius 10 is about 62.8 mm round (the kernel's own figure), the whole circle. + assert_eq!(prompt.matches("Edge 62.").count(), 2, "{prompt}"); let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") }; assert_eq!(context.items.len(), 2); assert_eq!(context.total(), 2); - // The detail still names the piece indices the tools take. - assert!(context.items.iter().all(|i| i.detail.contains("indices [")), "{:?}", context.items); + // The detail names the index the tools take. + let indices = [top, bottom].map(|i| format!("index {i}, ")); + assert!(context.items.iter().zip(&indices).all(|(item, index)| item.detail.contains(index)), "{:?}", context.items); } /// The same for a surface the kernel splits at a seam: one click on the cylinder's wall is one item. diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a59485328..cf53ea7ef 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -8304,10 +8304,10 @@ mod tests { app } - /// A Ø20 × 20 cylinder whose wall and rims are each in two halves: a circle drawn as two - /// half arcs, extruded (one wall face per arc). SMLib's own cylinder has one wall and one - /// edge per rim; a rim or wall in pieces comes from a profile like this one or an import. - fn split_cylinder_app() -> SolveApp { + /// A Ø20 × 20 cylinder from a circle drawn as two half arcs, extruded: the arcs on one + /// circle sweep one full-turn wall with its seam edge, and each rim is one closed edge, as + /// SMLib's own cylinder has (a rim or wall in pieces now comes only from an import). + fn arcs_cylinder_app() -> SolveApp { let mut s = solidcraft_engine::Session::default(); s.execute("sketch.create", &json!({"plane": "XY"})).unwrap(); s.execute("sketch.arc.three_point", &json!({"start": [10, 0], "end": [-10, 0], "through": [0, 10]})).unwrap(); @@ -8679,7 +8679,7 @@ mod tests { #[test] fn circular_items_measure_as_whole_rims_and_surfaces() { - let mut app = split_cylinder_app(); + let mut app = arcs_cylinder_app(); let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); @@ -8698,16 +8698,18 @@ mod tests { assert_eq!(d.items().len(), 1); let faces = m.edge_faces.iter().zip(&m.seams).find(|(_, seam)| **seam).unwrap().0; + assert_eq!(faces.len(), 1, "the seam is inside the one wall"); let wall = Sel::Face { body: b.name.clone(), index: faces[0] as usize, point: Vec3::new(10.0, 0.0, 10.0) }; let wall_pieces = grouped_selection(&app.session, &wall); + assert_eq!(wall_pieces, std::slice::from_ref(&wall)); let result = app.session.measure_items(&wall_pieces); assert_eq!(result["items"].as_array().unwrap().len(), 1); assert!((result["items"][0]["area_mm2"].as_f64().unwrap() - 400.0 * std::f64::consts::PI).abs() < 10.0, "{result}"); let mut d = crate::dialogs::Dialog::for_command(&app, "inspect.measure").unwrap(); d.pick(&app.session, wall.clone()); assert_eq!(d.items().len(), 2, "a rim and a wall are two measurement targets"); - d.pick(&app.session, Sel::Face { body: b.name.clone(), index: faces[1] as usize, point: Vec3::new(-10.0, 0.0, 10.0) }); - assert_eq!(d.items().len(), 1, "the other half toggles the same wall"); + d.pick(&app.session, Sel::Face { body: b.name.clone(), index: faces[0] as usize, point: Vec3::new(-10.0, 0.0, 10.0) }); + assert_eq!(d.items().len(), 1, "a pick across the seam toggles the same wall"); } #[test] @@ -8759,87 +8761,100 @@ mod tests { } #[test] - fn circular_rim_hover_click_and_dialog_pick_include_both_halves() { - let mut app = split_cylinder_app(); + fn circular_rim_hover_click_and_dialog_pick_take_the_whole_rim() { + let mut app = arcs_cylinder_app(); let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); let top = m.edges.iter().position(|e| e.len() > 3 && e.iter().all(|p| (p.z - 20.0).abs() < 1e-6)).unwrap(); - let rim = m.circular_rim(top); - assert_eq!(rim.len(), 2); - let line_count: usize = rim.iter().map(|&i| m.edges[i].len() - 1).sum(); - for &i in &rim { - let mid = polyline_mid(&m.edges[i]); - app.viewport.hover = Some(Hit::Edge { body: b.name.clone(), index: i, mid }); - assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); - let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); - select(&mut app, Some(item.clone()), false, false); - assert_eq!(app.session.selection.len(), 2); - // Selecting both pieces must not draw each highlight twice. - assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); - // Ctrl/Shift clicking either half deselects the entire rim. - select(&mut app, Some(item.clone()), true, true); - assert!(app.session.selection.is_empty()); - let mut d = crate::dialogs::Dialog::for_command(&app, "solid.chamfer").unwrap(); - if let crate::dialogs::Kind::Fillet { chain, .. } = &mut d.kind { - *chain = false; - } - d.pick(&app.session, item.clone()); - assert_eq!(d.items().len(), 2); - d.pick(&app.session, item); - assert!(d.items().is_empty()); + // The rim is one closed edge round the whole circle. + assert_eq!(m.circular_rim(top), vec![top]); + let rim = &m.edges[top]; + assert!(rim.first().zip(rim.last()).is_some_and(|(a, b)| a.dist(*b) < 1e-9)); + assert!(rim.iter().all(|p| (p.x.hypot(p.y) - 10.0).abs() < 1e-6)); + let line_count = rim.len() - 1; + let mid = polyline_mid(rim); + app.viewport.hover = Some(Hit::Edge { body: b.name.clone(), index: top, mid }); + assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); + let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); + select(&mut app, Some(item.clone()), false, false); + assert_eq!(app.session.selection, std::slice::from_ref(&item)); + assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); + // Ctrl/Shift clicking the rim deselects it. + select(&mut app, Some(item.clone()), true, true); + assert!(app.session.selection.is_empty()); + let mut d = crate::dialogs::Dialog::for_command(&app, "solid.chamfer").unwrap(); + if let crate::dialogs::Kind::Fillet { chain, .. } = &mut d.kind { + *chain = false; } + d.pick(&app.session, item.clone()); + assert_eq!(d.items().len(), 1); + d.pick(&app.session, item); + assert!(d.items().is_empty()); // Screen-space picking works from either side of the rim as the model turns. - for &i in &rim { - let mid = polyline_mid(&m.edges[i]); - app.cam = app.cam.looking_from(Vec3::new(mid.x, mid.y, 20.0)); + for at in [rim[rim.len() / 4], rim[3 * rim.len() / 4]] { + app.cam = app.cam.looking_from(Vec3::new(at.x, at.y, 20.0)); app.cam.target = Vec3::new(0.0, 0.0, 10.0); for perspective in [false, true] { app.ui.perspective = perspective; let proj = projection(&app, Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))); - let hits = pick(&app, &proj, proj.to_screen(mid).unwrap()); + let hits = pick(&app, &proj, proj.to_screen(at).unwrap()); let (_, sel) = candidate(&app, &hits).unwrap(); - assert!(matches!(sel, Sel::Edge { .. }), "{hits:?}"); - assert_eq!(grouped_selection(&app.session, &sel).len(), 2); + assert!(matches!(sel, Sel::Edge { index, .. } if index == top), "{hits:?}"); + assert_eq!(grouped_selection(&app.session, &sel).len(), 1); } } } #[test] fn curved_face_hover_selection_and_dialogs_cross_the_seam() { - let mut app = split_cylinder_app(); + let mut app = arcs_cylinder_app(); let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); - let faces = m.edge_faces.iter().zip(&m.seams).find(|(_, seam)| **seam).unwrap().0; - assert_eq!(faces.len(), 2); - let triangle_count = m.tri_face.iter().filter(|f| faces.contains(f)).count(); - for &f in faces { - let index = f as usize; - let t = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf == f).unwrap().0; - let [a, c, d] = m.tri(t).unwrap(); - let point = (a + c + d) / 3.0; + let seam = m.seams.iter().position(|seam| *seam).unwrap(); + let faces = &m.edge_faces[seam]; + assert_eq!(faces.len(), 1, "the seam is inside the one wall"); + let wall = faces[0]; + let index = wall as usize; + assert_eq!(m.surface_patch(index), vec![index]); + let triangle_count = m.tri_face.iter().filter(|f| **f == wall).count(); + // The wall's triangles nearest the seam on either side of it, by their centres' turn + // from the seam round the axis. + let at = m.edges[seam][0]; + let turn = |p: Vec3| (at.x * p.y - at.y * p.x).atan2(at.x * p.x + at.y * p.y); + let centres: Vec = m + .triangles + .iter() + .zip(&m.tri_face) + .filter(|(_, f)| **f == wall) + .filter_map(|(t, _)| m.tri(t).map(|[a, c, d]| (a + c + d) / 3.0)) + .collect(); + let side = + |sign: f64| centres.iter().copied().filter(|p| turn(*p) * sign > 0.0).min_by(|p, q| turn(*p).abs().total_cmp(&turn(*q).abs())).unwrap(); + let sides = [side(1.0), side(-1.0)]; + assert!(sides.iter().all(|p| turn(*p).abs() < 0.5), "{sides:?}"); + for (k, &point) in sides.iter().enumerate() { app.viewport.hover = Some(Hit::Face { body: b.name.clone(), index, point }); assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); select(&mut app, Some(item.clone()), false, false); - assert_eq!(app.session.selection.len(), 2); + assert_eq!(app.session.selection, std::slice::from_ref(&item), "keep the original tool placement point"); assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); - assert_eq!(app.session.selection.first(), Some(&item), "keep the original tool placement point first"); let mut dialog = crate::dialogs::Dialog::for_command(&app, "solid.chamfer").unwrap(); - assert_eq!(dialog.items().len(), 2); + assert_eq!(dialog.items().len(), 1); dialog.pick(&app.session, item.clone()); assert!(dialog.items().is_empty()); dialog.pick(&app.session, item); - assert_eq!(dialog.items().len(), 2); - // A point elsewhere on the opposite half still toggles the whole surface off. - let other = faces.iter().find(|&&x| x != f).unwrap(); - select(&mut app, Some(Sel::Face { body: b.name.clone(), index: *other as usize, point: m.positions[0] }), true, true); + assert_eq!(dialog.items().len(), 1); + // A point on the other side of the seam still toggles the whole surface off. + select(&mut app, Some(Sel::Face { body: b.name.clone(), index, point: sides[1 - k] }), true, true); assert!(app.session.selection.is_empty()); } - // Planar caps and box corners stay separate. - let cap = (0..b.body.face_count()).find(|&i| m.surface_patch(i).len() == 1).unwrap(); - assert_eq!(m.surface_patch(cap), vec![cap]); + // Every face is its own patch: the planar caps, the wall, a box's faces. + for i in 0..b.body.face_count() { + assert_eq!(m.surface_patch(i), vec![i]); + } app.session.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); let st = app.session.world_state().unwrap(); let box_body = st.bodies.last().unwrap();