Skip to content

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

Extrude: the distance arrow snaps to a parallel face and outlines it (#2398) (#9688)

PaddleStrokedb3558d82052
diff --git a/assets/locales/pending/extrude-arrow-face-stops.json b/assets/locales/pending/extrude-arrow-face-stops.json
new file mode 100644
index 0000000000..915ee194ae
--- /dev/null
+++ b/assets/locales/pending/extrude-arrow-face-stops.json
@@ -0,0 +1,38 @@
+{
+ "en": {
+ "prefs.extrude_arrow_face_stops": "Extrude arrow stops at faces",
+ "prefs.extrude_arrow_face_stops_note": "Dragging Extrude's distance arrow stops at flat faces parallel to the profile, such as the far side of a block being cut, and outlines the face. Off: the arrow moves in round steps only."
+ },
+ "ar": {
+ "prefs.extrude_arrow_face_stops": "يتوقف سهم البثق عند الأوجه",
+ "prefs.extrude_arrow_face_stops_note": "عند سحب سهم مسافة البثق يتوقف عند الأوجه المستوية الموازية للمقطع، مثل الجانب البعيد من كتلة يجري قطعها، ويحدد الوجه. عند الإيقاف: يتحرك السهم بخطوات مستديرة فقط."
+ },
+ "he": {
+ "prefs.extrude_arrow_face_stops": "חץ השליפה נעצר בפאות",
+ "prefs.extrude_arrow_face_stops_note": "גרירת חץ המרחק של השליפה נעצרת בפאות שטוחות המקבילות לפרופיל, כמו הצד הרחוק של גוש שנחתך, ומדגישה את קו המתאר של הפאה. כבוי: החץ זז בצעדים עגולים בלבד."
+ },
+ "ja": {
+ "prefs.extrude_arrow_face_stops": "押し出し矢印を面で止める",
+ "prefs.extrude_arrow_face_stops_note": "押し出しの距離矢印をドラッグすると、プロファイルに平行な平らな面(カットするブロックの反対側など)で止まり、その面の輪郭を表示します。オフ: 矢印はきりのよい刻みでのみ動きます。"
+ },
+ "vi": {
+ "prefs.extrude_arrow_face_stops": "Mũi tên đùn dừng tại các mặt",
+ "prefs.extrude_arrow_face_stops_note": "Khi kéo mũi tên khoảng cách của Đùn, nó dừng tại các mặt phẳng song song với biên dạng, chẳng hạn mặt bên kia của khối đang cắt, và tô viền mặt đó. Tắt: mũi tên chỉ di chuyển theo các bước tròn."
+ },
+ "zh": {
+ "prefs.extrude_arrow_face_stops": "拉伸箭头停在面上",
+ "prefs.extrude_arrow_face_stops_note": "拖动拉伸的距离箭头时,它会停在与轮廓平行的平面上(例如正在切除的块的另一侧),并勾勒出该面。关闭:箭头只按整数步长移动。"
+ },
+ "fr": {
+ "prefs.extrude_arrow_face_stops": "La flèche d'extrusion s'arrête aux faces",
+ "prefs.extrude_arrow_face_stops_note": "En faisant glisser la flèche de distance d'Extrusion, elle s'arrête aux faces planes parallèles au profil, comme l'autre côté d'un bloc qu'on découpe, et souligne la face. Désactivé : la flèche avance seulement par pas ronds."
+ },
+ "de": {
+ "prefs.extrude_arrow_face_stops": "Extrusionspfeil hält an Flächen",
+ "prefs.extrude_arrow_face_stops_note": "Beim Ziehen des Abstandspfeils von Extrusion hält er an ebenen Flächen parallel zum Profil, etwa an der Rückseite eines Blocks, in den geschnitten wird, und hebt die Fläche hervor. Aus: Der Pfeil bewegt sich nur in runden Schritten."
+ },
+ "es": {
+ "prefs.extrude_arrow_face_stops": "La flecha de Extruir se detiene en las caras",
+ "prefs.extrude_arrow_face_stops_note": "Al arrastrar la flecha de distancia de Extruir, se detiene en las caras planas paralelas al perfil, como el lado opuesto de un bloque que se corta, y resalta la cara. Desactivado: la flecha solo avanza en pasos redondos."
+ }
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index ec8e90ebbe..fb26669721 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -340,6 +340,7 @@ pub(crate) fn owns_pointer(app: &SolveApp, proj: &Proj, p: Pos2) -> bool {
/// Draw the manipulator and the value box (called by the viewport after the model is drawn).
pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj) {
+ crate::extrude_face_snap::set(None);
// While OK computes, the inputs hold what it computes: no arrow to drag, no box to type in.
if app.applying.is_some() {
return;
@@ -755,6 +756,12 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
}
// A placement marker at the base: the arrow stands above it and the base dot is the marker's.
let clear = crate::place_gizmo::arrow_clearance(app, d);
+ // While an extrude's arrow is dragged, the flat faces it can stop at (#2398).
+ let arrow_id = egui::Id::unique("sc_manipulator");
+ let stops = match dir {
+ Some(n) if ui.ctx().is_being_dragged(arrow_id) => crate::extrude_face_snap::stops(app, d, base, n * sign),
+ _ => Vec::new(),
+ };
let Some((label, kind, value)) = d.primary() else { return };
let len = all_span.or_else(|| {
if to_span.is_some() && value.trim().is_empty() {
@@ -775,21 +782,22 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
let mut shown_value = format_len(&app.session.doc, half + baseline);
let original_shown = shown_value.clone();
let dragged = if to_span.is_some() || symmetric_scale != 1.0 { &mut shown_value } else { &mut *value };
- if let Some(ts) = drag_arrow(
+ let drawn = drag_arrow_to(
&app.session.doc,
ui,
painter,
proj,
- base,
- bs,
- n,
- half + baseline,
- signed,
- egui::Id::unique("sc_manipulator"),
+ ArrowLine { base, bs, n, l: half + baseline, signed, clear_px: clear },
+ arrow_id,
half_height,
- clear,
+ &stops,
dragged,
- ) {
+ );
+ if let Some((_, Some(stop))) = &drawn {
+ crate::extrude_face_snap::outline(app, painter, proj, stop);
+ }
+ crate::extrude_face_snap::set(drawn.as_ref().and_then(|(_, stop)| stop.clone()));
+ if let Some((ts, _)) = drawn {
if (to_span.is_some() || symmetric_scale != 1.0)
&& shown_value != original_shown
&& let Ok(v) = crate::length_input::eval(&app.session.doc, &shown_value, ValueKind::Length)
@@ -1083,6 +1091,39 @@ fn drag_arrow(
clear_px: f32,
value: &mut String,
) -> Option<Pos2> {
+ let line = ArrowLine { base, bs, n, l, signed, clear_px };
+ drag_arrow_to(doc, ui, painter, proj, line, id, half_height, &[], value).map(|(ts, _)| ts)
+}
+
+/// Where a drag arrow stands: from `base` (on screen `bs`) along `n`, showing `l`; `signed` lets
+/// it go below zero, `clear_px` keeps that much of the base free (see [`drag_arrow`]).
+#[derive(Clone, Copy, Debug)]
+struct ArrowLine {
+ base: Vec3,
+ bs: Pos2,
+ n: Vec3,
+ l: f64,
+ signed: bool,
+ clear_px: f32,
+}
+
+/// [`drag_arrow`] that also stops at `stops` (#2398): a drag whose tip comes near a stop's
+/// plane takes its distance exactly instead of a round step. Returns the tip's screen position
+/// and the stop it took this frame.
+#[allow(clippy::too_many_arguments)]
+fn drag_arrow_to(
+ doc: &solidcraft_engine::doc::Document,
+ ui: &mut egui::Ui,
+ painter: &egui::Painter,
+ proj: &Proj,
+ line: ArrowLine,
+ id: egui::Id,
+ half_height: f64,
+ stops: &[crate::extrude_face_snap::Stop],
+ value: &mut String,
+) -> Option<(Pos2, Option<crate::extrude_face_snap::Stop>)> {
+ let ArrowLine { base, bs, n, l, signed, clear_px } = line;
+ let mut stopped = None;
let t = Tokens::get();
let min = f64::from(40.0 + clear_px) * 2.0 * half_height / f64::from(proj.rect.height().max(1.0));
let tip = |length: f64| {
@@ -1124,7 +1165,12 @@ fn drag_arrow(
let v = v - ui.data(|d| d.get_temp::<f64>(grab)).unwrap_or(0.0);
let free = crate::tool_modifiers::manipulator_free();
let step = snap_step(half_height);
- let mut v = if free { v } else { (v / step).round() * step };
+ stopped = if free { None } else { crate::extrude_face_snap::nearest(proj, base, n, v, stops).cloned() };
+ let mut v = match &stopped {
+ Some(stop) => stop.distance,
+ None if free => v,
+ None => (v / step).round() * step,
+ };
if !signed {
v = v.max(if free { 1e-3 } else { step });
}
@@ -1141,7 +1187,7 @@ fn drag_arrow(
painter.circle_stroke(ts, 8.0, Stroke::new(1.5, col));
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
}
- Some(ts)
+ Some((ts, stopped))
}
/// A fillet's radius spline on each of its edges (a spline fillet, or the splines a taper gave
diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rs
index 85ee2ba167..bb211556be 100644
--- a/crates/ui-egui/src/extrude_edit_tests.rs
+++ b/crates/ui-egui/src/extrude_edit_tests.rs
@@ -666,3 +666,106 @@ fn failed_face_extrusion_edit_keeps_context_until_escape_and_preserves_visibilit
assert!(!h.app.body_visible("Source"));
assert_eq!(h.app.session.visibility, visibility);
}
+
+/// A block 12.345678 mm thick under XY (so no round step lands on its underside), a 10 mm
+/// square sketched on its top and cut 5 mm into it, a second block beside it whose underside is
+/// at -7.777 mm, and the cut open in its editor.
+fn cut_into_block() -> Harness {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.run("solid.box", json!({"length":30,"width":30,"height":12.345678,"corner":[-10,-10,-12.345678],"body_name":"Block"})).unwrap();
+ h.app
+ .run("solid.box", json!({"length":10,"width":10,"height":7.777,"corner":[40,0,-7.777],"body_name":"Beside","operation":"new_body"}))
+ .unwrap();
+ h.app.run("sketch.create", json!({"plane":"XY","name":"Pocket"})).unwrap();
+ h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,10]})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ let cut = json!({"sketch":"Pocket","direction":"negative","distance":"5 mm","operation":"cut","targets":["Block"],"name":"Depth"});
+ h.app.run("solid.extrude", cut).unwrap();
+ h.call("ui.view", json!({"view":"fit"}));
+ h.frames(4);
+ open(&mut h);
+ h
+}
+
+/// Presses the arrow's tip and holds it at the world point `to`, frame by frame, without letting
+/// go; returns the face the arrow stopped at then.
+fn hold_arrow_at(h: &mut Harness, to: Value) -> Option<crate::extrude_face_snap::Stop> {
+ let from = h.at(&json!({"handle":"arrow"})).unwrap();
+ let from = egui::pos2(from[0] as f32, from[1] as f32);
+ let to = h.at(&to).unwrap();
+ let to = egui::pos2(to[0] as f32, to[1] as f32);
+ h.app.synthetic.push(egui::Event::PointerMoved(from));
+ h.frame();
+ h.app.synthetic.push(egui::Event::PointerButton {
+ pos: from,
+ button: egui::PointerButton::Primary,
+ pressed: true,
+ modifiers: h.app.synthetic_mods,
+ });
+ h.frame();
+ for k in 1..=4 {
+ h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 4.0)));
+ h.frame();
+ }
+ crate::extrude_face_snap::current()
+}
+
+fn let_go(h: &mut Harness) {
+ let at = h.ctx.input(|i| i.pointer.hover_pos()).unwrap_or_default();
+ h.app.synthetic.push(egui::Event::PointerButton {
+ pos: at,
+ button: egui::PointerButton::Primary,
+ pressed: false,
+ modifiers: h.app.synthetic_mods,
+ });
+ h.frames(2);
+}
+
+/// Extrude Cut depth stops at the far face (#2398): dragged near the block's underside, the
+/// cut's arrow takes its exact depth (not a round step) and outlines that face; OK cuts through.
+#[test]
+fn the_extrude_arrow_stops_at_a_parallel_face_and_outlines_it() {
+ let mut h = cut_into_block();
+ let stop = hold_arrow_at(&mut h, json!({"world":[5,5,-12.2]}));
+ let stop = stop.expect("the arrow stops at the block's underside");
+ assert_eq!((stop.body.as_str(), (stop.distance - 12.345678).abs() < 1e-9), ("Block", true), "{stop:?}");
+ assert!((dialog_distance(&h) - 12.345678).abs() < 1e-9, "{}", dialog_distance(&h));
+ let_go(&mut h);
+ assert!(crate::extrude_face_snap::current().is_none(), "no outline once the arrow is let go");
+ assert!((dialog_distance(&h) - 12.345678).abs() < 1e-9, "{}", dialog_distance(&h));
+ h.step(&json!({"widget":"OK"})).unwrap();
+ assert!(h.app.dialog.is_none(), "{:?}", h.app.session.log);
+ let expected = 30.0 * 30.0 * 12.345678 - 10.0 * 10.0 * 12.345678;
+ assert!((volume(&h, "Block") - expected).abs() < 1e-6, "{} for {expected}", volume(&h, "Block"));
+}
+
+/// The free drag (Ctrl held) passes the face by, and a face beside the profile never catches the
+/// arrow: the distance stays the pointer's or a round step.
+#[test]
+fn the_extrude_arrow_passes_faces_beside_the_profile_and_in_a_free_drag() {
+ let mut h = cut_into_block();
+ // The other block's underside at -7.777 is not under the square.
+ assert_eq!(hold_arrow_at(&mut h, json!({"world":[5,5,-7.75]})), None);
+ assert!((dialog_distance(&h) - 7.777).abs() > 1e-6, "{}", dialog_distance(&h));
+ let_go(&mut h);
+ h.app.synthetic_mods.ctrl = true;
+ assert_eq!(hold_arrow_at(&mut h, json!({"world":[5,5,-12.2]})), None);
+ assert!((dialog_distance(&h) - 12.345678).abs() > 1e-3, "{}", dialog_distance(&h));
+ let_go(&mut h);
+}
+
+/// With Preferences › Design › "Extrude arrow stops at faces" off, the arrow keeps the old
+/// behaviour (#2398): dragged near the block's underside it takes a round step, not the face's
+/// distance, and nothing is outlined.
+#[test]
+fn without_face_stops_the_extrude_arrow_moves_in_round_steps() {
+ let mut h = cut_into_block();
+ h.app.preferences.extrude_arrow_face_stops = false;
+ assert_eq!(hold_arrow_at(&mut h, json!({"world":[5,5,-12.2]})), None);
+ let d = dialog_distance(&h);
+ assert!((d - 12.345678).abs() > 1e-3, "{d}");
+ let step = crate::canvas::snap_step(h.app.cam.half_height());
+ assert!(((d / step).round() * step - d).abs() < 1e-9, "{d} is not a multiple of the {step} mm step");
+ let_go(&mut h);
+}
diff --git a/crates/ui-egui/src/extrude_face_snap.rs b/crates/ui-egui/src/extrude_face_snap.rs
new file mode 100644
index 0000000000..c027366181
--- /dev/null
+++ b/crates/ui-egui/src/extrude_face_snap.rs
@@ -0,0 +1,212 @@
+//! Extrude's distance arrow stops at faces (#2398). While the arrow is dragged, a flat face
+//! parallel to the profile takes the distance once the arrow's tip comes within a few screen
+//! points of its plane: the distance becomes exactly the face's, and the face is outlined. A
+//! cut dragged through a block so stops at the block's far side, and the outline shows it got
+//! there. Only faces over the profile's footprint count (seen along the arrow), so faces off to
+//! the side of the profile don't catch the arrow. Holding Alt or Ctrl (the free drag) turns
+//! this off with the round steps. Preferences › Tools › `extrude_arrow_face_stops` (on by
+//! default) turns it off for good: the arrow then moves in round steps only, as before.
+//!
+//! The distance stays a distance: the face is not stored with the extrude (To Object does that).
+
+use std::cell::RefCell;
+use std::sync::Arc;
+
+use egui::{Pos2, Stroke};
+use solidcore_record::{Plane, Vec2, Vec3};
+use solidcraft_engine::Sel;
+use solidcraft_engine::doc::ModelState;
+use solidcraft_engine::geom::{Mesh, prelude::*};
+
+use crate::SolveApp;
+use crate::dialogs::{Dialog, Kind};
+use crate::theme::Tokens;
+use crate::viewport::Proj;
+
+/// How near (screen points) the arrow's tip must come to a face's plane to stop there.
+pub const SNAP_PX: f32 = 8.0;
+/// How closely (cosine) a face's normal must follow the arrow to count as parallel.
+const PARALLEL: f64 = 1.0 - 1e-6;
+/// The most faces looked at in one model, and the most points kept of each.
+const MAX_FACES: usize = 20_000;
+const MAX_POINTS: usize = 4_096;
+
+/// A face the arrow can stop at: `distance` along the arrow from its base to the face's plane.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Stop {
+ pub body: String,
+ pub face: usize,
+ pub distance: f64,
+}
+
+/// A flat face of a body: a point on it, its unit normal and its corners' bounds.
+#[derive(Clone, Debug)]
+struct FlatFace {
+ body: String,
+ face: usize,
+ point: Vec3,
+ normal: Vec3,
+ points: Vec<Vec3>,
+}
+
+type Faces = (Option<Arc<ModelState>>, Arc<Vec<FlatFace>>);
+
+thread_local! {
+ /// The face the arrow stopped at this frame (for the outline, scenarios and tests).
+ static CURRENT: RefCell<Option<Stop>> = const { RefCell::new(None) };
+ /// The flat faces of the last model state looked at.
+ static FACES: RefCell<Faces> = RefCell::new((None, Arc::new(Vec::new())));
+}
+
+/// The face the arrow stopped at in the last frame drawn, if any.
+#[cfg(test)]
+pub fn current() -> Option<Stop> {
+ CURRENT.with(|c| c.borrow().clone())
+}
+
+pub(crate) fn set(stop: Option<Stop>) {
+ CURRENT.with(|c| *c.borrow_mut() = stop);
+}
+
+/// The flat faces of a mesh: per face, the plane its triangles lie in (within a tolerance
+/// scaled to the mesh) and its points.
+fn flat_faces_of(body: &str, m: &Mesh) -> Vec<FlatFace> {
+ let mut by_face: Vec<(Vec3, Vec<Vec3>)> = Vec::new();
+ for (t, f) in m.triangles.iter().zip(&m.tri_face) {
+ let f = *f as usize;
+ if f >= MAX_FACES {
+ continue;
+ }
+ let Some([a, b, c]) = m.tri(t) else { continue };
+ if by_face.len() <= f {
+ by_face.resize_with(f + 1, || (Vec3::ZERO, Vec::new()));
+ }
+ let Some((n, pts)) = by_face.get_mut(f) else { continue };
+ *n += (b - a).cross(c - a);
+ if pts.len() + 3 <= MAX_POINTS {
+ pts.extend([a, b, c]);
+ }
+ }
+ let tol = (m.bounds().diagonal() * 1e-6).max(1e-7) * 10.0;
+ by_face
+ .into_iter()
+ .enumerate()
+ .filter_map(|(face, (n, points))| {
+ let normal = n.normalized()?;
+ let point = *points.first()?;
+ let flat = points.iter().all(|p| (*p - point).dot(normal).abs() <= tol);
+ (flat && normal.is_finite()).then(|| FlatFace { body: body.to_string(), face, point, normal, points })
+ })
+ .collect()
+}
+
+/// The flat faces of every body in `st`, kept while the state stays the same.
+fn flat_faces(st: &Arc<ModelState>) -> Arc<Vec<FlatFace>> {
+ if let Some(known) = FACES.with(|c| {
+ let c = c.borrow();
+ c.0.as_ref().filter(|k| Arc::ptr_eq(k, st)).map(|_| c.1.clone())
+ }) {
+ return known;
+ }
+ let faces: Arc<Vec<FlatFace>> = Arc::new(st.bodies.iter().flat_map(|b| flat_faces_of(&b.name, &b.mesh())).collect());
+ FACES.with(|c| *c.borrow_mut() = (Some(st.clone()), faces.clone()));
+ faces
+}
+
+/// The bounds, in the plane's own coordinates, of `points` seen along the plane's normal.
+fn bounds_2d(plane: &Plane, points: impl IntoIterator<Item = Vec3>) -> Option<(Vec2, Vec2)> {
+ let mut out: Option<(Vec2, Vec2)> = None;
+ for p in points {
+ let q = plane.to_local(p);
+ if !(q.x.is_finite() && q.y.is_finite()) {
+ continue;
+ }
+ out = Some(match out {
+ None => (q, q),
+ Some((lo, hi)) => (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y))),
+ });
+ }
+ out
+}
+
+/// What the extrude starts from, as world points: its profiles' outlines, or its faces' points.
+fn footprint(app: &SolveApp, d: &Dialog, faces: &[FlatFace]) -> Vec<Vec3> {
+ let Ok(st) = app.session.world_state() else { return Vec::new() };
+ let mut out = Vec::new();
+ for item in d.inputs.first().map(|i| i.items.as_slice()).unwrap_or_default() {
+ match item {
+ Sel::Profile { sketch, index } => {
+ let (Some(ss), Some(plane)) = (st.sketch(*sketch), crate::canvas::profile_plane(app, *sketch)) else { continue };
+ if let Some(p) = ss.profiles.get(*index) {
+ out.extend(p.region.outer.polyline(1e-2).into_iter().take(MAX_POINTS).map(|q| plane.to_world(q)));
+ }
+ }
+ Sel::Face { body, index, .. } => {
+ if let Some(f) = faces.iter().find(|f| f.body == *body && f.face == *index) {
+ out.extend(f.points.iter().copied());
+ }
+ }
+ _ => {}
+ }
+ }
+ out
+}
+
+/// The faces the open extrude's arrow (from `base` along `n`) can stop at: flat faces of shown
+/// bodies, parallel to the arrow, off the base's own plane, over the footprint.
+pub(crate) fn stops(app: &SolveApp, d: &Dialog, base: Vec3, n: Vec3) -> Vec<Stop> {
+ if !app.preferences.extrude_arrow_face_stops || !matches!(d.kind, Kind::Extrude { .. }) {
+ return Vec::new();
+ }
+ let Some(plane) = Plane::from_normal(base, n) else { return Vec::new() };
+ let Ok(st) = app.session.world_state() else { return Vec::new() };
+ let faces = flat_faces(&st);
+ let Some((lo, hi)) = bounds_2d(&plane, footprint(app, d, &faces)) else { return Vec::new() };
+ let size = lo.dist(hi).max(1.0);
+ let tol = size * 1e-6;
+ let mut out: Vec<Stop> = faces
+ .iter()
+ .filter(|f| f.normal.dot(n).abs() >= PARALLEL && app.body_visible(&f.body))
+ .filter_map(|f| {
+ let distance = (f.point - base).dot(n);
+ if !distance.is_finite() || distance.abs() <= tol {
+ return None;
+ }
+ let (flo, fhi) = bounds_2d(&plane, f.points.iter().copied())?;
+ let over = flo.x <= hi.x + tol && fhi.x >= lo.x - tol && flo.y <= hi.y + tol && fhi.y >= lo.y - tol;
+ over.then(|| Stop { body: f.body.clone(), face: f.face, distance })
+ })
+ .collect();
+ out.sort_by(|a, b| a.distance.total_cmp(&b.distance));
+ out
+}
+
+/// The stop nearest the arrow's tip on screen when the tip is at `along` (from `base` along
+/// `n`), if one is within [`SNAP_PX`].
+pub(crate) fn nearest<'a>(proj: &Proj, base: Vec3, n: Vec3, along: f64, stops: &'a [Stop]) -> Option<&'a Stop> {
+ let tip = proj.to_screen(base + n * along)?;
+ stops
+ .iter()
+ .filter_map(|s| Some((s, proj.to_screen(base + n * s.distance)?.distance(tip))))
+ .filter(|(_, px)| *px <= SNAP_PX)
+ .min_by(|a, b| a.1.total_cmp(&b.1))
+ .map(|(s, _)| s)
+}
+
+/// Outlines the face the arrow stopped at, as a hovered face's edges are drawn.
+pub(crate) fn outline(app: &SolveApp, painter: &egui::Painter, proj: &Proj, stop: &Stop) {
+ let Ok(st) = app.session.world_state() else { return };
+ let Some(b) = st.body(&stop.body) else { return };
+ let m = b.mesh();
+ let t = Tokens::get();
+ let Ok(face) = u32::try_from(stop.face) else { return };
+ for e in m.face_edges(face) {
+ let Some(pts) = m.edges.get(e) else { continue };
+ let screen: Vec<Pos2> = pts.iter().filter_map(|p| proj.to_screen(*p)).collect();
+ if screen.len() < 2 {
+ continue;
+ }
+ painter.add(egui::Shape::line(screen.clone(), Stroke::new(5.0, t.hover_edge_halo)));
+ painter.add(egui::Shape::line(screen, Stroke::new(2.5, t.hover_edge)));
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index e8e473c19e..01db64e591 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -169,6 +169,7 @@ mod expression_complete;
mod extrude_auto_to_object_tests;
#[cfg(test)]
mod extrude_edit_tests;
+mod extrude_face_snap;
mod extrude_preview;
mod file_load;
mod file_picker;
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 08a660141a..f6f3b3db3f 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1435,6 +1435,9 @@ preference_settings! {
/// How the offer is made for a file whose header names no program known to save Y up: a note
/// over the view (the default), the dialog, or nothing (#7717).
stand_up_unknown: StandUpUnknown = StandUpUnknown::default(), PAGE_DESIGN;
+ /// Dragging Extrude's distance arrow stops at flat faces parallel to the profile over it and
+ /// outlines them (`extrude_face_snap`, #2398). Off: the drag moves in round steps only.
+ extrude_arrow_face_stops: bool = true, PAGE_TOOLS => check_id("prefs.extrude_arrow_face_stops");
/// Extrude: with a profile picked, a face, vertex or parallel plane picked off its plane
/// switches the extent to To Object (off: picks only add profiles, as before). A click into the
/// Profiles box makes the next picks profiles again.
@@ -6172,6 +6175,7 @@ mod tests {
("direct_interaction", json!(true), PAGE_TOOLS),
("hole_snaps", json!(true), PAGE_TOOLS),
("hole_moves", json!(true), PAGE_TOOLS),
+ ("extrude_arrow_face_stops", json!(false), PAGE_TOOLS),
("extrude_auto_to_object", json!(false), PAGE_TOOLS),
("extrude_view_isometric", json!(true), PAGE_TOOLS),
("extrude_view_return", json!(true), PAGE_TOOLS),
diff --git a/crates/ui-egui/src/prefs/tools.rs b/crates/ui-egui/src/prefs/tools.rs
index 24ab1196ff..e573f97f3a 100644
--- a/crates/ui-egui/src/prefs/tools.rs
+++ b/crates/ui-egui/src/prefs/tools.rs
@@ -35,6 +35,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
"extrude_auto_to_object",
),
(setting::auto_operation, "prefs.auto_operation_note", "auto_operation"),
+ (setting::extrude_arrow_face_stops, "prefs.extrude_arrow_face_stops_note", "extrude_arrow_face_stops"),
] {
ui.horizontal_wrapped(|ui| {
let response = setting(app, ui).backing_on_hover_text(app.tr(help));
diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md
index 38a7ee90a2..26dc4556fe 100644
--- a/docs/book/src/guide/features.md
+++ b/docs/book/src/guide/features.md
@@ -89,6 +89,14 @@ start or end offsets or a From Object input, the target also sets the stored dis
one-sided direction, so returning to **Distance** keeps that reach. Thin Extrude keeps its
existing picks. With the setting off, picks only add profiles.
+Dragging Extrude's distance arrow stops at flat faces parallel to the profile that lie over it,
+such as the far side of the block a cut goes into: once the arrow's tip comes within a few
+screen points of such a face, the distance becomes exactly that face's and the face is
+outlined. Elsewhere the distance moves in round steps. Hold Alt or Ctrl for a free drag, which
+stops at neither. **Extrude arrow stops at faces** (Preferences › Tools, on by default) turns
+the face stops off; the arrow then moves in round steps only, as before. The distance stays a number; to follow the face when the model changes, use
+**To Object** or **Through All**.
+
A positive extrude taper slopes the side walls outward, so the profile grows along the
extrusion direction and the far end is larger; a negative taper slopes them inward, making
the far end smaller. For example, a 10 × 10 mm square extruded 10 mm with `taper: "5 deg"`
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 42ad991144..5d6022d7f4 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -714,6 +714,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own
- `dimension_input` (`view` (default): a sketch dimension's value is typed in a box on the dimension; `window`: placing a dimension with the Dimension tool, or double-clicking one, opens a small window at it with the value field (handle `dimwin:value`), arrows that step the value (`dimwin:up`, `dimwin:down`), a check (`dimwin:ok`, also Enter) and a cross (`dimwin:cancel`, also Esc), #7246)
- `dimension_step_deg` (default 1, 0.001…180: what the dimension window's arrows, Up/Down and the wheel over its field add to an angle, in degrees)
- `dimension_step_mm` (default 1, 0.001…1000: what the window's arrows, Up/Down and the wheel over its field add to a length, in millimetres, written in the unit the value is written in)
+- `extrude_arrow_face_stops` (default true: dragging Extrude's distance arrow stops at flat faces parallel to the profile that lie over it, takes their exact distance and outlines them, #2398; false: the drag moves in round steps only, as before)
- `extrude_auto_to_object` (default true: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object, unless the Profiles box was clicked into; it applies to Extrude dialogs opened afterwards)
- `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it)
- `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence)