Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Sketch: 3D arc command (#5681) (#5682)

Dahak Builds2863b80574af
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 9dcc8f7905..fa88bf404c 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -925,6 +925,7 @@
"cmd.sheet_refold": "Refold",
"cmd.sheet_rules": "List Sheet Metal Rules",
"cmd.sheet_unfold": "Unfold",
+ "cmd.sketch_arc3d": "3D Arc",
"cmd.sketch_arc_center_point": "Center Point Arc",
"cmd.sketch_arc_tangent": "Tangent Arc",
"cmd.sketch_arc_three_point": "3-Point Arc",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 01b08e0d51..df31d90abd 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -925,6 +925,7 @@
"cmd.sheet_refold": "折り戻し",
"cmd.sheet_rules": "板金ルールを一覧表示",
"cmd.sheet_unfold": "展開",
+ "cmd.sketch_arc3d": "3D 円弧",
"cmd.sketch_arc_center_point": "中心点円弧",
"cmd.sketch_arc_tangent": "正接円弧",
"cmd.sketch_arc_three_point": "3点指定円弧",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index 171e19a551..30d0a53576 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -925,6 +925,7 @@
"cmd.sheet_refold": "重新折弯",
"cmd.sheet_rules": "列出钣金规则",
"cmd.sheet_unfold": "展开",
+ "cmd.sketch_arc3d": "三维圆弧",
"cmd.sketch_arc_center_point": "中心点圆弧",
"cmd.sketch_arc_tangent": "相切圆弧",
"cmd.sketch_arc_three_point": "三点圆弧",
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 0643bf6fe8..98b559b683 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -5803,10 +5803,18 @@ fn pipe_region(vals: &BTreeMap<String, Value>, r: f64, wall: &Option<crate::Expr
Ok(Region2 { outer: solidcraft_geom::Loop2::circle(Vec2::ZERO, r), holes })
}
-fn map_wire(wire: &mut solidcraft_sketch::Wire, matrix: &Mat) {
+pub fn map_wire(wire: &mut solidcraft_sketch::Wire, matrix: &Mat) {
for point in wire.pts.iter_mut().chain(&mut wire.fit) {
*point = crate::apply_point(matrix, *point);
}
+ if let Some(arc) = &mut wire.arc {
+ let normal = crate::apply_vector(matrix, arc.normal);
+ arc.center = crate::apply_point(matrix, arc.center);
+ arc.start = crate::apply_point(matrix, arc.start);
+ arc.end = crate::apply_point(matrix, arc.end);
+ arc.normal = normal.normalized().unwrap_or(arc.normal);
+ arc.radius = arc.center.dist(arc.start);
+ }
}
/// A feature's sketch as its component sees it: a sketch of another component that is placed
diff --git a/crates/doc/src/format/pending/sketch-arc3d.rs b/crates/doc/src/format/pending/sketch-arc3d.rs
new file mode 100644
index 0000000000..999e5e4712
--- /dev/null
+++ b/crates/doc/src/format/pending/sketch-arc3d.rs
@@ -0,0 +1,4 @@
+//! Drawn 3D sketch arcs: a wire drawn as an exact circular arc now also saves its analytic
+//! form (`arc`: centre, unit normal, radius, start and end) beside its three defining fit
+//! points and its samples. Older designs contain no such arcs and open unchanged; a design
+//! saved with this change carries the newer format number, which the last release refuses.
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 586e05d6d1..158e0d6e29 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -76,9 +76,10 @@ pub use document::*;
pub use eval::KeptResults;
pub use eval::{
EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error,
- edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height,
- parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane,
- state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance, world_state, world_state_reusing,
+ edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, map_wire, metric_thread_sizes,
+ object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction,
+ sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance, world_state,
+ world_state_reusing,
};
pub use expr::Expr;
pub use names::{BodyName, FeatureName, SketchId};
diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs
index f5c0fb4151..aa1baeab87 100644
--- a/crates/engine/src/cmd/inspect.rs
+++ b/crates/engine/src/cmd/inspect.rs
@@ -236,7 +236,7 @@ fn sketch_json(s: &Session, id: u64) -> Option<Value> {
"constraints": constraints,
"profiles": profiles,
"links": sk.links,
- "wires": sk.wires.iter().map(|w| json!({"id": w.id, "points": w.pts.len(), "start": w.pts.first(), "end": w.pts.last(), "link": w.link})).collect::<Vec<_>>(),
+ "wires": sk.wires.iter().map(|w| json!({"id": w.id, "points": w.pts.len(), "start": w.pts.first(), "end": w.pts.last(), "link": w.link, "arc": w.arc.map(|a| json!({"center": a.center, "radius": a.radius, "start": a.start, "end": a.end, "sweep_deg": solidcraft_sketch::arc_sweep(&a).to_degrees()}))})).collect::<Vec<_>>(),
"visible": crate::view::sketch_shown(s, id),
}))
}
diff --git a/crates/engine/src/cmd/sketch_3d.rs b/crates/engine/src/cmd/sketch_3d.rs
index d6202511f7..7bdfe9df2b 100644
--- a/crates/engine/src/cmd/sketch_3d.rs
+++ b/crates/engine/src/cmd/sketch_3d.rs
@@ -1,6 +1,7 @@
-//! 3D sketch drawing: with the sketch's 3D Sketch option on (Sketch Palette), lines, splines and
-//! points may leave the sketch plane. They are kept as drawn 3D curves (wires with fit points):
-//! drawn and snapped to, movable point by point, and usable as sweep and pipe paths.
+//! 3D sketch drawing: with the sketch's 3D Sketch option on (Sketch Palette), lines, arcs,
+//! splines and points may leave the sketch plane. They are kept as drawn 3D curves (wires with
+//! fit points, exact arcs keeping their analytic form): drawn and snapped to, movable point by
+//! point, and usable as sweep and pipe paths.
use serde_json::{Value, json};
use solidcraft_geom::Vec3;
@@ -20,6 +21,13 @@ pub static COMMANDS: &[CommandSpec] = &[
.icon("spline")
.enabled(in_sketch)
.params(concat!("points: [[x,y,z]…] world fit points (2 or more): a smooth 3D curve through them (needs 3D Sketch on)", created_doc!())),
+ CommandSpec::new("sketch.arc3d", "3D Arc", arc3d)
+ .icon("arc3")
+ .enabled(in_sketch_3d)
+ .params(concat!(
+ "start, through, end: [x,y,z] world points: an exact circular arc through them, from start through through to end (needs 3D Sketch on). Stored exactly (centre, radius, angles), so path consumers can treat it as a true arc",
+ created_doc!()
+ )),
CommandSpec::new("sketch.point3d", "3D Point", point3d)
.icon("point")
.enabled(in_sketch)
@@ -42,6 +50,17 @@ fn needs_3d(sk: &solidcraft_sketch::Sketch, cmd: &str) -> Result<()> {
if sk.view.three_d { Ok(()) } else { Err(bad(cmd, "turn on 3D Sketch (sketch.options sketch_3d: true) to draw off the sketch plane")) }
}
+/// The 3D Arc button starts an interactive tool, so it is only offered while a 3D sketch is
+/// being edited; otherwise the tool could only fail on its third click.
+fn in_sketch_3d(s: &Session) -> std::result::Result<(), String> {
+ let id = s.active_sketch.ok_or("no sketch is being edited (Create Sketch or Edit Sketch first)")?;
+ match s.doc.sketch(id) {
+ Ok(sk) if sk.view.three_d => Ok(()),
+ Ok(_) => Err("turn on 3D Sketch (sketch.options sketch_3d: true) to draw 3D arcs".into()),
+ Err(_) => Err("no sketch is being edited (Create Sketch or Edit Sketch first)".into()),
+ }
+}
+
/// World command inputs belong to the target sketch's owner, which may differ from the
/// active component when a script supplies an explicit sketch.
fn inverse_owner_frame(s: &Session, p: &Value, cmd: &str) -> Result<solidcraft_doc::Mat> {
@@ -100,6 +119,23 @@ fn spline3d(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"curves": [id], "sketch": info}))
}
+fn arc3d(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "sketch.arc3d";
+ let inverse = inverse_owner_frame(s, p, cmd)?;
+ let pts: Vec<Vec3> = ["start", "through", "end"]
+ .iter()
+ .map(|k| req_vec3(cmd, p, k))
+ .collect::<Result<Vec<Vec3>>>()?
+ .into_iter()
+ .map(|at| solidcraft_doc::apply_point(&inverse, at))
+ .collect();
+ let (id, info) = edit(s, p, cmd, false, |sk, _| {
+ needs_3d(sk, cmd)?;
+ Ok(sk.add_drawn_arc_in(&pts, WireSpace::Component)?)
+ })?;
+ Ok(json!({"curves": [id], "sketch": info}))
+}
+
fn point3d(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.point3d";
let inverse = inverse_owner_frame(s, p, cmd)?;
diff --git a/crates/engine/src/cmd/sketch_3d_frame_tests.rs b/crates/engine/src/cmd/sketch_3d_frame_tests.rs
index 311e8ee7a2..34ddee7b19 100644
--- a/crates/engine/src/cmd/sketch_3d_frame_tests.rs
+++ b/crates/engine/src/cmd/sketch_3d_frame_tests.rs
@@ -313,3 +313,107 @@ fn wire_frame_three_owner_sweep_profile_move_invalidates_warm_cache() {
assert_eq!(s.doc.to_json(), saved);
measure(&s, 4.0);
}
+
+#[test]
+fn arc3d_is_exact_inspectable_movable_and_reopens() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane":"XY"}));
+ run(&mut s, "sketch.options", json!({"sketch_3d":true}));
+ let sketch = s.active_sketch.unwrap();
+ let d = 5.0 * std::f64::consts::SQRT_2;
+ let r = run(&mut s, "sketch.arc3d", json!({"start":[10,0,0],"through":[d,d,0],"end":[0,10,0]}));
+ let id = r["curves"][0].as_str().unwrap().to_string();
+ let sk = s.doc.sketch(sketch).unwrap();
+ let w = &sk.wires[sk.wire_index(&id).unwrap()];
+ let arc = w.arc.expect("an exact arc is stored");
+ assert!((arc.radius - 10.0).abs() < 1e-9, "radius {}", arc.radius);
+ assert!(arc.center.dist(Vec3::ZERO) < 1e-9, "centre {:?}", arc.center);
+ assert_eq!(w.fit.len(), 3);
+ assert_eq!(w.pts.first(), w.fit.first());
+ assert_eq!(w.pts.last(), w.fit.get(2));
+ assert!(w.pts.iter().all(|p| (arc.center.dist(*p) - arc.radius).abs() < 1e-6));
+ let _ = sk;
+ let insp = run(&mut s, "sketch.inspect", json!({}));
+ let entry = insp["wires"].as_array().unwrap().iter().find(|e| e["id"] == json!(id)).unwrap();
+ assert!((entry["arc"]["radius"].as_f64().unwrap() - 10.0).abs() < 1e-9);
+ assert!((entry["arc"]["sweep_deg"].as_f64().unwrap() - 90.0).abs() < 1e-6);
+ // Pulling the through point in rebuilds the arc exactly.
+ run(&mut s, "sketch.move3d", json!({"wire":id,"index":1,"to":[0,5,0]}));
+ let sk = s.doc.sketch(sketch).unwrap();
+ let arc = sk.wires[sk.wire_index(&id).unwrap()].arc.unwrap();
+ assert!((arc.radius - 62.5_f64.sqrt()).abs() < 1e-9, "radius {}", arc.radius);
+ let saved = s.doc.to_json();
+ let restored = solidcraft_doc::format::read(&saved).unwrap();
+ assert_eq!(restored.sketch(sketch).unwrap().wires, s.doc.sketch(sketch).unwrap().wires);
+ let idx = s.doc.sketch(sketch).unwrap().wire_index(&id).unwrap();
+ run(&mut s, "edit.undo", json!({}));
+ assert!((s.doc.sketch(sketch).unwrap().wires[idx].arc.unwrap().radius - 10.0).abs() < 1e-9);
+}
+
+#[test]
+fn arc3d_follows_the_sketch_owner_placement() {
+ let (mut s, _, _, second) = second_frame();
+ let sketch = s.active_sketch.unwrap();
+ let d = 5.0 * std::f64::consts::SQRT_2;
+ // World points of a quarter circle whose local centre is (0,0,5), radius 10.
+ let id = run(&mut s, "sketch.arc3d", json!({"start":[20,40,45],"through":[20.0 - d,30.0 + d,45],"end":[10,30,45]}))["curves"][0]
+ .as_str()
+ .unwrap()
+ .to_string();
+ let sk = s.doc.sketch(sketch).unwrap();
+ let arc = sk.wires[sk.wire_index(&id).unwrap()].arc.unwrap();
+ near(arc.center, Vec3::new(0.0, 0.0, 5.0));
+ assert!((arc.radius - 10.0).abs() < 1e-7, "radius {}", arc.radius);
+ let _ = sk;
+ let world = s.world_state();
+ let ws = &world.sketch(sketch).unwrap().sketch;
+ let arc = ws.wires[ws.wire_index(&id).unwrap()].arc.unwrap();
+ near(arc.center, Vec3::new(20.0, 30.0, 45.0));
+ near(ws.wires[ws.wire_index(&id).unwrap()].fit[0], Vec3::new(20.0, 40.0, 45.0));
+ drop(world);
+ run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0]}));
+ let world = s.world_state();
+ let ws = &world.sketch(sketch).unwrap().sketch;
+ let arc = ws.wires[ws.wire_index(&id).unwrap()].arc.unwrap();
+ near(arc.center, Vec3::new(25.0, 30.0, 45.0));
+ assert!((arc.radius - 10.0).abs() < 1e-7, "radius {}", arc.radius);
+}
+
+#[test]
+fn arc3d_hostile_inputs_rollback_full_session() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane":"XY"}));
+ run(&mut s, "sketch.options", json!({"sketch_3d":true}));
+ let doc = s.doc.to_json();
+ let history = (s.undo.len(), s.redo.len());
+ for (cmd, p) in [
+ ("sketch.arc3d", json!({"start":[0,0,0],"through":[1,0,0],"end":[2,0,0]})), // collinear
+ ("sketch.arc3d", json!({"start":[0,0,0],"through":[0,0,0],"end":[0,10,0]})), // coincident
+ ("sketch.arc3d", json!({"start":[0,0,0],"through":[f64::NAN,5,0],"end":[10,0,0]})),
+ ("sketch.arc3d", json!({"start":[0,0,0],"through":[1e100,5,0],"end":[10,0,0]})),
+ ("sketch.arc3d", json!({"start":[0,0,0],"through":[5,5,0]})), // missing end
+ ("sketch.arc3d", json!({"start":[0,0,0],"through":["x",5,0],"end":[10,0,0]})),
+ ("sketch.arc3d", json!({"through":[5,5,0],"end":[10,0,0]})), // missing start
+ ] {
+ assert!(s.execute(cmd, &p).is_err(), "{cmd}: {p}");
+ assert_eq!(s.doc.to_json(), doc);
+ assert_eq!((s.undo.len(), s.redo.len()), history);
+ }
+}
+
+#[test]
+fn arc3d_pipes_along_the_arc() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane":"XY"}));
+ run(&mut s, "sketch.options", json!({"sketch_3d":true}));
+ let sketch = s.active_sketch.unwrap();
+ let d = 10.0 * std::f64::consts::SQRT_2;
+ let wire = run(&mut s, "sketch.arc3d", json!({"start":[20,0,0],"through":[d,d,0],"end":[0,20,0]}))["curves"][0].as_str().unwrap().to_string();
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.pipe", json!({"path_sketch":sketch,"path":[wire],"diameter":4}));
+ let world = s.world_state();
+ let body = world.bodies.last().unwrap();
+ let measure = solidcraft_kernel::measure(&body.body).unwrap();
+ let quarter = 20.0 * std::f64::consts::FRAC_PI_2;
+ assert!((measure.volume - 4.0 * std::f64::consts::PI * quarter).abs() < 0.5, "{}", measure.volume);
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 13d2fa9181..246304821c 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -749,9 +749,7 @@ impl Session {
}
for wire in &mut sketch.sketch.wires {
if wire.space == solidcraft_doc::sketch::WireSpace::Component {
- for point in wire.pts.iter_mut().chain(&mut wire.fit) {
- *point = solidcraft_doc::apply_point(&delta, *point);
- }
+ solidcraft_doc::map_wire(wire, &delta);
}
}
}
diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs
index b0b986c2d6..f30136b10a 100644
--- a/crates/sketch/src/lib.rs
+++ b/crates/sketch/src/lib.rs
@@ -72,7 +72,7 @@ pub use solver::{
};
pub use text::{MAX_TEXT_CHARS, TextAlign, TextMetrics, TextStyle, text_geometry, text_geometry_in, text_geometry_styled};
pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions};
-pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, WireSpace, fit_polyline};
+pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, WireArc, WireSpace, arc_from_3_points, arc_polyline, arc_sweep, fit_polyline};
#[cfg(test)]
mod circle_edge_tests;
diff --git a/crates/sketch/src/wire.rs b/crates/sketch/src/wire.rs
index b0bc5f32e5..15e1883b64 100644
--- a/crates/sketch/src/wire.rs
+++ b/crates/sketch/src/wire.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use solidcraft_geom::Vec3;
use crate::link::{Link, LinkGeom, LinkKind, LinkSource};
-use crate::model::{Result, Sketch, SketchError, in_range3};
+use crate::model::{Result, Sketch, SketchError, in_range3, radius_in_range};
/// Most points one wire may have.
pub const MAX_WIRE_POINTS: usize = 100_000;
@@ -33,6 +33,18 @@ impl WireSpace {
}
}
+/// An exact circular arc drawn in 3D space: centre, unit normal of its plane, radius, and the
+/// arc from `start` to `end` counter-clockwise about `normal` (through the wire's middle fit
+/// point). All coordinates are in the wire's `space`.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct WireArc {
+ pub center: Vec3,
+ pub normal: Vec3,
+ pub radius: f64,
+ pub start: Vec3,
+ pub end: Vec3,
+}
+
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Wire {
pub id: String,
@@ -46,6 +58,10 @@ pub struct Wire {
/// line; more: a smooth spline). `pts` is made from them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fit: Vec<Vec3>,
+ /// Drawn in a 3D sketch as an exact circular arc: the analytic curve, whose `fit` points
+ /// are its three defining points (start, through, end) and whose `pts` are its samples.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub arc: Option<WireArc>,
}
/// Most fit points of a drawn 3D curve.
@@ -95,6 +111,74 @@ pub fn fit_polyline(fit: &[Vec3]) -> Vec<Vec3> {
out
}
+/// Chord-height tolerance (mm) when sampling a drawn 3D arc into `pts`.
+const ARC_TOL: f64 = 1e-3;
+
+/// The circular arc through `start`, `through` and `end` — the three points uniquely define
+/// it — running counter-clockwise about the plane normal from `start` through `through` to
+/// `end`. `None` when the points coincide, are collinear (no circle through them) or the
+/// circle is out of range.
+pub fn arc_from_3_points(start: Vec3, through: Vec3, end: Vec3) -> Option<WireArc> {
+ let (b, c) = (through - start, end - start);
+ if b.len2() < 1e-18 || c.len2() < 1e-18 {
+ return None;
+ }
+ let n = b.cross(c);
+ // Collinear points make |n| vanish relative to the chord lengths; scale the test with them.
+ if n.len2() < 1e-18 * b.len2() * c.len2() {
+ return None;
+ }
+ let normal = n.normalized()?;
+ let center = start + (n.cross(b) * c.len2() + c.cross(n) * b.len2()) * (0.5 / n.len2());
+ let radius = center.dist(start);
+ if !center.is_finite() || !radius_in_range(radius) {
+ return None;
+ }
+ Some(WireArc { center, normal, radius, start, end })
+}
+
+/// The sweep of an exact 3D arc: the angle in (0, 2π) from `start` to `end` counter-clockwise
+/// about `normal`.
+pub fn arc_sweep(arc: &WireArc) -> f64 {
+ let (u, v) = (arc.start - arc.center, arc.end - arc.center);
+ let a = u.cross(v).dot(arc.normal).atan2(u.dot(v));
+ if a <= 0.0 { a + std::f64::consts::TAU } else { a }
+}
+
+/// The polyline of an exact 3D arc, sampled so every chord's sagitta stays within `tol`.
+pub fn arc_polyline(arc: &WireArc, tol: f64) -> Vec<Vec3> {
+ let sweep = arc_sweep(arc);
+ if !(arc.radius > 0.0) || !arc.radius.is_finite() || !sweep.is_finite() {
+ return vec![arc.start, arc.end];
+ }
+ // Sagitta of a chord spanning Δ on a circle r: r(1 − cos(Δ/2)) ≤ tol.
+ let max_step = (2.0 * (1.0 - (tol / arc.radius).clamp(0.0, 1.0)).acos()).max(1e-4);
+ let n = (sweep / max_step).ceil() as usize;
+ let n = n.clamp(2, MAX_WIRE_POINTS);
+ let u = arc.start - arc.center;
+ let e = arc.normal.cross(u); // in the arc's plane, perpendicular to u, same length
+ let mut out = Vec::with_capacity(n + 1);
+ for k in 0..=n {
+ let t = sweep * k as f64 / n as f64;
+ out.push(if k == n { arc.end } else { arc.center + u * t.cos() + e * t.sin() });
+ }
+ out
+}
+
+/// Is a saved arc consistent: in range, unit normal, and its ends on the circle?
+fn arc_ok(arc: &WireArc, fit: &[Vec3]) -> bool {
+ let on_circle = |p: Vec3| (arc.center.dist(p) - arc.radius).abs() < 1e-6 * arc.radius.max(1.0);
+ in_range3(arc.center)
+ && in_range3(arc.start)
+ && in_range3(arc.end)
+ && arc.normal.is_finite()
+ && (arc.normal.len() - 1.0).abs() < 1e-6
+ && radius_in_range(arc.radius)
+ && fit.len() == 3
+ && on_circle(arc.start)
+ && on_circle(arc.end)
+}
+
fn clean(w: &[Vec3]) -> Option<Vec<Vec3>> {
if w.len() > MAX_WIRE_POINTS {
return None;
@@ -168,6 +252,7 @@ impl Sketch {
|| w.fit.len() > MAX_FIT_POINTS
|| (w.pts.len() == 1 && w.fit.len() != 1)
|| w.pts.iter().chain(&w.fit).any(|p| !in_range3(*p))
+ || w.arc.as_ref().is_some_and(|a| !arc_ok(a, &w.fit))
{
return Err(SketchError::Invalid("3D curve arrays, ids or point bounds are invalid".into()));
}
@@ -223,7 +308,7 @@ impl Sketch {
Some(o) => o.clone(),
None => self.fresh("w")?,
};
- self.wires.push(Wire { id: wid, pts, space: WireSpace::Component, link: Some(id.to_string()), fit: Vec::new() });
+ self.wires.push(Wire { id: wid, pts, space: WireSpace::Component, link: Some(id.to_string()), fit: Vec::new(), arc: None });
}
Ok(())
}
@@ -238,7 +323,27 @@ impl Sketch {
let pts = drawn_polyline(fit)?;
self.wire_budget(None, 1, pts.len() + fit.len())?;
let id = self.fresh(if fit.len() == 1 { "q" } else { "w" })?;
- self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec() });
+ self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec(), arc: None });
+ Ok(id)
+ }
+
+ /// Add an exact circular arc drawn in a 3D sketch: `fit` is its three defining points
+ /// (start, through, end) in `space`; the wire keeps the analytic arc and its samples.
+ pub fn add_drawn_arc_in(&mut self, fit: &[Vec3], space: WireSpace) -> Result<String> {
+ let [start, through, end] = fit else {
+ return Err(SketchError::Invalid("a 3D arc needs exactly three points".into()));
+ };
+ for p in fit {
+ if !in_range3(*p) {
+ return Err(SketchError::Invalid("3D point out of range".into()));
+ }
+ }
+ let arc = arc_from_3_points(*start, *through, *end)
+ .ok_or_else(|| SketchError::Invalid("the three points of a 3D arc must differ and not be collinear".into()))?;
+ let pts = arc_polyline(&arc, ARC_TOL);
+ self.wire_budget(None, 1, pts.len() + fit.len())?;
+ let id = self.fresh("w")?;
+ self.wires.push(Wire { id: id.clone(), pts, space, link: None, fit: fit.to_vec(), arc: Some(arc) });
Ok(id)
}
@@ -267,13 +372,26 @@ impl Sketch {
n += 1;
}
if changed {
- let pts = drawn_polyline(&fit)?;
- changes.push((index, fit, pts));
+ // An exact arc keeps its analytic form: re-derive it from its three defining
+ // points; a spline keeps its fit-point polyline. Both before any change lands.
+ let (arc, pts) = match w.arc {
+ Some(_) => {
+ let [start, through, end] = fit.as_slice() else {
+ return Err(SketchError::Invalid("a 3D arc needs exactly three points".into()));
+ };
+ let arc = arc_from_3_points(*start, *through, *end)
+ .ok_or_else(|| SketchError::Invalid("a 3D arc's points must differ and not be collinear".into()))?;
+ (Some(arc), arc_polyline(&arc, ARC_TOL))
+ }
+ None => (None, drawn_polyline(&fit)?),
+ };
+ changes.push((index, fit, arc, pts));
}
}
- for (index, fit, pts) in changes {
+ for (index, fit, arc, pts) in changes {
if let Some(w) = self.wires.get_mut(index) {
w.fit = fit;
+ w.arc = arc;
w.pts = pts;
}
}
@@ -350,4 +468,85 @@ mod tests {
assert_eq!(open.first(), ring.first());
assert_eq!(open.last(), ring.get(11));
}
+
+ #[test]
+ fn an_arc_from_three_points_is_exact() {
+ // A quarter circle of radius 10 in the XY plane: 0° through 45° to 90°.
+ let arc = arc_from_3_points(
+ Vec3::new(10.0, 0.0, 0.0),
+ Vec3::new(5.0 * std::f64::consts::SQRT_2, 5.0 * std::f64::consts::SQRT_2, 0.0),
+ Vec3::new(0.0, 10.0, 0.0),
+ )
+ .unwrap();
+ assert!((arc.radius - 10.0).abs() < 1e-9, "radius {}", arc.radius);
+ assert!(arc.center.dist(Vec3::ZERO) < 1e-9, "centre {:?}", arc.center);
+ assert!((arc_sweep(&arc) - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "sweep {}", arc_sweep(&arc));
+ // A tilted plane: the same arc lifted onto a 45° plane keeps its radius and sweep.
+ let n = std::f64::consts::FRAC_PI_4;
+ let up = Vec3::new(0.0, n.sin(), n.cos());
+ let right = Vec3::new(1.0, 0.0, 0.0);
+ let at = |a: f64| up * (10.0 * a.sin()) + right * (10.0 * a.cos());
+ let tilted = arc_from_3_points(at(0.0), at(std::f64::consts::FRAC_PI_4), at(std::f64::consts::FRAC_PI_2)).unwrap();
+ assert!((tilted.radius - 10.0).abs() < 1e-9);
+ assert!((arc_sweep(&tilted) - std::f64::consts::FRAC_PI_2).abs() < 1e-9);
+ assert!(tilted.normal.dot(up.cross(right).normalized().unwrap()).abs() > 1.0 - 1e-9);
+ }
+
+ #[test]
+ fn an_arc_refuses_degenerate_and_hostile_points() {
+ // Collinear, coincident and out-of-range defining points never build an arc.
+ assert!(arc_from_3_points(Vec3::ZERO, Vec3::X, Vec3::X * 2.0).is_none());
+ assert!(arc_from_3_points(Vec3::ZERO, Vec3::ZERO, Vec3::Y).is_none());
+ assert!(arc_from_3_points(Vec3::ZERO, Vec3::new(1e-12, 0.0, 0.0), Vec3::Y).is_none());
+ let mut sk = Sketch::new();
+ assert!(sk.add_drawn_arc_in(&[Vec3::ZERO, Vec3::X, Vec3::X * 2.0], WireSpace::World).is_err());
+ assert!(sk.add_drawn_arc_in(&[Vec3::ZERO, Vec3::X], WireSpace::World).is_err());
+ assert!(sk.add_drawn_arc_in(&[Vec3::ZERO, Vec3::new(1e100, 0.0, 0.0), Vec3::Y], WireSpace::World).is_err());
+ assert!(sk.add_drawn_arc_in(&[Vec3::ZERO, Vec3::new(f64::NAN, 1.0, 0.0), Vec3::Y], WireSpace::World).is_err());
+ assert!(sk.wires.is_empty());
+ }
+
+ #[test]
+ fn an_arc_wire_stores_fit_points_samples_and_survives_a_round_trip() {
+ let mut sk = Sketch::new();
+ let id =
+ sk.add_drawn_arc_in(&[Vec3::new(10.0, 0.0, 5.0), Vec3::new(0.0, 10.0, 5.0), Vec3::new(-10.0, 0.0, 5.0)], WireSpace::Component).unwrap();
+ let w = sk.wires.iter().find(|w| w.id == id).unwrap();
+ assert_eq!(w.fit.len(), 3);
+ assert!(w.arc.is_some());
+ assert!(w.pts.len() >= 3);
+ assert_eq!(w.pts.first(), w.fit.first());
+ assert_eq!(w.pts.last(), w.fit.get(2));
+ // Every sample sits on the circle.
+ let arc = w.arc.unwrap();
+ assert!(w.pts.iter().all(|p| (arc.center.dist(*p) - arc.radius).abs() < 1e-6));
+ sk.validate_wires().unwrap();
+ let raw = serde_json::to_value(w).unwrap();
+ assert_eq!(serde_json::from_value::<Wire>(raw).unwrap(), *w);
+ }
+
+ #[test]
+ fn moving_an_arc_point_rebuilds_it_and_refuses_collinear() {
+ let mut sk = Sketch::new();
+ let id = sk.add_drawn_arc_in(&[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(-10.0, 0.0, 0.0)], WireSpace::World).unwrap();
+ // Pull the through point onto the chord: collinear, refused, and nothing changed.
+ let before = sk.clone();
+ assert!(sk.move_drawn_point(&id, 1, Vec3::ZERO).is_err());
+ assert_eq!(sk, before);
+ // Pull it off again: the arc follows and stays exact.
+ sk.move_drawn_point(&id, 1, Vec3::new(0.0, 5.0, 0.0)).unwrap();
+ let w = sk.wires.iter().find(|w| w.id == id).unwrap();
+ assert_eq!(w.fit[1], Vec3::new(0.0, 5.0, 0.0));
+ let arc = w.arc.unwrap();
+ assert!(w.pts.iter().all(|p| (arc.center.dist(*p) - arc.radius).abs() < 1e-6));
+ sk.validate_wires().unwrap();
+ }
+
+ #[test]
+ fn a_saved_arc_that_lies_about_its_circle_is_refused() {
+ let mut sk = Sketch::new();
+ sk.add_drawn_arc_in(&[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(-10.0, 0.0, 0.0)], WireSpace::World).unwrap();
+ sk.wires[0].arc.as_mut().unwrap().radius = 1.0; // claims a circle its ends are not on
+ assert!(sk.validate_wires().is_err());
+ }
}
diff --git a/crates/ui-egui/src/sketch3d.rs b/crates/ui-egui/src/sketch3d.rs
index de2377014a..76ddb2971e 100644
--- a/crates/ui-egui/src/sketch3d.rs
+++ b/crates/ui-egui/src/sketch3d.rs
@@ -1,9 +1,11 @@
-//! 3D sketching in the viewport (the Sketch Palette's 3D Sketch option): the Line, Spline and
-//! Point tools take points off the sketch plane by snapping to model vertices, edges and faces
-//! and to points already drawn in 3D; segments that stay on the plane are ordinary sketch lines.
-//! A drawn 3D point (or curve end) clicked without a tool gets a move triad: drag an arrow to
-//! move along X, Y or Z, or the square to move parallel to the sketch plane. Everything runs
-//! `sketch.line3d`, `sketch.spline3d`, `sketch.point3d`, `sketch.move3d` and `sketch.line`.
+//! 3D sketching in the viewport (the Sketch Palette's 3D Sketch option): the Line, Arc, Spline
+//! and Point tools take points off the sketch plane by snapping to model vertices, edges and
+//! faces and to points already drawn in 3D; segments that stay on the plane are ordinary sketch
+//! lines and arcs. The 3D Arc command has its own tool: every point it takes is a world point.
+//! A drawn 3D point (or curve end) clicked without a tool gets a move triad:
+//! drag an arrow to move along X, Y or Z, or the square to move parallel to the sketch plane.
+//! Everything runs `sketch.line3d`, `sketch.arc3d`, `sketch.spline3d`, `sketch.point3d`,
+//! `sketch.move3d`, `sketch.line` and `sketch.arc.three_point`.
use std::cell::RefCell;
@@ -37,7 +39,7 @@ pub fn active(app: &SolveApp) -> bool {
}
fn takes(cmd: &str) -> bool {
- matches!(cmd, "sketch.line" | "sketch.spline.fit_point" | "sketch.point")
+ matches!(cmd, "sketch.line" | "sketch.arc.three_point" | "sketch.arc3d" | "sketch.spline.fit_point" | "sketch.point")
}
/// Only 3D point-placing tools broaden sketch-point picking; ordinary selection stays local.
@@ -150,6 +152,23 @@ pub fn on_click(app: &mut SolveApp, tool: &mut Tool, proj: &Proj, pos: Pos2) ->
c.push(p);
set_chain(Some(tool.cmd), c);
}
+ "sketch.arc.three_point" | "sketch.arc3d" => {
+ let mut c = chain();
+ c.push(p);
+ if c.len() >= 3 {
+ // Same click order as the 2D tool: start, end, then a point on the arc.
+ let (a, e, t) = (c[0], c[1], c[2]);
+ let r = match (on_plane(app, a), on_plane(app, e), on_plane(app, t)) {
+ (Some(qa), Some(qe), Some(qt)) if tool.cmd == "sketch.arc.three_point" => {
+ app.run("sketch.arc.three_point", json!({"start": [qa.x, qa.y], "end": [qe.x, qe.y], "through": [qt.x, qt.y]}))
+ }
+ _ => app.run("sketch.arc3d", json!({"start": [a.x, a.y, a.z], "through": [t.x, t.y, t.z], "end": [e.x, e.y, e.z]})),
+ };
+ report(app, r);
+ c.clear();
+ }
+ set_chain(Some(tool.cmd), c);
+ }
_ => {
let mut c = chain();
c.push(p);
@@ -226,7 +245,18 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) -
tk.text_dim,
);
}
- if t.cmd == "sketch.spline.fit_point" && all.len() >= 2 {
+ if matches!(t.cmd, "sketch.arc.three_point" | "sketch.arc3d") && pts.len() == 2 {
+ // The arc the third click would finish: from the first point to the second, through the cursor.
+ let poly = match hover.map(|(h, _)| h) {
+ Some(h) => match solidcraft_engine::sketch::arc_from_3_points(pts[0], h, pts[1]) {
+ Some(a) => solidcraft_engine::sketch::arc_polyline(&a, 0.2),
+ None => vec![pts[0], h, pts[1]],
+ },
+ None => vec![pts[0], pts[1]],
+ };
+ let screen: Vec<Pos2> = poly.into_iter().filter_map(|p| proj.to_screen(p)).collect();
+ painter.add(Shape::line(screen, stroke));
+ } else if t.cmd == "sketch.spline.fit_point" && all.len() >= 2 {
let mut w: Vec<Vec3> = pts.clone();
if let Some((h, _)) = hover {
w.push(h);
diff --git a/crates/ui-egui/src/sketch3d_frame_ui_tests.rs b/crates/ui-egui/src/sketch3d_frame_ui_tests.rs
index c00f8c2be4..6a3291e770 100644
--- a/crates/ui-egui/src/sketch3d_frame_ui_tests.rs
+++ b/crates/ui-egui/src/sketch3d_frame_ui_tests.rs
@@ -194,3 +194,69 @@ fn second_occurrence_drawn_wire_fit_picks_and_world_triad_drag_stay_aligned() {
let restored = h.app.session.model.state();
assert!(restored.sketch(sketch).unwrap().sketch.wires[0].fit[0].dist(Vec3::new(2.0, 3.0, 5.0)) < 1e-6);
}
+
+#[test]
+fn arc_tool_draws_an_exact_3d_arc_off_the_plane() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("solid.box", json!({"corner":[10,0,5],"length":10,"width":10,"height":5,"body_name":"ArcPicks"})).unwrap();
+ let sketch = h.app.run("sketch.create", json!({"plane":"XY","name":"Arcs"})).unwrap()["sketch"].as_u64().unwrap();
+ h.app.run("sketch.options", json!({"sketch_3d":true})).unwrap();
+ h.app.session.visibility.origin_hidden = Some(true);
+ h.call("ui.view", json!({"view":"home"}));
+ h.call("ui.view", json!({"view":"fit"}));
+ h.frames(3);
+ h.app.start("sketch.arc.three_point");
+ h.frames(2);
+ h.app.status = None;
+ // Three top-face vertices: off the XY sketch plane, so the arc tool draws a 3D arc.
+ for p in [[10.0, 0.0, 10.0], [20.0, 10.0, 10.0], [10.0, 10.0, 10.0]] {
+ let [x, y] = h.at(&json!({"world": p})).unwrap();
+ let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap());
+ let picked = crate::sketch3d::point_at(&h.app, &proj, egui::pos2(x as f32, y as f32));
+ assert!(picked.is_some_and(|(q, _)| (q - Vec3::new(p[0], p[1], p[2])).dist(Vec3::ZERO) < 1e-5), "p={p:?}, picked={picked:?}");
+ h.step(&json!({"click": {"world": p}})).unwrap();
+ }
+ h.step(&json!({"key": "Escape"})).unwrap();
+ let state = h.app.session.world_state();
+ let wires = &state.sketch(sketch).unwrap().sketch.wires;
+ assert_eq!(wires.len(), 1, "three off-plane clicks draw one 3D arc");
+ let w = &wires[0];
+ let arc = w.arc.expect("the drawn arc is stored exactly");
+ assert!(arc.center.dist(Vec3::new(15.0, 5.0, 10.0)) < 1e-6, "{:?}", arc.center);
+ assert!((arc.radius - 50.0_f64.sqrt()).abs() < 1e-6, "{}", arc.radius);
+ assert_eq!(w.fit.len(), 3);
+}
+
+#[test]
+fn arc3d_button_starts_its_own_tool() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.run("solid.box", json!({"corner":[10,0,5],"length":10,"width":10,"height":5,"body_name":"Arc3dBtn"})).unwrap();
+ let sketch = h.app.run("sketch.create", json!({"plane":"XY","name":"Arcs"})).unwrap()["sketch"].as_u64().unwrap();
+ h.app.run("sketch.options", json!({"sketch_3d":true})).unwrap();
+ h.app.session.visibility.origin_hidden = Some(true);
+ h.call("ui.view", json!({"view":"home"}));
+ h.call("ui.view", json!({"view":"fit"}));
+ h.frames(3);
+ h.app.start("sketch.arc3d");
+ assert!(h.app.tool.as_ref().is_some_and(|t| t.cmd == "sketch.arc3d"), "the 3D Arc button starts a tool: {:?}", h.app.status);
+ h.frames(2);
+ h.app.status = None;
+ // Same click order as the 2D arc tool: start, end, then a point on the arc.
+ for p in [[10.0, 0.0, 10.0], [10.0, 10.0, 10.0], [20.0, 10.0, 10.0]] {
+ h.step(&json!({"click": {"world": p}})).unwrap();
+ }
+ let state = h.app.session.world_state();
+ let wires = &state.sketch(sketch).unwrap().sketch.wires;
+ assert_eq!(wires.len(), 1, "three clicks draw one exact 3D arc");
+ let arc = wires[0].arc.expect("the drawn arc is stored exactly");
+ assert!(arc.center.dist(Vec3::new(15.0, 5.0, 10.0)) < 1e-6, "{:?}", arc.center);
+ assert!((arc.radius - 50.0_f64.sqrt()).abs() < 1e-6, "{}", arc.radius);
+ assert!(arc.start.dist(Vec3::new(10.0, 0.0, 10.0)) < 1e-6, "{:?}", arc.start);
+ assert!(arc.end.dist(Vec3::new(10.0, 10.0, 10.0)) < 1e-6, "{:?}", arc.end);
+ // With 3D Sketch off the button is not offered: its tool could only fail.
+ h.step(&json!({"key": "Escape"})).unwrap();
+ assert!(h.app.tool.is_none(), "Escape ends the tool");
+ h.app.run("sketch.options", json!({"sketch_3d": false})).unwrap();
+ h.app.start("sketch.arc3d");
+ assert!(h.app.tool.is_none(), "3D Arc is disabled while 3D Sketch is off");
+}
diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs
index 7bac922757..4e2af4da25 100644
--- a/crates/ui-egui/src/tools.rs
+++ b/crates/ui-egui/src/tools.rs
@@ -105,6 +105,7 @@ impl Tool {
"sketch.circle.two_point" => ("sketch.circle.two_point", Kind::Draw(2)),
"sketch.circle.three_point" => ("sketch.circle.three_point", Kind::Draw(3)),
"sketch.arc.three_point" => ("sketch.arc.three_point", Kind::Draw(3)),
+ "sketch.arc3d" => ("sketch.arc3d", Kind::Draw(3)),
"sketch.arc.center_point" => ("sketch.arc.center_point", Kind::Draw(3)),
"sketch.polygon.inscribed" => ("sketch.polygon.inscribed", Kind::Draw(2)),
"sketch.polygon.circumscribed" => ("sketch.polygon.circumscribed", Kind::Draw(2)),
@@ -150,6 +151,7 @@ pub fn hint(id: &str) -> String {
"sketch.rectangle.three_point" => "3-point rectangle: click two points of one edge, then the width".into(),
"sketch.circle.center" => "Circle: click the centre, then a point on the circle".into(),
"sketch.arc.three_point" => "Arc: click start, end, then a point on the arc".into(),
+ "sketch.arc3d" => "3D Arc: click start, end, then a point on the arc (points may leave the sketch plane)".into(),
"sketch.arc.center_point" => "Arc: click centre and start, then click end or type a signed sweep".into(),
"sketch.dimension" => {
"Dimension: pick one or two entities and type the value (or click to place it first); click a dimension to edit it; Enter applies".into()
diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs
index dccb1689e3..d58abdd35d 100644
--- a/crates/ui-egui/src/workspace.rs
+++ b/crates/ui-egui/src/workspace.rs
@@ -74,7 +74,7 @@ pub const SECTIONS: &[Section] = &[
tab: "MODEL",
panel: "SKETCH",
promoted: 1,
- ids: &["sketch.create", "sketch.edit", "sketch.line3d", "sketch.spline3d", "sketch.point3d", "sketch.move3d"],
+ ids: &["sketch.create", "sketch.edit", "sketch.line3d", "sketch.arc3d", "sketch.spline3d", "sketch.point3d", "sketch.move3d"],
},
Section { tab: "MODEL", panel: "CREATE", promoted: 3, ids: &["solid.extrude", "solid.revolve", "solid.hole"] },
Section {