Selection: a freehand lasso that takes what is fully inside it (#4376) (#10185)

* claim: #4376

* Selection: a freehand lasso that takes what is wholly inside it (#4376)

The SELECT panel gets a Lasso checkbox (UiState::lasso_select, ui.set
lassoSelect). With it on, a primary drag from empty space draws a
freehand loop; the release selects through the same path as the window
box: items whose points are all inside the loop and no segment crosses
it, so a concave loop leaves out a curve that bulges out of it. Shift
and Ctrl add as with the box. ui.drag takes via waypoints (and scenario
drag steps take more than two points) so agents and tests can draw it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: thocsmith <193096300+thocsmith@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
thocsmith
2026-10-31 18:31:21 +00:00
committed by GitHub
parent ed66adac5c
commit 85197c1224
9 changed files with 193 additions and 18 deletions
+10
View File
@@ -0,0 +1,10 @@
{
"en": { "ui.lasso_select": "Lasso (drag a freehand loop: takes what is wholly inside)" },
"ar": { "ui.lasso_select": "الحبل (اسحب حلقة حرة: يحدّد ما يقع داخلها بالكامل)" },
"de": { "ui.lasso_select": "Lasso (freihändig umfahren: wählt, was ganz innen liegt)" },
"he": { "ui.lasso_select": "לאסו (גרירת לולאה חופשית: בוחר את מה שנמצא כולו בתוכה)" },
"ja": { "ui.lasso_select": "投げ縄(フリーハンドで囲む:完全に内側にあるものを選択)" },
"ko": { "ui.lasso_select": "올가미(자유롭게 둘러 그리기: 완전히 안쪽에 있는 것을 선택)" },
"vi": { "ui.lasso_select": "Lasso (kéo một vòng tự do: chọn những gì nằm hoàn toàn bên trong)" },
"zh": { "ui.lasso_select": "套索(徒手圈选:选择完全在圈内的对象)" }
}
+16 -2
View File
@@ -852,8 +852,22 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
app.synthetic.push(egui::Event::PointerMoved(a));
}
let steps = f("steps").unwrap_or(10.0).clamp(1.0, 200.0) as usize;
for k in 1..=steps {
app.synthetic.push(egui::Event::PointerMoved(a + (z - a) * (k as f32 / steps as f32)));
// `via`: [[x, y], ...] the pointer passes through on its way (a lasso's loop, #4376).
let via: Vec<egui::Pos2> = p
.get("via")
.and_then(Value::as_array)
.into_iter()
.flatten()
.take(500)
.filter_map(|q| Some(egui::pos2(q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32)))
.filter(|q| q.is_finite())
.collect();
let mut from = a;
for to in via.into_iter().chain([z]) {
for k in 1..=steps {
app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (k as f32 / steps as f32)));
}
from = to;
}
// `hold_end`: frames to keep the button down at the end (to look at a drag's snap).
for _ in 0..f("hold_end").unwrap_or(0.0).clamp(0.0, 600.0) as usize {
+4
View File
@@ -360,6 +360,9 @@ pub struct UiState {
pub pick_bodies: bool,
/// A face picks its exact component occurrence in Design and Render.
pub pick_components: bool,
/// The selection shape (#4376): a drag in the view draws a freehand lasso that takes what is
/// wholly inside it, instead of the window/crossing rectangle. Off by default.
pub lasso_select: bool,
/// 0: shaded with edges, 1: shaded, 2: wireframe, 3: shaded with hidden edges.
pub visual_style: u8,
/// A soft shadow on the ground under the model (seen from above).
@@ -405,6 +408,7 @@ impl Default for UiState {
pick_off: Vec::new(),
pick_bodies: false,
pick_components: false,
lasso_select: false,
visual_style: 0,
ground_shadow: true,
up_axis: Default::default(),
+20 -7
View File
@@ -8,7 +8,8 @@
//! text (with `near`: the one in that label's row)
//! - `{"click": AT, "double"?, "shift"?, "ctrl"?, "button"?}`, `{"move": AT, "shift"?, "alt"?, "ctrl"?, "cmd"?}`,
//! `{"hold": AT, "frames"?}` (press and hold still: Select Other),
//! `{"drag": [AT, AT], "shift"?, "ctrl"?, "steps"?}` where AT is `[x, y]` (screen), `{"world": [x,y,z]}`
//! `{"drag": [AT, AT, ...], "shift"?, "ctrl"?, "steps"?}` (through any points between, `steps` moves
//! each) where AT is `[x, y]` (screen), `{"world": [x,y,z]}`
//! or `{"sketch": [x,y]}` (the sketch being edited)
//! - `{"queued": "engine.execute", "params": {…}, "min_frames"?: n, "max_frames"?: n}`: a request sent the way an
//! agent's arrive (through the app's request queue, answered between frames, so the agent
@@ -449,6 +450,19 @@ impl Harness {
Err(format!("view_anim {v}: still animating after 240 frames"))
}
/// A drag step's first and last points, and the screen points it passes through between them
/// (a lasso's loop, #4376).
fn drag_points(&mut self, d: &Value) -> Result<([f64; 2], [f64; 2], Vec<Value>), String> {
let pts = d.as_array().map(Vec::as_slice).unwrap_or_default();
let start = self.at(pts.first().unwrap_or(&Value::Null))?;
let end = self.at(pts.get(pts.len().saturating_sub(1).max(1)).unwrap_or(&Value::Null))?;
let mut via = Vec::new();
for q in pts.iter().skip(1).take(pts.len().saturating_sub(2)) {
via.push(json!(self.at(q)?));
}
Ok((start, end, via))
}
/// Run one step.
pub fn step(&mut self, s: &Value) -> Result<(), String> {
let flag = |k: &str| s.get(k).and_then(Value::as_bool).unwrap_or(false);
@@ -504,13 +518,12 @@ impl Harness {
let [x, y] = self.at(at)?;
self.call("ui.move", json!({"x": x, "y": y,"shift":flag("shift"),"alt":flag("alt"),"ctrl":flag("ctrl"),"cmd":flag("cmd")}))
} else if let Some(d) = s.get("drag") {
let [x0, y0] = self.at(d.get(0).unwrap_or(&Value::Null))?;
let [x1, y1] = self.at(d.get(1).unwrap_or(&Value::Null))?;
let ([x0, y0], [x1, y1], via) = self.drag_points(d)?;
let steps = s.get("steps").cloned().unwrap_or(json!(8));
self.call(
"ui.drag",
json!({"x0": x0, "y0": y0, "x1": x1, "y1": y1, "steps": steps, "shift": flag("shift"), "ctrl": flag("ctrl"), "alt": flag("alt")}),
)
let mut p =
json!({"x0": x0, "y0": y0, "x1": x1, "y1": y1, "steps": steps, "shift": flag("shift"), "ctrl": flag("ctrl"), "alt": flag("alt")});
p["via"] = Value::Array(via);
self.call("ui.drag", p)
} else if let Some(m) = s.get("queued").and_then(Value::as_str) {
let (v, frames) = self.call_queued(m, s.get("params").cloned().unwrap_or(json!({})));
let min = s.get("min_frames").and_then(Value::as_u64).unwrap_or(0);
+81 -3
View File
@@ -257,16 +257,46 @@ pub fn ray_quad(o: Vec3, d: Vec3, q: &[Vec3; 4]) -> Option<f64> {
}
/// A rectangle dragged in the viewport selects by window (dragged left to right: items fully
/// inside) or by crossing (right to left: items touching it).
#[derive(Clone, Copy, Debug, PartialEq)]
/// inside) or by crossing (right to left: items touching it). A freehand lasso (#4376, the
/// selection shape `UiState::lasso_select`) selects by window whichever way it is drawn.
#[derive(Clone, Debug, PartialEq)]
pub struct BoxSel {
/// The rectangle, or the bounds of the lasso.
pub rect: Rect,
pub crossing: bool,
/// The lasso's points in drawing order, closed back to the first; empty for a rectangle.
pub lasso: Vec<Pos2>,
}
/// Lasso points closer together than this (screen points) add nothing to its shape.
const LASSO_STEP: f32 = 2.0;
impl BoxSel {
pub fn from_drag(start: Pos2, end: Pos2) -> BoxSel {
BoxSel { rect: Rect::from_two_pos(start, end), crossing: end.x < start.x }
BoxSel { rect: Rect::from_two_pos(start, end), crossing: end.x < start.x, lasso: Vec::new() }
}
/// A lasso through these screen points (non-finite ones are left out).
pub fn lasso(points: &[Pos2]) -> BoxSel {
let mut sel = BoxSel { rect: Rect::NOTHING, crossing: false, lasso: Vec::new() };
for p in points {
sel.extend(*p);
}
sel
}
/// Is this a lasso rather than a rectangle?
pub fn is_lasso(&self) -> bool {
!self.lasso.is_empty()
}
/// The lasso drawn on to `p` (a point too close to the last one adds nothing).
pub fn extend(&mut self, p: Pos2) {
if !p.is_finite() || self.lasso.last().is_some_and(|q| q.distance(p) < LASSO_STEP) {
return;
}
self.lasso.push(p);
self.rect = if self.lasso.len() == 1 { Rect::from_min_max(p, p) } else { self.rect.union(Rect::from_min_max(p, p)) };
}
/// Does the polyline (screen points) count as selected?
@@ -274,11 +304,36 @@ impl BoxSel {
if pts.is_empty() {
return false;
}
if self.is_lasso() {
return self.lasso_takes(pts);
}
if !self.crossing {
return pts.iter().all(|p| self.rect.contains(*p));
}
pts.iter().any(|p| self.rect.contains(*p)) || pts.windows(2).any(|w| segment_hits_rect(w[0], w[1], self.rect))
}
/// Every point inside the closed lasso, and no segment crossing its outline (a concave lasso
/// can hold both ends of a segment that leaves it in between).
fn lasso_takes(&self, pts: &[Pos2]) -> bool {
let n = self.lasso.len();
if n < 3 || !pts.iter().all(|p| self.rect.contains(*p) && inside_polygon(*p, &self.lasso)) {
return false;
}
let edges: Vec<(Pos2, Pos2)> = self.lasso.iter().copied().zip(self.lasso.iter().copied().cycle().skip(1)).collect();
!pts.windows(2).any(|w| edges.iter().any(|&(r, s)| segments_cross(w[0], w[1], r, s)))
}
}
/// Is `p` inside the closed polygon (even-odd rule)?
pub fn inside_polygon(p: Pos2, polygon: &[Pos2]) -> bool {
let mut inside = false;
for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)) {
if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x {
inside = !inside;
}
}
inside
}
/// Does the segment a–b cross the rectangle's boundary or lie inside it?
@@ -349,6 +404,29 @@ mod tests {
assert!(c.takes(&inside) && c.takes(&partly) && c.takes(&through) && !c.takes(&away));
}
/// #4376: a freehand lasso takes what is wholly inside it, whichever way it was drawn. An L
/// shaped loop leaves out what sits in its notch, and a segment whose ends are both inside but
/// which cuts across the notch.
#[test]
fn a_lasso_takes_only_what_is_wholly_inside_it() {
let l = [pos2(0.0, 0.0), pos2(100.0, 0.0), pos2(100.0, 40.0), pos2(40.0, 40.0), pos2(40.0, 100.0), pos2(0.0, 100.0)];
for path in [l.to_vec(), l.iter().rev().copied().collect::<Vec<_>>()] {
let lasso = BoxSel::lasso(&path);
assert!(!lasso.crossing, "a lasso selects by window");
assert!(lasso.takes(&[pos2(10.0, 10.0), pos2(90.0, 20.0)]), "inside the bottom arm");
assert!(lasso.takes(&[pos2(10.0, 50.0), pos2(30.0, 90.0)]), "inside the left arm");
assert!(!lasso.takes(&[pos2(60.0, 60.0), pos2(90.0, 90.0)]), "in the notch");
assert!(!lasso.takes(&[pos2(20.0, 90.0), pos2(90.0, 20.0)]), "both ends inside, across the notch");
assert!(!lasso.takes(&[pos2(10.0, 10.0), pos2(120.0, 10.0)]), "partly outside");
assert!(!lasso.takes(&[]), "nothing");
assert_eq!(lasso.rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)), "the loop's bounds");
}
// Fewer than three points enclose nothing; hostile coordinates never panic.
assert!(!BoxSel::lasso(&[pos2(0.0, 0.0), pos2(10.0, 10.0)]).takes(&[pos2(5.0, 5.0)]));
let nan = BoxSel::lasso(&[pos2(f32::NAN, 0.0), pos2(10.0, f32::INFINITY), pos2(0.0, 10.0)]);
assert!(!nan.takes(&[pos2(1.0, 1.0)]));
}
#[test]
fn inputs_toggle_and_filter() {
let mut inp = SelInput::new("Edges", EDGES, true);
+3
View File
@@ -2911,6 +2911,9 @@ pub(crate) fn selection_filter(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
}
// The selection shape (#4376): a drag draws a freehand lasso instead of the rectangle.
let label = app.tr("ui.lasso_select").to_string();
ui_kit::checkbox(ui, &label, &mut app.ui.lasso_select);
}
/// Two Esc presses within this many seconds finish the open sketch.
+56 -3
View File
@@ -4946,7 +4946,12 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
&& !crate::shell::covered(app, a)
&& !axes.contains(a)
{
app.viewport.boxsel = Some(BoxSel::from_drag(a, b));
// The lasso (#4376) follows the pointer from the press; the rectangle spans it.
match &mut app.viewport.boxsel {
Some(lasso) if app.ui.lasso_select && lasso.is_lasso() => lasso.extend(b),
_ if app.ui.lasso_select => app.viewport.boxsel = Some(BoxSel::lasso(&[a, b])),
_ => app.viewport.boxsel = Some(BoxSel::from_drag(a, b)),
}
}
// A shell card disables its underlying widgets. The release still ends a
// rubber band even when egui no longer sends drag_stopped to the viewport.
@@ -4998,7 +5003,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
Tokens::view().warning,
);
}
if let Some(bx) = app.viewport.boxsel {
if let Some(bx) = &app.viewport.boxsel {
paint_box_selection(&painter, bx, app.session.active_sketch.is_some());
}
if let Some(tl) = app.tool.as_ref() {
@@ -5046,7 +5051,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
crate::tool_cursor::show(app, &painter, badge_at);
}
fn paint_box_selection(painter: &egui::Painter, bx: BoxSel, sketch: bool) {
fn paint_box_selection(painter: &egui::Painter, bx: &BoxSel, sketch: bool) {
let t = Tokens::get();
let col = if sketch {
t.sketch_accent
@@ -5055,6 +5060,11 @@ fn paint_box_selection(painter: &egui::Painter, bx: BoxSel, sketch: bool) {
} else {
t.box_window
};
// The lasso is drawn as its closed outline: a fill of a concave loop would need tessellating.
if bx.is_lasso() {
painter.add(Shape::closed_line(bx.lasso.clone(), Stroke::new(1.2, col)));
return;
}
painter.rect_filled(bx.rect, 0.0, col.gamma_multiply(0.12));
if bx.crossing {
let c = [bx.rect.left_top(), bx.rect.right_top(), bx.rect.right_bottom(), bx.rect.left_bottom()];
@@ -11558,6 +11568,49 @@ mod tests {
let items = h.app.dialog.as_ref().unwrap().inputs[0].items.clone();
assert!(!items.iter().any(|s| matches!(s, Sel::Profile { .. })), "a mask that asks for edges takes no region: {items:?}");
}
/// #4376: with the Lasso selection shape, a drag in a sketch draws a freehand loop and takes
/// the curves wholly inside it. An L shaped loop leaves out a line in its notch and a line
/// that cuts across the notch, which no rectangle could; Shift adds to the selection.
#[test]
fn a_lasso_in_a_sketch_takes_the_curves_wholly_inside_it() {
let mut h = crate::scenario::Harness::new();
h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();
let line = |h: &mut crate::scenario::Harness, a: [f64; 2], b: [f64; 2]| {
let made = h.app.run("sketch.line", json!({"points": [a, b]})).unwrap();
made["created"]["curves"][0].as_str().unwrap().to_string()
};
let bottom = line(&mut h, [25.0, 25.0], [75.0, 25.0]);
let left = line(&mut h, [25.0, 35.0], [25.0, 75.0]);
let notch = line(&mut h, [60.0, 60.0], [75.0, 75.0]);
let across = line(&mut h, [30.0, 75.0], [75.0, 30.0]);
let far = line(&mut h, [120.0, 25.0], [120.0, 75.0]);
h.call("ui.view", json!({"view": "top"}));
h.call("ui.view", json!({"view": "fit"}));
let r = h.call("ui.set", json!({"lassoSelect": true}));
assert_eq!(r["ok"], true, "{r}");
let loop_at = |pts: &[[f64; 2]]| pts.iter().map(|p| json!({"world": [p[0], p[1], 0.0]})).collect::<Vec<_>>();
let curves = |h: &crate::scenario::Harness| {
h.app
.session
.selection
.iter()
.filter_map(|s| if let Sel::SketchCurve { id, .. } = s { Some(id.clone()) } else { None })
.collect::<Vec<_>>()
};
let l = [[15.0, 15.0], [85.0, 15.0], [85.0, 45.0], [45.0, 45.0], [45.0, 85.0], [15.0, 85.0], [15.0, 20.0]];
h.step(&json!({"drag": loop_at(&l), "steps": 6})).unwrap();
assert!(h.app.viewport.boxsel.is_none(), "the release ends the lasso");
assert_eq!(curves(&h), vec![bottom.clone(), left.clone()], "not {notch}, {across} or {far}");
// Shift adds the far line with a second loop; drawn the other way round, it is the same.
let around_far = [[110.0, 15.0], [110.0, 85.0], [130.0, 85.0], [130.0, 15.0], [112.0, 15.0]];
h.step(&json!({"drag": loop_at(&around_far), "steps": 6, "shift": true})).unwrap();
assert_eq!(curves(&h), vec![bottom, left, far]);
// Back to the rectangle: a plain drag is a box again.
h.call("ui.set", json!({"lassoSelect": false}));
h.step(&json!({"drag": loop_at(&[[15.0, 15.0], [85.0, 85.0]])})).unwrap();
assert_eq!(curves(&h).len(), 4, "the window box takes all four lines inside it: {:?}", curves(&h));
}
}
#[cfg(test)]
@@ -869,8 +869,8 @@ fn sketch_previews_selection_band_and_number_focus_follow_sketch_accent() {
assert!(output.shapes.iter().any(|s| sketch_stroke(&s.shape, t.sketch_accent)));
for sketch in [false, true] {
for crossing in [false, true] {
let bx = BoxSel { rect: Rect::from_min_size(pos2(20.0, 20.0), vec2(100.0, 80.0)), crossing };
let output = draw(&h.ctx, |ui| paint_box_selection(ui.painter(), bx, sketch));
let bx = BoxSel { rect: Rect::from_min_size(pos2(20.0, 20.0), vec2(100.0, 80.0)), crossing, lasso: Vec::new() };
let output = draw(&h.ctx, |ui| paint_box_selection(ui.painter(), &bx, sketch));
let color = if sketch {
t.sketch_accent
} else if crossing {
+1 -1
View File
@@ -370,7 +370,7 @@ no box selection.
| `ui.start` | `command`, `params?` | like a toolbar click: starts the sketch tool or dialog for the command. `params` sets what the dialog opens on, and nothing runs until OK: `joint.drive` takes `joint` (id or name; without it, the joint picked in the browser, else the first joint that moves; a rigid joint opens to say why it has nothing to drive, with an Edit Joint button, handle `drive:edit_joint`) and `values` (numbers in degrees or millimetres, or expressions); `motion.study` takes `study` (id or name), which opens that study to edit and chart. A command that takes no params is refused before it starts; a param the dialog doesn't take is refused and the dialog closes |
| `ui.click` | `x`, `y` (screen points), `button?`: left/right/middle, `shift?`, `ctrl?`, `double?` | real pointer input |
| `ui.move` | `x`, `y`, `shift?`, `alt?`, `ctrl?`, `cmd?` | pointer movement without a button; modifiers apply until the next synthetic move/click; a move with omitted modifiers releases them. With `nav: "touchpad"`, Shift pans and Alt/Option orbits. |
| `ui.drag` | `x0`, `y0`, `x1`, `y1`, `button?`, `shift?`, `ctrl?`, `steps?`, `hold?`, `hold_end?` | press, move, release; a left drag on the model is a box selection (left to right: window, right to left: crossing); with OpenSCAD navigation, plain left-drag on empty space orbits, Shift+left-drag box-selects, and drags starting on sketch geometry edit it; `hold` keeps the button down that many frames first (a right press-and-hold opens the marking menu, releasing over a direction picks it), `hold_end` that many frames at the end (a sketch drag shows its snap) |
| `ui.drag` | `x0`, `y0`, `x1`, `y1`, `via?`, `button?`, `shift?`, `ctrl?`, `steps?`, `hold?`, `hold_end?` | press, move, release; `via` is a list of `[x, y]` points passed through on the way (`steps` moves to each); a left drag on the model is a box selection (left to right: window, right to left: crossing), or with `lassoSelect` on (`ui.set`, the SELECT panel's Lasso) a freehand lasso that takes what is wholly inside it; with OpenSCAD navigation, plain left-drag on empty space orbits, Shift+left-drag box-selects, and drags starting on sketch geometry edit it; `hold` keeps the button down that many frames first (a right press-and-hold opens the marking menu, releasing over a direction picks it), `hold_end` that many frames at the end (a sketch drag shows its snap) |
| `ui.menu` | `x?`, `y?`, `target?`, `close?` | with a point: open a context menu there as a right-click would (the viewport's marking menu, or a browser menu with `target: {"type": "body", "name"} \| {"type": "sketch", "id"} \| {"type": "component", "id"}`); without: the open menu (`radial` and `items`: id, label, shortcut, enabled, icon, placeholder; blank icons on headings/separators have `placeholder: false`) |
| `ui.icon_audit` | `reset?`, `stop?` | `reset: true` enables collection on the UI thread and clears previous requests; returns `{requested: [{name, master, placeholder}]}` sorted by requested id. Each read drains names collected since the previous read/reset. Collection stays enabled until `stop: true` (which returns pending names before disabling it). Includes aliases, variable/table ids and cached paints. |
| `ui.menuPick` | `item`: id or label | runs an item of the open menu, as clicking it does |