diff --git a/assets/locales/pending/surface-extrude-symmetric-total.json b/assets/locales/pending/surface-extrude-symmetric-total.json new file mode 100644 index 000000000..4d6c40391 --- /dev/null +++ b/assets/locales/pending/surface-extrude-symmetric-total.json @@ -0,0 +1,30 @@ +{ + "en": { + "prefs.surface_extrude_symmetric_per_side": "Symmetric surface extrudes go the distance each way (10 mm: 20 mm in all), as before, not the total like solid extrudes", + "prefs.surfaces": "Surfaces" + }, + "ar": { + "prefs.surface_extrude_symmetric_per_side": "يمتد بثق السطح المتماثل بالمسافة في كل جانب كما كان من قبل (10 مم: 20 مم إجمالًا)، لا بالمسافة الكلية كبثق المجسم", + "prefs.surfaces": "الأسطح" + }, + "he": { + "prefs.surface_extrude_symmetric_per_side": "שליפת משטח סימטרית נשלפת את המרחק לכל צד כמו קודם (10 מ\"מ: 20 מ\"מ בסך הכול), ולא את המרחק הכולל כמו שליפת גוף", + "prefs.surfaces": "משטחים" + }, + "ja": { + "prefs.surface_extrude_symmetric_per_side": "対称のサーフェス押し出しを、ソリッドの押し出しのような合計ではなく、以前のように両側にそれぞれその距離だけ押し出す(10 mm: 合計 20 mm)", + "prefs.surfaces": "サーフェス" + }, + "zh": { + "prefs.surface_extrude_symmetric_per_side": "对称曲面拉伸像以前一样向两侧各拉伸该距离(10 mm:共 20 mm),而非像实体拉伸那样取总距离", + "prefs.surfaces": "曲面" + }, + "de": { + "prefs.surface_extrude_symmetric_per_side": "Symmetrische Flächen-Extrusionen wie bisher um den Abstand nach jeder Seite (10 mm: insgesamt 20 mm), nicht um die Gesamtlänge wie Volumen-Extrusionen", + "prefs.surfaces": "Flächen" + }, + "ko": { + "prefs.surface_extrude_symmetric_per_side": "대칭 서피스 돌출을 솔리드 돌출처럼 전체 거리가 아니라 이전처럼 양쪽으로 각각 그 거리만큼 돌출 (10 mm: 총 20 mm)", + "prefs.surfaces": "서피스" + } +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 0ea238841..289dab12a 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -5118,6 +5118,15 @@ fn path_points(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result { + let x = (arc.start - arc.center).normalized().ok_or_else(|| DocError::Invalid("a 3D arc of no radius".into()))?; + let y = arc.normal.cross(x); + let frame = solidcraft_geom::brep::Frame { origin: arc.center.into(), x_axis: x.into(), y_axis: y.into() }; + let circle = solidcraft_geom::brep::Curve::Circle { frame, radius: arc.radius }; + kernel::PathPiece::Segs(kernel::curve_path(&circle, [0.0, solidcraft_sketch::arc_sweep(arc)])?) + } Some(w) if w.fit.len() >= 3 => kernel::PathPiece::Spline { fit: w.fit.clone(), reversed: false }, Some(w) if !w.exact.is_empty() => { let mut segs = Vec::new(); diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index 37a5dff11..a50ff5622 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -366,8 +366,9 @@ fn edge_curves(body: Option<&crate::ModelBody>, e: usize) -> Vec { } /// The sketch segments `segs` of `ss` projected along the sketch normal `normal` (turned toward -/// the face) onto the face of `target` at `at`: SMLib's projection, the pieces that meet end to -/// end joined into one wire each, every wire its points (for display) and its exact curves. +/// the face) onto the face of `target` at `at`: SMLib's projection, the side of the face the +/// projection meets first ([`first_hits`]), the pieces that meet end to end joined into one wire +/// each, every wire its points (for display) and its exact curves. fn projected_wires( target: &crate::ModelBody, at: Vec3, @@ -378,30 +379,119 @@ fn projected_wires( ) -> Result<(Vec>, Vec>)> { let from = segs.first().map(|s| ss.plane.to_world(s.start())).unwrap_or(at); let toward = if (at - from).dot(normal) < 0.0 { normal * -1.0 } else { normal }; - joined_wires(crate::kernel::project_onto_face(&target.body, at, &ss.plane, segs, toward)?, size * 1e-6) + let curves = crate::kernel::project_onto_face(&target.body, at, &ss.plane, segs, toward)?; + joined_wires(first_hits(target, curves, toward)?, size * 1e-6) } -/// Record curves as wires: curves that meet end to end (within `tol`) one wire, each wire its -/// points (for display) and its exact curves. +/// Of the curves a parallel projection along `toward` made on a face of `target`, the ones the +/// projection meets first: SMLib gives every curve where the projecting lines cross the face +/// (both sides of a sphere), and a projection onto a surface is where they first hit it. A curve +/// is kept when the first hit along the line through its middle, on the body's mesh, is the +/// curve itself (within the mesh's chord tolerance, a few times over), not a point of the body +/// in front of it. +fn first_hits( + target: &crate::ModelBody, + curves: Vec<(solidcraft_geom::brep::Curve, [f64; 2])>, + toward: Vec3, +) -> Result> { + let Some(dir) = toward.normalized() else { return Ok(curves) }; + let mesh = target.mesh(); + let reach = 2.0 * mesh.bounds().diagonal().max(1e-9); + let slack = 4.0 * target.display_tol(); + let mut kept = Vec::with_capacity(curves.len()); + for (curve, interval) in curves { + let eval = solidcraft_geom::brep::eval::CurveEval::new(&curve).map_err(|e| DocError::Invalid(format!("projected curve: {e}")))?; + let mid = eval.point(0.5 * (interval[0] + interval[1])).ok_or_else(|| DocError::Invalid("projected curve: no middle point".into()))?; + let origin = mid - dir * reach; + let front = mesh.raycast(origin, dir).is_some_and(|(t, _)| t < reach - slack); + if !front { + kept.push((curve, interval)); + } + } + Ok(kept) +} + +/// Record curves as wires: curves that meet end to end (within `tol`) one wire, in any order and +/// direction they come (a projection split at a sphere's pole into two pieces that both end there +/// joins again there, the second run the other way), each wire its points (for display) and its +/// exact curves. fn joined_wires(curves: Vec<(solidcraft_geom::brep::Curve, [f64; 2])>, tol: f64) -> Result<(Vec>, Vec>)> { let (mut wires, mut exact): (Vec>, Vec>) = (Vec::new(), Vec::new()); for (curve, interval) in curves { let pts = crate::kernel::PathPiece::Segs(crate::kernel::curve_path(&curve, interval)?).points(); - let Some(start) = pts.first().copied() else { continue }; - match (wires.last_mut(), exact.last_mut()) { - (Some(w), Some(e)) if w.last().is_some_and(|end| end.dist(start) <= tol) => { - w.extend(pts.into_iter().skip(1)); - e.push(WireCurve { curve, interval }); - } - _ => { - wires.push(pts); - exact.push(vec![WireCurve { curve, interval }]); + if pts.is_empty() { + continue; + } + wires.push(pts); + exact.push(vec![WireCurve { curve, interval }]); + } + // Join a wire onto the one that ends where it starts (or ends, turned round), until no two + // meet: each join removes a wire. + 'join: loop { + for i in 0..wires.len() { + for j in 0..wires.len() { + let (Some(a), Some(b)) = (wires.get(i), wires.get(j)) else { continue }; + let (Some(end), Some(start), Some(last)) = (a.last(), b.first(), b.last()) else { continue }; + let turned = if i == j { + continue; + } else if end.dist(*start) <= tol { + false + } else if end.dist(*last) <= tol && exact.get(j).is_some_and(|e| e.iter().all(|c| reversed(c).is_some())) { + true + } else { + continue; + }; + let (mut w, mut e) = (wires.remove(j), exact.remove(j)); + if turned { + w.reverse(); + e = e.iter().rev().filter_map(reversed).collect(); + } + let i = if j < i { i - 1 } else { i }; + if let (Some(into), Some(curves)) = (wires.get_mut(i), exact.get_mut(i)) { + into.extend(w.into_iter().skip(1)); + curves.extend(e); + } + continue 'join; } } + break; } Ok((wires, exact)) } +/// `c` run the other way: the same points, its parameter `t` now `c0 + c1 - t` over the curve's +/// own knots (a line's `1 - t`, a circle's or ellipse's angle negated with its y axis turned). +/// Exact; `None` for a curve kind it doesn't turn. +fn reversed(c: &WireCurve) -> Option { + use solidcraft_geom::brep::{Curve, Frame}; + let [t0, t1] = c.interval; + let flip = |frame: &Frame| Frame { origin: frame.origin, x_axis: frame.x_axis, y_axis: frame.y_axis.map(|v| -v) }; + let (curve, interval) = match &c.curve { + Curve::Line { start, end } => (Curve::Line { start: *end, end: *start }, [1.0 - t1, 1.0 - t0]), + Curve::Circle { frame, radius } => (Curve::Circle { frame: flip(frame), radius: *radius }, [-t1, -t0]), + Curve::Ellipse { frame, radii } => (Curve::Ellipse { frame: flip(frame), radii: *radii }, [-t1, -t0]), + Curve::Spline { knots, points } => { + let sum = knots.first()? + knots.last()?; + ( + Curve::Spline { knots: knots.iter().rev().map(|k| sum - k).collect(), points: points.iter().rev().copied().collect() }, + [sum - t1, sum - t0], + ) + } + Curve::RationalSpline { knots, homogeneous } => { + let sum = knots.first()? + knots.last()?; + ( + Curve::RationalSpline { + knots: knots.iter().rev().map(|k| sum - k).collect(), + homogeneous: homogeneous.iter().rev().copied().collect(), + }, + [sum - t1, sum - t0], + ) + } + _ => return None, + }; + Some(WireCurve { curve, interval }) +} + /// Curve `ci` of the solved sketch `ss` as its exact pieces in space, in the order its polyline /// runs; none where a piece has no record curve. fn sketch_curves(ss: &crate::eval::SolvedSketch, ci: usize) -> Vec { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d4a81c856..31655f997 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1047,12 +1047,16 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { resolve_feature_names(&mut v, &s.doc, cmd)?; let mut nf: Feature = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("invalid feature: {e}")))?; nf.id = f.id; - if let (FeatureKind::Extrude { extent: old, .. }, FeatureKind::Extrude { extent: new, .. }) = (&f.kind, &mut nf.kind) + // A one-sided extrude made symmetric takes the convention a new one would: its old marker + // never read a symmetric distance. + let maker = if matches!(f.kind, FeatureKind::SurfaceExtrude { .. }) { "surface.extrude" } else { "solid.extrude" }; + if let (FeatureKind::Extrude { extent: old, .. }, FeatureKind::Extrude { extent: new, .. }) + | (FeatureKind::SurfaceExtrude { extent: old, .. }, FeatureKind::SurfaceExtrude { extent: new, .. }) = (&f.kind, &mut nf.kind) && old.direction != solidcraft_doc::Direction::Symmetric && new.direction == solidcraft_doc::Direction::Symmetric && set.get("extent").and_then(|e| e.get("convention")).is_none() { - new.convention = solidcraft_doc::ExtrudeConvention::TotalDistance; + new.convention = super::features::default_extrude_convention(s, maker); } if std::mem::discriminant(&nf.kind) != std::mem::discriminant(&f.kind) { return Err(bad(cmd, "the feature type cannot change")); @@ -1410,10 +1414,10 @@ fn redefine(s: &mut Session, p: &Value) -> Result { && matches!(cid, "solid.extrude" | "surface.extrude") && let Some(parameters) = params.as_object_mut() { - let convention = if cid == "surface.extrude" || extent.direction == solidcraft_doc::Direction::Symmetric { + let convention = if extent.direction == solidcraft_doc::Direction::Symmetric { extent.convention } else { - solidcraft_doc::ExtrudeConvention::TotalDistance + super::features::default_extrude_convention(s, cid) }; parameters.entry("convention").or_insert_with(|| json!(convention)); } diff --git a/crates/engine/src/cmd/extrude_convention_tests.rs b/crates/engine/src/cmd/extrude_convention_tests.rs index 09d2a223e..8dd40a9ea 100644 --- a/crates/engine/src/cmd/extrude_convention_tests.rs +++ b/crates/engine/src/cmd/extrude_convention_tests.rs @@ -123,23 +123,102 @@ fn symmetric_extrude_thin_wall_uses_total_distance_and_to_object_remains_one_sid check(&fixture(json!({"to":[0,0,10]})), 0.0, 10.0); } +/// The z range of surface body `name`. +fn sheet_z(s: &Session, name: &str) -> (f64, f64) { + assert!(s.model.results.iter().all(|r| r.error.is_none())); + let st = s.model.state(); + let bounds = st.body(name).unwrap().mesh().bounds(); + (bounds.min.z, bounds.max.z) +} + +fn assert_z(s: &Session, name: &str, lo: f64, hi: f64) { + let (z0, z1) = sheet_z(s, name); + assert!((z0 - lo).abs() < 1e-7 && (z1 - hi).abs() < 1e-7, "{name}: {z0}..{z1}, want {lo}..{hi}"); +} + +/// A symmetric surface extrude reads its distance as a solid one does: the total, split evenly +/// around the start plane, through a redefine and a save. #[test] -fn surface_extrude_shared_extent_retains_its_existing_per_side_semantics() { +fn surface_extrude_symmetric_distance_is_the_total_like_solid_extrude() { let mut s = fixture(json!({})); run(&mut s, "surface.extrude", json!({"sketch":"Square","distance":"10 mm","direction":"symmetric","name":"Sheet","body_name":"Sheet"})); - let check_sheet = |s: &Session| { - let st = s.model.state(); - let bounds = st.body("Sheet").unwrap().mesh().bounds(); - assert!((bounds.min.z + 10.0).abs() < 1e-7 && (bounds.max.z - 10.0).abs() < 1e-7); - }; - check_sheet(&s); + assert_z(&s, "Sheet", -5.0, 5.0); + let FeatureKind::SurfaceExtrude { extent, .. } = &s.doc.find_feature("Sheet").unwrap().kind else { panic!("surface extrude") }; + assert_eq!(extent.convention, ExtrudeConvention::TotalDistance); run( &mut s, "timeline.redefine", json!({"feature":"Sheet","command":"surface.extrude","params":{"sketch":"Square","distance":"10 mm","direction":"symmetric","body_name":"Sheet"}}), ); - check_sheet(&s); - check_sheet(&Session::new(Document::from_json(&s.doc.to_json()).unwrap())); + assert_z(&s, "Sheet", -5.0, 5.0); + assert_z(&Session::new(Document::from_json(&s.doc.to_json()).unwrap()), "Sheet", -5.0, 5.0); + // A one-sided surface extrude made symmetric splits its distance too, as a solid one does. + run(&mut s, "surface.extrude", json!({"sketch":"Square","distance":"10 mm","convention":"legacy_per_side","name":"Wall","body_name":"Wall"})); + assert_z(&s, "Wall", 0.0, 10.0); + run(&mut s, "timeline.edit", json!({"feature":"Wall","set":{"extent":{"direction":"symmetric"}}})); + assert_z(&s, "Wall", -5.0, 5.0); +} + +/// Surface extrudes saved before they matched solid ones stored `legacy_per_side` (or, older +/// still, no marker): they rebuild the distance on each side, and keep it through edits. +#[test] +fn older_symmetric_surface_extrudes_keep_the_distance_on_each_side() { + let mut s = fixture(json!({})); + run( + &mut s, + "surface.extrude", + json!({"sketch":"Square","distance":"10 mm","direction":"symmetric","convention":"legacy_per_side","name":"Sheet","body_name":"Sheet"}), + ); + assert_z(&s, "Sheet", -10.0, 10.0); + let marked: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + let mut unmarked = marked.clone(); + unmarked["format"] = json!("solidcraft/21"); + unmarked.as_object_mut().unwrap().remove("format_pending"); + for f in unmarked["features"].as_array_mut().unwrap() { + if let Some(extent) = f.get_mut("extent").and_then(Value::as_object_mut) { + extent.remove("convention"); + } + } + for saved in [marked, unmarked] { + let mut s = Session::new(Document::from_json(&saved.to_string()).unwrap()); + assert_z(&s, "Sheet", -10.0, 10.0); + run(&mut s, "timeline.edit", json!({"feature":"Sheet","set":{"extent":{"distance":"12 mm"}}})); + assert_z(&s, "Sheet", -12.0, 12.0); + run( + &mut s, + "timeline.redefine", + json!({"feature":"Sheet","command":"surface.extrude","params":{"sketch":"Square","distance":"10 mm","direction":"symmetric","body_name":"Sheet"}}), + ); + assert_z(&s, "Sheet", -10.0, 10.0); + } +} + +/// The preference brings back the per-side reading for new surface extrudes only: solid +/// extrudes and an explicit `convention` are unchanged by it. +#[test] +fn the_per_side_preference_keeps_the_older_surface_extrude_reading() { + let mut s = fixture(json!({})); + s.surface_extrude_symmetric_per_side = true; + run(&mut s, "surface.extrude", json!({"sketch":"Square","distance":"10 mm","direction":"symmetric","name":"Sheet","body_name":"Sheet"})); + assert_z(&s, "Sheet", -10.0, 10.0); + let FeatureKind::SurfaceExtrude { extent, .. } = &s.doc.find_feature("Sheet").unwrap().kind else { panic!("surface extrude") }; + assert_eq!(extent.convention, ExtrudeConvention::LegacyPerSide); + run( + &mut s, + "surface.extrude", + json!({"sketch":"Square","distance":"10 mm","direction":"symmetric","convention":"total_distance","name":"Total","body_name":"Total"}), + ); + assert_z(&s, "Total", -5.0, 5.0); + run(&mut s, "solid.extrude", json!({"sketch":"Square","distance":"10 mm","direction":"symmetric","operation":"new","body_name":"Solid"})); + assert_z(&s, "Solid", -5.0, 5.0); + // The saved marker, not the preference, decides on reopening. + s.surface_extrude_symmetric_per_side = false; + let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); + assert_z(&reopened, "Sheet", -10.0, 10.0); + // A design opened or started keeps the user's choice. + s.surface_extrude_symmetric_per_side = true; + s.replace_design(Session::default()); + assert!(s.surface_extrude_symmetric_per_side); } /// A second distance goes the other way from the first side (#2700): along the normal when the diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 816143638..398cc0455 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -25,7 +25,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .key("E") .contract(&EXTRUDE_CONTRACT) .output(output_schema_for::) - .params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"), + .params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (how a symmetric distance is read; default total_distance, split evenly around the start plane; legacy_per_side: the distance on each side, as older symmetric extrudes keep); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"), CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") .icon("revolve") @@ -1120,6 +1120,18 @@ fn thin_regions(s: &Session, ss: &solidcraft_doc::SolvedSketch, thin: &ThinWall) solidcraft_sketch::thin_wall_regions(&curves, inside, outside).map_err(|e| format!("thin wall: {e}")) } +/// How a new extent of `cmd` (`solid.extrude` or `surface.extrude`) reads a symmetric distance +/// when the call doesn't say: the total, split evenly around the start plane, for both. A surface +/// extrude reads it on each side, as surface extrudes did before, while the user's preference +/// says so ([`Session::surface_extrude_symmetric_per_side`]). +pub(crate) fn default_extrude_convention(s: &Session, cmd: &str) -> solidcraft_doc::ExtrudeConvention { + if cmd == "surface.extrude" && s.surface_extrude_symmetric_per_side { + solidcraft_doc::ExtrudeConvention::LegacyPerSide + } else { + solidcraft_doc::ExtrudeConvention::TotalDistance + } +} + /// An extrude's extent from its parameters: distance (or through all, or to an object), the /// side(s), a second distance, a start offset, a taper, and from an object. pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result { @@ -1156,9 +1168,7 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result check_expr(s, d, Kind::Length, cmd, "start_offset")?; } let convention = match p.get("convention") { - // Surface Extrude shares Extent but retains its existing per-side distance semantics. - None if cmd == "surface.extrude" => solidcraft_doc::ExtrudeConvention::LegacyPerSide, - None => solidcraft_doc::ExtrudeConvention::TotalDistance, + None => default_extrude_convention(s, cmd), Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`convention` must be total_distance or legacy_per_side"))?, }; Ok(Extent { diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index 7a49f87c1..6c32703a2 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -379,14 +379,28 @@ fn three_d_sketch_curves() { let src = s.doc.features.last().unwrap().id; run(&mut s, "sketch.create", json!({"plane": "XY"})); let r = run(&mut s, "sketch.project_to_surface", json!({"curves": [{"sketch": src, "curve": l}], "face": [0, 0, 20]})); + // The line's projection where it first meets the sphere: the arc of the great circle in y = 0 + // from x = -10 to 10 over the top (z = √(400 − x²)), one wire though SMLib splits it at the + // pole, and no curve on the far side. + assert_eq!(r["links"][0]["wires"].as_array().unwrap().len(), 1, "{r}"); let wid = r["links"][0]["wires"][0].as_str().unwrap().to_string(); let st = s.model.state(); let sk = &st.sketch(s.active_sketch.unwrap()).unwrap().sketch; let w = &sk.wires[sk.wire_index(&wid).unwrap()]; - assert!(w.pts.len() > 20); - for p in &w.pts { - assert!((p.len() - 20.0).abs() < 0.1, "{p:?}"); - assert!(p.z > 0.0); + assert!(!w.exact.is_empty()); + // SMLib makes projected curves to a millionth of the body's size (the sphere's 40 mm box). + let tol = 40.0 * 1e-6; + let ends = [*w.pts.first().unwrap(), *w.pts.last().unwrap()]; + let top = 300f64.sqrt(); + assert!(ends.iter().all(|e| (e.x.abs() - 10.0).abs() < tol && e.y.abs() < tol && (e.z - top).abs() < tol), "{ends:?}"); + assert!((ends[0].x + ends[1].x).abs() < tol, "{ends:?}"); + // Along its exact curves (the wire's points are its spans' polygon), on the sphere's top. + for c in &w.exact { + let eval = solidcraft_geom::brep::eval::CurveEval::new(&c.curve).unwrap(); + for k in 0..=32 { + let p = eval.point(c.interval[0] + (c.interval[1] - c.interval[0]) * f64::from(k) / 32.0).unwrap(); + assert!((p.len() - 20.0).abs() < tol && p.y.abs() < tol && p.z >= top - tol, "{p:?}"); + } } // Delete the wire. run(&mut s, "sketch.delete", json!({"entities": [wid]})); diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index dc1d320e0..d9b617042 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -39,7 +39,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.extrude", "Surface Extrude", surface_extrude) .at("SURFACE", "CREATE") .icon("surface_extrude") - .params("sketch?: id|name; curves?: [curve ids] (open or closed chains of curves meeting end to end) and/or profiles? (their boundaries; the default when no curves are given); distance: expr; direction?: positive|negative|symmetric; distance2?: expr; start_offset?: expr; name?, body_name? (a surface body: walls only, no caps)"), + .params("sketch?: id|name; curves?: [curve ids] (open or closed chains of curves meeting end to end) and/or profiles? (their boundaries; the default when no curves are given); distance: expr; direction?: positive|negative|symmetric (symmetric: distance is the total, split evenly around the start plane, as solid.extrude); convention?: total_distance|legacy_per_side (as solid.extrude; default total_distance, or legacy_per_side, the distance on each side, under the user's preference for the older reading); distance2?: expr; start_offset?: expr; name?, body_name? (a surface body: walls only, no caps)"), CommandSpec::new("surface.revolve", "Surface Revolve", surface_revolve) .at("SURFACE", "CREATE") .icon("surface_revolve") @@ -797,7 +797,8 @@ mod tests { // The line's wall and the half circle's (radius 5): length × height. let want = (10.0 + std::f64::consts::PI * 5.0) * 4.0; assert!((area(&s, "Wall") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Wall")); - run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": ["l1"], "distance": 2, "direction": "symmetric", "body_name": "Both"})); + // Symmetric: the distance is the total, split evenly around the sketch plane. + run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": ["l1"], "distance": 4, "direction": "symmetric", "body_name": "Both"})); let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Both").unwrap().body).unwrap().bbox; assert!((bb.min.z + 2.0).abs() < 1e-9 && (bb.max.z - 2.0).abs() < 1e-9, "{bb:?}"); run(&mut s, "edit.undo", json!({})); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3a45a9abc..7b93a7426 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -380,6 +380,10 @@ pub struct Session { /// A new metric tapped hole given no `diameter` drills the major diameter less the pitch, /// as before the tap maker's drills (a user preference); false: the tap maker's drill. pub metric_tap_drill_major_less_pitch: bool, + /// A new symmetric surface extrude given no `convention` reads its distance on each side, as + /// surface extrudes did before they matched solid ones (a user preference); false: the total, + /// split evenly around the start plane, as a solid extrude reads it. + pub surface_extrude_symmetric_per_side: bool, /// How calls that break a command's parameter contract are treated (off by default). It /// belongs to the session, not the design, so it survives opening and starting designs. pub param_check: schema::ParamCheck, @@ -600,6 +604,7 @@ impl Session { followed: None, auto_project: true, metric_tap_drill_major_less_pitch: false, + surface_extrude_symmetric_per_side: false, param_check: schema::ParamCheck::Off, easyprint_upload: None, live_links: None, @@ -647,6 +652,7 @@ impl Session { pub fn replace_design(&mut self, fresh: Session) { let auto_project = self.auto_project; let metric_tap_drill_major_less_pitch = self.metric_tap_drill_major_less_pitch; + let surface_extrude_symmetric_per_side = self.surface_extrude_symmetric_per_side; let param_check = self.param_check; let easyprint_upload = self.easyprint_upload.take(); let render_viewport = self.render_viewport.clone(); @@ -663,6 +669,7 @@ impl Session { self.command_check = command_check; self.auto_project = auto_project; self.metric_tap_drill_major_less_pitch = metric_tap_drill_major_less_pitch; + self.surface_extrude_symmetric_per_side = surface_extrude_symmetric_per_side; self.param_check = param_check; self.easyprint_upload = easyprint_upload; self.render_viewport = render_viewport; @@ -1406,6 +1413,7 @@ impl Session { followed: None, auto_project: self.auto_project, metric_tap_drill_major_less_pitch: self.metric_tap_drill_major_less_pitch, + surface_extrude_symmetric_per_side: self.surface_extrude_symmetric_per_side, param_check: self.param_check, easyprint_upload: self.easyprint_upload.clone(), live_links: None, diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index b5678aa22..23066271e 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -937,8 +937,12 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K if let Some(input) = ins.first_mut() { input.items = sels; } + // A symmetric extrude keeps the reading it was made with; a one-sided one made + // symmetric here takes a new one's (timeline.redefine fills it in either way). let mut extra = Map::new(); - extra.insert("convention".into(), json!(extent.convention)); + if extent.direction == Direction::Symmetric { + extra.insert("convention".into(), json!(extent.convention)); + } return Some((Kind::Surface(k), ins, extra)); } FeatureKind::Patch { sketch, edges, crown, continuity, points, .. } => { diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 0c0296aa4..8e859fb55 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -159,6 +159,7 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { // Preferences the session holds go with the user, not the tab (#680). app.session.auto_project = out.session.auto_project; app.session.metric_tap_drill_major_less_pitch = out.session.metric_tap_drill_major_less_pitch; + app.session.surface_extrude_symmetric_per_side = out.session.surface_extrude_symmetric_per_side; // So does the host's pre-command check: every tab is held to it. app.session.set_command_check(out.session.command_check()); // Views cache by revision: the incoming design must not look unchanged. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b6dd8b45c..8b0819186 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -978,8 +978,10 @@ impl SolveApp { if matches!(id, "file.save_mesh" | "file.send_to_slicer") { solidcraft_engine::slicers::set_chosen_programs(&self.preferences.custom_slicers); } - // The preference the hole command reads, current even before the next frame applies it. + // The preferences the hole and surface extrude commands read, current even before the + // next frame applies them. self.session.metric_tap_drill_major_less_pitch = self.preferences.metric_tap_drill_major_less_pitch; + self.session.surface_extrude_symmetric_per_side = self.preferences.surface_extrude_symmetric_per_side; let t0 = now_ms(); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 2ab6b458e..21286834f 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -637,6 +637,10 @@ preference_settings! { /// the tap maker's drills; off by default: the tap maker's drill (M8: 6.8 mm). Saved designs /// keep the drill they stored either way. metric_tap_drill_major_less_pitch: bool = false, PAGE_DESIGN => check_id("prefs.metric_tap_drill_major_less_pitch"); + /// New symmetric surface extrudes go their distance each way, as before they matched solid + /// extrudes; off by default: the distance is the total, split evenly around the start plane. + /// Saved designs keep the reading they stored either way. + surface_extrude_symmetric_per_side: bool = false, PAGE_DESIGN => check_id("prefs.surface_extrude_symmetric_per_side"); /// Reopen the saved designs that were open when the app was last closed (#5542). reopen_designs: bool = true, PAGE_GENERAL; /// Those designs' files, in tab order, as the last quit left them. @@ -1122,8 +1126,10 @@ fn defaults(app: &mut SolveApp, page: usize) { /// the interface scale. pub fn apply(app: &mut SolveApp, ctx: &egui::Context) { apply_network(&app.preferences); - // The hole command reads the metric tapped drill rule from the session. + // The hole command reads the metric tapped drill rule from the session, Surface Extrude its + // symmetric reading. app.session.metric_tap_drill_major_less_pitch = app.preferences.metric_tap_drill_major_less_pitch; + app.session.surface_extrude_symmetric_per_side = app.preferences.surface_extrude_symmetric_per_side; // The profiler records while the preference is on (switched when it changes; at start-up only // when on, so SOLIDCRAFT_PROFILE=1 is not undone by the default). let profile = app.preferences.profile_operations; @@ -2484,6 +2490,34 @@ mod tests { assert!(h.app.session.metric_tap_drill_major_less_pitch); } + /// New symmetric surface extrudes read their distance as the total, as solid extrudes do; the + /// preference brings back the distance on each side they took before. It reaches the command + /// whether set through the control channel or the Preferences page, and survives a new design. + #[test] + fn the_surface_extrude_preference_keeps_the_distance_on_each_side() { + use serde_json::json; + let height = |h: &mut crate::scenario::Harness, name: &str| { + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,10]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("surface.extrude", json!({"distance":"10 mm","direction":"symmetric","body_name":name})).unwrap(); + let st = h.app.session.world_state().unwrap(); + let b = st.body(name).unwrap().mesh().bounds(); + b.max.z - b.min.z + }; + let mut h = crate::scenario::Harness::new(); + h.frames(1); + assert!(!h.app.preferences.surface_extrude_symmetric_per_side, "off by default"); + assert!((height(&mut h, "Total") - 10.0).abs() < 1e-7); + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"surface_extrude_symmetric_per_side": true})); + h.frames(2); + assert!(h.app.session.surface_extrude_symmetric_per_side); + assert!((height(&mut h, "Each") - 20.0).abs() < 1e-7); + h.app.run("file.new", json!({})).unwrap(); + assert!(h.app.session.surface_extrude_symmetric_per_side); + } + #[test] fn the_ghost_position_defaults_round_trips_and_reads_tolerantly() { use super::SpaceMouseGhost::{LeftViewport as Current, LeftWindow as Left, RightViewport as Right}; diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs index 07d8843c4..5b7b902c9 100644 --- a/crates/ui-egui/src/prefs/design.rs +++ b/crates/ui-egui/src/prefs/design.rs @@ -40,6 +40,10 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let check = setting::metric_tap_drill_major_less_pitch(app, ui); crate::scenario::publish_handle("prefs:metric_tap_drill_major_less_pitch", check.rect.center()); }); + ui_kit::settings_section(ui, "surfaces", app.tr("prefs.surfaces"), |ui| { + let check = setting::surface_extrude_symmetric_per_side(app, ui); + crate::scenario::publish_handle("prefs:surface_extrude_symmetric_per_side", check.rect.center()); + }); ui_kit::settings_section(ui, "orientation", app.tr("prefs.orientation"), |ui| { ui.horizontal_wrapped(|ui| { for (id, label, y_up) in [("z", "Z up", false), ("y", "Y up", true)] { diff --git a/tests/kernel-cases/booleans/3830-split-cup-by-extended-spline-surface/recipe.json b/tests/kernel-cases/booleans/3830-split-cup-by-extended-spline-surface/recipe.json index 3049ad63f..0952745c8 100644 --- a/tests/kernel-cases/booleans/3830-split-cup-by-extended-spline-surface/recipe.json +++ b/tests/kernel-cases/booleans/3830-split-cup-by-extended-spline-surface/recipe.json @@ -105,6 +105,7 @@ ], "distance": 30, "direction": "symmetric", + "convention": "legacy_per_side", "body_name": "Body2" } },