Skip to main content

brep_render/engine_state/
sketch_input.rs

1use super::*;
2use super::sketch_panel::{sketch_constraint_signature, sketch_perpendicular_should_swap};
3
4// Sketch picking maps camera rays to plane-space coordinates. Hit tests prefer
5// points over geometry within the grab radius. Mutators refresh the live overlay
6// and mark the engine dirty; calls outside sketch mode are no-ops.
7impl EngineState {
8    /// Re-push the sketch overlay reflecting the live hover + selection. Reads the
9    /// active `sketch_edit`'s session; a no-op when not in sketch mode. Called at
10    /// the end of every S2 mutator (the reusable counterpart of the initial
11    /// [`set_sketch_overlay`](Self::set_sketch_overlay) push).
12    pub(super) fn refresh_sketch_overlay(&mut self) {
13        let world_per_pixel = self.camera.world_per_pixel();
14        let (json, preview, leaders, glyphs, arrows) = match self.sketch_edit.as_ref() {
15            Some(edit) => (
16                edit.session.overlay_json_with_state(world_per_pixel),
17                edit.session.preview_overlay_json(
18                    world_per_pixel,
19                    &edit.pending,
20                    edit.hover_uv,
21                    &edit.handdraw_stroke,
22                ),
23                edit.session.dim_leaders_overlay_json_with_state(world_per_pixel),
24                edit.session
25                    .constraint_glyphs_overlay_json_with_state(world_per_pixel),
26                edit.session.freedom_arrows_overlay_json(world_per_pixel),
27            ),
28            None => return,
29        };
30        let _ = self.set_overlay_json(&json);
31        // The draw-tool rubber-band rides in its own `sketch-preview` group so it
32        // upserts/clears independently of the solved geometry + point groups.
33        let _ = self.set_overlay_json(&preview);
34        // The dimension leaders + arrows ride in `sketch-dim-leaders`, refreshed
35        // alongside everything else (S5).
36        let _ = self.set_overlay_json(&leaders);
37        // The geometric-constraint glyphs ride in `sketch-constraint-glyphs` (S6c).
38        let _ = self.set_overlay_json(&glyphs);
39        // The hovered entity's free directions ride in `sketch-dof-arrows`.
40        let _ = self.set_overlay_json(&arrows);
41        // Remember the zoom these groups were baked at: their construction dashes,
42        // dimension arrowheads and constraint glyphs are all screen-constant, so
43        // `ensure_sketch_overlay_current` re-bakes them when it moves.
44        self.sketch_overlay_wpp = if world_per_pixel > 0.0 {
45            world_per_pixel
46        } else {
47            f64::MIN_POSITIVE
48        };
49    }
50
51    /// Per-frame upkeep for the live SKETCH overlay (driven by
52    /// [`Self::ensure_overlays_current`]) — the sketch-mode sibling of
53    /// [`Self::ensure_feature_dimension_overlay_current`]. The dimension leaders
54    /// (draggable), constraint glyphs and construction dashes are sized in PIXELS
55    /// against the camera at bake time, so a zoom leaves them stale until
56    /// something else mutates the sketch. Re-bakes on a material
57    /// `world_per_pixel` change only, so a quiet frame stays quiet.
58    pub(super) fn ensure_sketch_overlay_current(&mut self) {
59        if !self.sketch_mode() {
60            self.sketch_overlay_wpp = 0.0;
61            return;
62        }
63        let wpp = self.camera.world_per_pixel();
64        if super::overlay_wpp_stale(self.sketch_overlay_wpp, wpp) {
65            self.refresh_sketch_overlay();
66        }
67    }
68
69    /// Map CSS-pixel `(x, y)` to the active sketch plane's `(u, v)` via the camera
70    /// pick ray ∩ the sketch plane. `None` when not in sketch mode or the ray misses
71    /// the plane (parallel / behind).
72    pub fn sketch_uv_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
73        let edit = self.sketch_edit.as_ref()?;
74        let ray = self.camera.pick_ray(x, y);
75        crate::sketch::ray_plane_uv(&edit.session.plane, ray.origin, ray.dir)
76    }
77
78    /// The world-space pick tolerance at the current zoom — the ONE radius that
79    /// drives hover-highlight, click-select, drag-grab, draw-snap AND trim, for
80    /// points AND geometry, so "what highlights" is exactly "what you can grab".
81    /// Sized at 1.5× the visualized point (`POINT_SIZE_PX`) for forgiving clicking.
82    pub(super) fn sketch_pick_radius(&self) -> f64 {
83        f64::from(crate::sketch::tessellate::POINT_SIZE_PX) * 1.5 * self.camera.world_per_pixel()
84    }
85
86    /// The entity ref under CSS-pixel `(x, y)` within the grab radius, or `None`.
87    /// Priority is points > geometry > constraint: [`pick_entity`] resolves the first
88    /// two, and only when neither is in range do we consult [`pick_constraint`] (a glyph
89    /// or dimension leader that overlaps a point/edge never shadows it).
90    ///
91    /// [`pick_entity`]: crate::sketch::SketchSession::pick_entity
92    /// [`pick_constraint`]: crate::sketch::SketchSession::pick_constraint
93    fn sketch_entity_at(&self, x: f64, y: f64) -> Option<serde_json::Value> {
94        let (u, v) = self.sketch_uv_at(x, y)?;
95        let radius = self.sketch_pick_radius();
96        let wpp = self.camera.world_per_pixel();
97        self.sketch_edit.as_ref().and_then(|edit| {
98            edit.session
99                .pick_entity(u, v, radius)
100                .or_else(|| edit.session.pick_constraint(u, v, radius, wpp))
101        })
102    }
103
104    /// Set (or clear) the sketch hover, re-pushing the overlay + marking dirty only
105    /// when it actually changed. Returns whether the hover changed.
106    pub(super) fn set_sketch_hover(&mut self, new_hover: Option<serde_json::Value>) -> bool {
107        let changed = match self.sketch_edit.as_ref() {
108            Some(edit) => {
109                !crate::sketch::entity_ref_eq(edit.session.selection.hovered.as_ref(), new_hover.as_ref())
110            }
111            None => false,
112        };
113        if changed {
114            if let Some(edit) = self.sketch_edit.as_mut() {
115                edit.session.set_hover(new_hover);
116            }
117            self.refresh_sketch_overlay();
118            self.dirty = true;
119        }
120        changed
121    }
122
123    /// Update the sketch hover to the entity under CSS-pixel `(x, y)` (S2). Returns
124    /// whether the hover changed. A no-op returning `false` when not in sketch mode.
125    pub fn sketch_hover_at(&mut self, x: f64, y: f64) -> bool {
126        if self.sketch_edit.is_none() {
127            return false;
128        }
129        // Track the live cursor uv for the S3a rubber-band. In DRAW mode with pending
130        // clicks the preview follows the cursor even when the hovered ENTITY is
131        // unchanged, so force an overlay refresh there.
132        let uv = self.sketch_uv_at(x, y);
133        let preview_live = match self.sketch_edit.as_mut() {
134            Some(edit) => {
135                edit.hover_uv = uv;
136                edit.session.tool.is_some() && !edit.pending.is_empty()
137            }
138            None => false,
139        };
140        let new_hover = self.sketch_entity_at(x, y);
141        let changed = self.set_sketch_hover(new_hover);
142        if preview_live && !changed {
143            self.refresh_sketch_overlay();
144            self.dirty = true;
145        }
146        changed
147    }
148
149    /// Clear the sketch hover (pointer left the viewport / moved over the ViewCube).
150    /// Returns whether a hover was cleared.
151    pub fn sketch_clear_hover(&mut self) -> bool {
152        self.set_sketch_hover(None)
153    }
154
155    /// Click-select in sketch mode: pick the entity under `(x, y)`; nothing → clear
156    /// the selection. Otherwise honor the SAME "Multi-select" setting the 3D viewport
157    /// reads (`settings.multi_select`): under `ClickToggles` a plain click toggles the
158    /// hit in the set (no modifier needed for a multi-selection); under
159    /// `CtrlClick` a plain click replaces the set with just the hit and `additive`
160    /// (Ctrl/Cmd) toggles. Re-pushes the overlay + marks dirty.
161    pub fn sketch_click_at(&mut self, x: f64, y: f64, additive: bool) {
162        // Read the setting before the mutable `sketch_edit` borrow.
163        let toggles = self.settings.multi_select == crate::style::MultiSelectMode::ClickToggles;
164        let hit = self.sketch_entity_at(x, y);
165        let Some(edit) = self.sketch_edit.as_mut() else {
166            return;
167        };
168        match hit {
169            None => edit.session.clear_selection(),
170            Some(entity_ref) => {
171                if additive || toggles {
172                    edit.session.toggle_selection(entity_ref);
173                } else {
174                    edit.session.clear_selection();
175                    edit.session.toggle_selection(entity_ref);
176                }
177            }
178        }
179        self.refresh_sketch_overlay();
180        self.dirty = true;
181    }
182
183    /// Begin a point drag if a DRAGGABLE point is under `(x, y)` (S2): remember it
184    /// (id + original `fixed` flag). Returns `true` iff a point was grabbed (the
185    /// viewport routes the drag to the sketch; otherwise it orbits the camera). A
186    /// locked / fully-constrained point is not draggable, so an empty-space or
187    /// locked-point drag falls through to a camera orbit.
188    pub fn sketch_drag_begin(&mut self, x: f64, y: f64) -> bool {
189        let Some((u, v)) = self.sketch_uv_at(x, y) else {
190            return false;
191        };
192        let radius = self.sketch_pick_radius();
193        // Grab EXACTLY what's HIGHLIGHTED: the hovered entity was picked at the exact
194        // cursor position on the last move, so it is immune to egui reporting the
195        // drag-start ~6px into the gesture (the "highlighted but won't grab"
196        // intermittency — and it's what lets a whole geometry drag). A hovered LOCKED
197        // point yields `None` → the drag falls through to a camera gesture; it must
198        // NOT positional-fall-back there (that would grab a nearby UNhighlighted
199        // point). Only an EMPTY hover (a press with no prior move) falls back to a
200        // fresh positional pick.
201        let points = self.sketch_edit.as_ref().and_then(|edit| {
202            match edit.session.selection.hovered.as_ref() {
203                Some(entity_ref) => edit.session.drag_points_from_ref(entity_ref),
204                None => edit
205                    .session
206                    .pick_draggable_point(u, v, radius)
207                    .and_then(|(id, fixed)| {
208                        edit.session
209                            .doc
210                            .point(&id)
211                            .map(|p| vec![(id, p.x, p.y, fixed)])
212                    }),
213            }
214        });
215        let Some(points) = points else {
216            return self.sketch_glyph_drag_begin(u, v);
217        };
218        if let Some(edit) = self.sketch_edit.as_mut() {
219            // Snapshot ONCE at the gesture start so the whole drag is one undo step
220            // (S6a); `sketch_drag_to` never snapshots. A grab that moves nothing is
221            // discarded in `sketch_drag_end`.
222            edit.record_undo();
223            let infer_on_drop = edit.session.selection.hovered.as_ref()
224                .and_then(|entity| entity.get("kind"))
225                .and_then(serde_json::Value::as_str) != Some("geometry");
226            edit.drag = Some(SketchDrag { points, anchor: (u, v), infer_on_drop, glyph: None });
227        }
228        true
229    }
230
231    /// Drag the grabbed target to `(x, y)` (S2): pin every grabbed point at its
232    /// ORIGINAL position plus the cursor delta (`fixed = true`) so the solver anchors
233    /// the whole shape there, re-solve, then restore each point's ORIGINAL `fixed`
234    /// flag. Absolute-from-anchor (never incremental), so a rigid geometry translate
235    /// tracks the cursor 1:1 without drifting as the solver nudges points between
236    /// frames. A resolve error rolls every grabbed point back to its pre-drag coords
237    /// (the last good state). No-op when nothing is grabbed / not in sketch mode / the
238    /// ray misses the plane.
239    pub fn sketch_drag_to(&mut self, x: f64, y: f64) {
240        let Some((u, v)) = self.sketch_uv_at(x, y) else {
241            return;
242        };
243        let Some(edit) = self.sketch_edit.as_mut() else {
244            return;
245        };
246        let Some(drag) = edit.drag.clone() else {
247            return;
248        };
249        let (du, dv) = (u - drag.anchor.0, v - drag.anchor.1);
250        if let Some((cid, shift)) = &drag.glyph {
251            use crate::sketch::constraint_glyphs::{glyph_shift_entry, GlyphShift};
252            let moved = match *shift {
253                GlyphShift::Normal { normal, n } => {
254                    GlyphShift::Normal { normal, n: n + du * normal[0] + dv * normal[1] }
255                }
256                GlyphShift::Free { offset } => GlyphShift::Free { offset: [offset[0] + du, offset[1] + dv] },
257            };
258            edit.session
259                .dim_offsets
260                .insert(crate::sketch::doc::id_key(cid), glyph_shift_entry(moved));
261            self.refresh_sketch_overlay();
262            self.dirty = true;
263            return;
264        }
265        let session = &mut edit.session;
266        let before = session.doc.clone();
267        for (id, ox, oy, _) in &drag.points {
268            if let Some(p) = session.doc.point_mut(id) {
269                p.x = *ox + du;
270                p.y = *oy + dv;
271                p.fixed = true;
272            }
273        }
274        match session.resolve_drag() {
275            Ok(()) => {
276                for (id, _, _, orig_fixed) in &drag.points {
277                    if let Some(p) = session.doc.point_mut(id) {
278                        p.fixed = *orig_fixed;
279                    }
280                }
281            }
282            Err(_) => {
283                // Unsolvable target: roll every grabbed point back to its pre-drag
284                // coords + flag (keep the last good state).
285                for (id, ox, oy, orig_fixed) in &drag.points {
286                    if let Some(p) = session.doc.point_mut(id) {
287                        p.x = *ox;
288                        p.y = *oy;
289                        p.fixed = *orig_fixed;
290                    }
291                }
292            }
293        }
294        // A drag can collapse a free radius without producing a solver error.
295        // Preserve the last valid geometry, while tolerating pre-existing broken
296        // circles in imported documents so they can still be edited/repaired.
297        if newly_collapsed_radial_geometry(&before, &session.doc) {
298            session.doc = before;
299            let _ = session.resolve();
300        }
301        self.refresh_sketch_overlay();
302        self.dirty = true;
303    }
304
305    /// End a point drag (S2): clear the grab, then one final re-solve + overlay
306    /// refresh. No-op when no drag is live.
307    pub fn sketch_drag_end(&mut self) {
308        let had_grab = self
309            .sketch_edit
310            .as_ref()
311            .map_or(false, |edit| edit.drag.is_some());
312        if !had_grab {
313            return;
314        }
315        // A glyph drag moved only its stand-off: no solve, no inference. Discard the
316        // snapshot of a grab that moved nothing.
317        if let Some(edit) = self.sketch_edit.as_mut() {
318            if edit.drag.as_ref().map_or(false, |d| d.glyph.is_some()) {
319                edit.drag = None;
320                if edit.undo_stack.last().map_or(false, |snap| {
321                    snap.doc == edit.session.doc && snap.dim_offsets == edit.session.dim_offsets
322                }) {
323                    edit.undo_stack.pop();
324                }
325                self.refresh_sketch_overlay();
326                self.dirty = true;
327                return;
328            }
329        }
330        // Drop radius for constraint inference == the point grab radius (12 px in
331        // world units) — read before the `&mut` borrow of `sketch_edit`.
332        let drop_tol = self.sketch_pick_radius();
333        if let Some(edit) = self.sketch_edit.as_mut() {
334            let before = edit.session.doc.clone();
335            // Drop-time inference (S6c): a SINGLE-point drop snaps to a coincident
336            // point / point-on-line at the release position, mirroring the previous
337            // coincident-on-drop / point-on-line-on-drop inference. A whole-
338            // geometry drag never infers, even with only one movable endpoint:
339            // inference could glue or collapse the curve in one solve.
340            let dragged_single = edit.drag.as_ref().and_then(|drag| {
341                (drag.infer_on_drop && drag.points.len() == 1).then(|| drag.points[0].0.clone())
342            });
343            edit.drag = None;
344            if let Some(point_id) = dragged_single {
345                crate::sketch::infer::infer_drop_constraint(
346                    &mut edit.session.doc,
347                    &point_id,
348                    drop_tol,
349                );
350            }
351            let _ = edit.session.resolve();
352            if newly_collapsed_radial_geometry(&before, &edit.session.doc) {
353                edit.session.doc = before;
354                let _ = edit.session.resolve();
355            }
356            // Discard the drag's undo snapshot when the doc is unchanged (a mere
357            // grab-and-release, no move and no inferred constraint), so it neither
358            // pollutes undo nor clobbers redo. An inferred constraint changes the
359            // doc, so the snapshot is kept — one Ctrl+Z then undoes move+constraint.
360            if edit
361                .undo_stack
362                .last()
363                .map_or(false, |snap| snap.doc == edit.session.doc)
364            {
365                edit.undo_stack.pop();
366            }
367        }
368        self.refresh_sketch_overlay();
369        self.dirty = true;
370    }
371
372    /// Begin a constraint GLYPH drag when the hovered entity is a geometric
373    /// constraint's glyph: the press at plane `(u, v)` grabs the glyph's stand-off,
374    /// which [`sketch_drag_to`](Self::sketch_drag_to) moves with the cursor (along the
375    /// line normal for a line glyph) and stores per constraint in `dimOffsets`, so it
376    /// saves and undoes with the sketch. Returns whether a glyph was grabbed.
377    fn sketch_glyph_drag_begin(&mut self, u: f64, v: f64) -> bool {
378        let wpp = self.camera.world_per_pixel();
379        let Some(edit) = self.sketch_edit.as_mut() else {
380            return false;
381        };
382        let Some(hovered) = edit.session.selection.hovered.clone() else {
383            return false;
384        };
385        if hovered.get("kind").and_then(serde_json::Value::as_str) != Some("constraint") {
386            return false;
387        }
388        let Some(cid) = hovered.get("id").cloned() else {
389            return false;
390        };
391        let key = crate::sketch::doc::id_key(&cid);
392        let shift = edit
393            .session
394            .doc
395            .constraints
396            .iter()
397            .find(|c| c.raw.get("id").map(crate::sketch::doc::id_key).as_deref() == Some(key.as_str()))
398            .and_then(|c| {
399                crate::sketch::constraint_glyphs::constraint_glyph_shift(
400                    c,
401                    &edit.session.doc,
402                    &edit.session.dim_offsets,
403                    wpp,
404                )
405            });
406        let Some(shift) = shift else {
407            return false;
408        };
409        edit.record_undo();
410        edit.drag = Some(SketchDrag {
411            points: Vec::new(),
412            anchor: (u, v),
413            infer_on_drop: false,
414            glyph: Some((cid, shift)),
415        });
416        true
417    }
418
419    /// The hovered point's or geometry's remaining freedoms, for the hover readout
420    /// (`"2 DOF free"`, `"Fully constrained"`), or `None` when nothing such is
421    /// hovered.
422    pub fn sketch_hover_freedom_label(&self) -> Option<String> {
423        let edit = self.sketch_edit.as_ref()?;
424        let hovered = edit.session.selection.hovered.as_ref()?;
425        crate::sketch::freedom::freedom_label(&edit.session.doc, &edit.session.diagnostics, hovered)
426    }
427
428    /// The geometric-constraint glyphs as drawn, for the verifier: per glyph its
429    /// constraint id, its centre in CSS pixels, its size (box diagonal) in pixels,
430    /// and its saved stand-off (`dimOffsets` entry, `null` when at its default place).
431    /// `[]` outside sketch mode.
432    pub fn sketch_glyphs_json(&self) -> String {
433        let Some(edit) = self.sketch_edit.as_ref() else {
434            return "[]".to_string();
435        };
436        let wpp = self.camera.world_per_pixel();
437        let session = &edit.session;
438        let glyphs: Vec<serde_json::Value> = crate::sketch::constraint_glyphs::glyph_layout_segments(
439            &session.doc,
440            &session.dim_offsets,
441            wpp,
442        )
443        .into_iter()
444        .filter_map(|(index, segments)| {
445            let c = &session.doc.constraints[index];
446            let id = c.raw.get("id")?.clone();
447            let mut lo = [f64::INFINITY; 2];
448            let mut hi = [f64::NEG_INFINITY; 2];
449            for (a, b) in &segments {
450                for p in [a, b] {
451                    let w = session.plane.to_world(p[0], p[1]);
452                    let (x, y, _) = self.camera.project(w);
453                    lo = [lo[0].min(x), lo[1].min(y)];
454                    hi = [hi[0].max(x), hi[1].max(y)];
455                }
456            }
457            let key = crate::sketch::doc::id_key(&id);
458            Some(serde_json::json!({
459                "id": id,
460                "type": c.ctype(),
461                "center": [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0],
462                "sizePx": (hi[0] - lo[0]).hypot(hi[1] - lo[1]),
463                "offset": session.dim_offsets.get(&key).cloned(),
464            }))
465        })
466        .collect();
467        serde_json::Value::Array(glyphs).to_string()
468    }
469
470    /// [`sketch_reset_glyph_offset`](Self::sketch_reset_glyph_offset) for the
471    /// constraint glyph under CSS-pixel `(x, y)`, if any.
472    pub fn sketch_reset_glyph_offset_at(&mut self, x: f64, y: f64) -> bool {
473        let hit = self.sketch_entity_at(x, y);
474        match hit {
475            Some(entity) if entity.get("kind").and_then(serde_json::Value::as_str) == Some("constraint") => {
476                let id = entity.get("id").cloned().unwrap_or(serde_json::Value::Null);
477                self.sketch_reset_glyph_offset(&id)
478            }
479            _ => false,
480        }
481    }
482
483    /// Put a constraint's glyph back at its default place (double-click on the glyph):
484    /// drop its saved stand-off. One undo step; returns whether anything changed.
485    pub fn sketch_reset_glyph_offset(&mut self, constraint_id: &serde_json::Value) -> bool {
486        let key = crate::sketch::doc::id_key(constraint_id);
487        let Some(edit) = self.sketch_edit.as_mut() else {
488            return false;
489        };
490        let is_glyph = edit
491            .session
492            .doc
493            .constraints
494            .iter()
495            .find(|c| c.raw.get("id").map(crate::sketch::doc::id_key).as_deref() == Some(key.as_str()))
496            .map_or(false, |c| !matches!(c.ctype(), Some("⟺") | Some("↥") | Some("∠")) && !c.temporary());
497        if !is_glyph || !edit.session.dim_offsets.contains_key(&key) {
498            return false;
499        }
500        edit.record_undo();
501        edit.session.dim_offsets.remove(&key);
502        self.refresh_sketch_overlay();
503        self.dirty = true;
504        true
505    }
506
507    /// The number of selected sketch entities (0 when not in sketch mode) — the mode
508    /// bar / verifier readout.
509    pub fn sketch_selection_count(&self) -> usize {
510        self.sketch_edit
511            .as_ref()
512            .map_or(0, |edit| edit.session.selection.items.len())
513    }
514
515    /// The number of selected CONSTRAINTS (refs whose `kind` is `"constraint"`; 0 when
516    /// not in sketch mode) — the `__brepSketch` verifier readout for constraint
517    /// selection + delete.
518    pub fn sketch_selected_constraint_count(&self) -> usize {
519        self.sketch_edit.as_ref().map_or(0, |edit| {
520            edit.session
521                .selection.items
522                .iter()
523                .filter(|r| r.get("kind").and_then(|v| v.as_str()) == Some("constraint"))
524                .count()
525        })
526    }
527}
528
529fn radial_distance(doc: &crate::sketch::SketchDoc, points: &[serde_json::Value]) -> f64 {
530    match (doc.point(&points[0]), doc.point(&points[1])) {
531        (Some(a), Some(b)) => (b.x - a.x).hypot(b.y - a.y),
532        _ => 0.0,
533    }
534}
535
536fn newly_collapsed_radial_geometry(
537    before: &crate::sketch::SketchDoc,
538    after: &crate::sketch::SketchDoc,
539) -> bool {
540    before.geometries.iter().any(|g| {
541        matches!(g.geom_type.as_str(), "circle" | "arc")
542            && g.points.len() >= 2
543            && radial_distance(before, &g.points) > 1e-5
544            && radial_distance(after, &g.points) <= 1e-5
545    })
546}
547
548// ===========================================================================
549// Sketch draw tools (S3a) — primitive placement: point / line / rect / circle / arc.
550//
551// A click-state machine over the active `self.sketch_edit`. The active tool lives
552// on `session.tool` ("select"/None = selection mode, S2); a DRAW tool routes clicks
553// to `sketch_tool_click_at` (pixel → plane uv via the same S2 `sketch_uv_at`, then
554// `sketch_tool_place_uv`). Points/geometries are minted through `SketchDoc`
555// (`next_point_id`/`next_geometry_id` + `snap_or_add_point`, so shared vertices
556// coincide). Each placement re-solves (swallowing solve errors), re-pushes the
557// overlay (incl. the rubber-band preview), and marks dirty. The bezier tool has a
558// second mode on the same click: idle, a click ON an existing spline REFINES it
559// rather than starting a new one (`crate::sketch::spline`). Kept in ONE appended
560// block so concurrent edits to the primary impl land clean.
561// ===========================================================================
562impl EngineState {
563    /// Set (or clear) the active draw tool: `"select"`/`None` → selection mode (S2);
564    /// `"point"|"line"|"rect"|"circle"|"arc"|"bezier"` arm the corresponding draw
565    /// tool; `"handdraw"` arms the freehand stroke tool (S6b-3); `"trim"` arms the
566    /// trim tool (S6b); `"pickEdges"` arms the external-edge link tool (S6b-2). Clears
567    /// any in-progress click buffer + preview and refreshes the overlay. No-op when not
568    /// in sketch mode.
569    pub fn sketch_set_tool(&mut self, tool: Option<&str>) {
570        let normalized = normalize_sketch_tool(tool);
571        if let Some(edit) = self.sketch_edit.as_mut() {
572            edit.session.tool = normalized;
573            edit.pending.clear();
574            edit.hover_uv = None;
575            edit.handdraw_stroke.clear();
576        } else {
577            return;
578        }
579        // A context edge lit for pickEdges is only that tool's to show.
580        if self.sketch_active_tool() != Some("pickEdges") {
581            self.hover_context(None);
582        }
583        self.refresh_sketch_overlay();
584        self.dirty = true;
585    }
586
587    /// The active draw tool (`"point"|"line"|"rect"|"circle"|"arc"`), or `None` in
588    /// selection mode / when not in sketch mode.
589    pub fn sketch_active_tool(&self) -> Option<&str> {
590        self.sketch_edit
591            .as_ref()
592            .and_then(|edit| edit.session.tool.as_deref())
593    }
594
595    /// The number of in-progress draw-tool clicks buffered (0 in selection mode /
596    /// when not in sketch mode) — the UI/preview + verifier readout.
597    pub fn sketch_pending_len(&self) -> usize {
598        self.sketch_edit.as_ref().map_or(0, |edit| edit.pending.len())
599    }
600
601    /// A draw-tool click at CSS-pixel `(x, y)`: map to plane uv (the S2 pixel→plane
602    /// math) and drive the tool state machine. No-op when not in sketch mode, in
603    /// selection mode, or the ray misses the plane.
604    pub fn sketch_tool_click_at(&mut self, x: f64, y: f64) {
605        // pickEdges (S6b-2) acts on the 3D SCENE EDGE under the cursor — it needs the
606        // PIXEL coords (a scene pick), not a plane uv, so short-circuit before the
607        // pixel→plane projection (which would drop clicks that miss the plane).
608        if self.sketch_active_tool() == Some("pickEdges") {
609            self.sketch_pick_edge_at(x, y);
610            return;
611        }
612        let Some((u, v)) = self.sketch_uv_at(x, y) else {
613            return;
614        };
615        self.sketch_tool_place_uv(u, v);
616    }
617
618    /// The per-tool placement logic, in plane `(u, v)` (the headless-testable core
619    /// `sketch_tool_click_at` delegates to). Snaps to existing points within the grab
620    /// radius so shared vertices coincide; appends geometry and re-solves when a
621    /// primitive completes; carries the line chain via `pending`.
622    pub fn sketch_tool_place_uv(&mut self, u: f64, v: f64) {
623        let radius = self.sketch_pick_radius();
624        // Selection mode (no tool / "select") never places. Read the tool without
625        // holding a borrow so the trim branch can call back into `self`.
626        let tool = match self.sketch_edit.as_ref() {
627            Some(edit) => match edit.session.tool.clone() {
628                Some(tool) => tool,
629                None => return,
630            },
631            None => return,
632        };
633        // Trim (S6b) is a click tool that acts IMMEDIATELY on the geometry under the
634        // cursor — it never buffers `pending` or places a point. It owns its own undo
635        // snapshot (and pops it on a no-op), so short-circuit before the draw path.
636        if tool == "trim" {
637            self.sketch_trim_uv(u, v);
638            return;
639        }
640        // Fillet and chamfer act on the corner under the cursor at once, owning
641        // their undo snapshot like trim.
642        if tool == "fillet" || tool == "chamfer" {
643            self.sketch_corner_uv(u, v, tool == "fillet");
644            return;
645        }
646        // pickEdges is NOT a uv-placement tool — it acts on a 3D scene edge (routed via
647        // pixel coords in `sketch_tool_click_at`), so a stray uv place is a no-op here.
648        if tool == "pickEdges" {
649            return;
650        }
651        // handdraw (S6b-3) captures a DRAG as a stroke (routed via `sketch_handdraw_*`),
652        // not a click-placed point — a plain click is a no-op (and never records a dead
653        // undo step here, since we return before `record_undo`).
654        if tool == "handdraw" {
655            return;
656        }
657        let Some(edit) = self.sketch_edit.as_mut() else {
658            return;
659        };
660        // Check the SNAP RESULT, not just the cursor: a nearby radius click can
661        // reuse the center id. Keep waiting for a valid radius/end without adding
662        // points or an undo step. Arc endpoints must also be off the center.
663        if matches!(tool.as_str(), "circle" | "arc") && !edit.pending.is_empty() {
664            let doc = &edit.session.doc;
665            let Some(center) = doc.point(&edit.pending[0]) else { return; };
666            let snapped = doc.points.iter()
667                .filter(|p| (p.x - u).hypot(p.y - v) <= radius)
668                .min_by(|a, b| (a.x - u).hypot(a.y - v).total_cmp(&(b.x - u).hypot(b.y - v)));
669            let (x, y) = snapped.map_or((u, v), |p| (p.x, p.y));
670            let distance = (x - center.x).hypot(y - center.y);
671            if !distance.is_finite() || distance <= 1e-5 {
672                return;
673            }
674        }
675        if tool == "text" && !edit.pending.is_empty() {
676            if let Some(a) = edit.session.doc.point(&edit.pending[0]) {
677                if (u-a.x).abs() < 1e-5 || (v-a.y).abs() < 1e-5 { return; }
678            }
679        }
680        // A draw tool is active → this click WILL mutate the doc (a point and/or a
681        // geometry); snapshot for undo before it does (S6a).
682        edit.record_undo();
683        let doc = &mut edit.session.doc;
684        match tool.as_str() {
685            "point" => {
686                doc.snap_or_add_point(u, v, radius);
687                edit.pending.clear();
688            }
689            "line" => {
690                if edit.pending.is_empty() {
691                    let a = doc.snap_or_add_point(u, v, radius);
692                    edit.pending.push(a);
693                } else {
694                    let start = edit.pending.last().cloned().expect("pending non-empty");
695                    let end = doc.snap_or_add_point(u, v, radius);
696                    push_sketch_geometry(doc, "line", vec![start, end.clone()]);
697                    // Continue the chain: the just-placed end is the next start.
698                    edit.pending = vec![end];
699                }
700            }
701            "rect" | "text" => {
702                let radius = if tool == "text" { -1.0 } else { radius };
703                if edit.pending.is_empty() {
704                    let a = doc.snap_or_add_point(u, v, radius);
705                    edit.pending.push(a);
706                } else {
707                    let a_id = edit.pending[0].clone();
708                    let Some((ax, ay)) = doc.point(&a_id).map(|p| (p.x, p.y)) else {
709                        edit.pending.clear();
710                        return;
711                    };
712                    let (ax, ay, bx, by) = if tool == "text" {
713                        (ax.min(u), ay.min(v), ax.max(u), ay.max(v))
714                    } else { (ax, ay, u, v) };
715                    if tool == "text" {
716                        if let Some(p) = doc.point_mut(&a_id) { p.x = ax; p.y = ay; }
717                    }
718                    // Corners A=(ax,ay), (bx,ay), (bx,by), (ax,by) → 4 closed lines.
719                    let b1 = doc.snap_or_add_point(bx, ay, radius);
720                    let b2 = doc.snap_or_add_point(bx, by, radius);
721                    let b3 = doc.snap_or_add_point(ax, by, radius);
722                    push_sketch_geometry(doc, "line", vec![a_id.clone(), b1.clone()]);
723                    push_sketch_geometry(doc, "line", vec![b1.clone(), b2.clone()]);
724                    push_sketch_geometry(doc, "line", vec![b2.clone(), b3.clone()]);
725                    push_sketch_geometry(doc, "line", vec![b3.clone(), a_id.clone()]);
726                    // Keep the rectangle rectangular under drag: three ⟂ constraints on
727                    // the adjacent-edge pairs (the 4th corner's right angle follows from
728                    // the closed loop). This is the minimal rigid set — it removes 3 DOF
729                    // from the 8-DOF four-corner quad, leaving position (2) + rotation (1)
730                    // + width + height = 5 DOF, so the sketch is neither over-constrained
731                    // nor conflicting.
732                    if tool == "text" {
733                        let corners = vec![a_id.clone(), b1.clone(), b2.clone(), b3.clone()];
734                        let text_id = doc.next_geometry_id();
735                        for edge in doc.geometries.iter_mut().rev().take(4) {
736                            edge.extra.insert("construction".into(), serde_json::json!(true));
737                            edge.extra.insert("textFrame".into(), text_id.clone());
738                        }
739                        for id in &corners { if let Some(p) = doc.point_mut(id) { p.construction = true; } }
740                        doc.geometries.push(crate::sketch::text::object(text_id.clone(), corners, "Text", "Ubuntu Light").expect("bundled default font"));
741                        edit.session.selection.items = vec![crate::sketch::session::geometry_ref(&text_id)];
742                        edit.session.tool = None;
743                    }
744                    push_rect_perpendicular_constraints(doc, [a_id, b1, b2, b3]);
745                    edit.pending.clear();
746                }
747            }
748            "circle" => {
749                if edit.pending.is_empty() {
750                    let c = doc.snap_or_add_point(u, v, radius);
751                    edit.pending.push(c);
752                } else {
753                    let center = edit.pending[0].clone();
754                    let r = doc.snap_or_add_point(u, v, radius);
755                    push_sketch_geometry(doc, "circle", vec![center, r]);
756                    edit.pending.clear();
757                }
758            }
759            "arc" => {
760                // Clicks: center, start, then end completes [center, start, end].
761                if edit.pending.len() < 2 {
762                    let p = doc.snap_or_add_point(u, v, radius);
763                    edit.pending.push(p);
764                } else {
765                    let center = edit.pending[0].clone();
766                    let start = edit.pending[1].clone();
767                    let end = doc.snap_or_add_point(u, v, radius);
768                    push_sketch_geometry(doc, "arc", vec![center, start, end]);
769                    edit.pending.clear();
770                }
771            }
772            "bezier" => {
773                // Cubic Bezier: 4 clicks place end0, ctrl0, ctrl1, end1 (in order).
774                // The 4th click commits the span [p0, p1, p2, p3] PLUS two dashed
775                // construction guide lines for the control handles (end0→ctrl0 and
776                // end1→ctrl1), matching the previous basic bezier tool. One INVOCATION
777                // authors one span; a chained multi-span polygon (3n+1 ids in ONE
778                // geometry — the model the solver, tessellator and profile builder all
779                // already read) is grown by insertion instead, below.
780                //
781                // IDLE + a click on an existing spline = refine it: subdivide the
782                // clicked span so a new anchor lands under the cursor without the curve
783                // moving (see `crate::sketch::spline`). Only while `pending` is empty —
784                // mid-draw the click still means "place the next control point", so a
785                // new spline can be drawn across an old one. A refusal (nothing under
786                // the cursor, a point winning the pick, a degenerate span) falls
787                // through to that placement, which mutates the doc too, so the
788                // `record_undo` above never leaves a dead step either way.
789                let refined = edit.pending.is_empty() && spline_insert_anchor(doc, u, v, radius);
790                if !refined {
791                    if edit.pending.len() < 3 {
792                        let p = doc.snap_or_add_point(u, v, radius);
793                        edit.pending.push(p);
794                    } else {
795                        let p0 = edit.pending[0].clone();
796                        let p1 = edit.pending[1].clone();
797                        let p2 = edit.pending[2].clone();
798                        let p3 = doc.snap_or_add_point(u, v, radius);
799                        push_sketch_geometry(
800                            doc,
801                            "bezier",
802                            vec![p0.clone(), p1.clone(), p2.clone(), p3.clone()],
803                        );
804                        // Construction guide lines (dashed, non-modeling) for the two
805                        // control handles — separate freshly minted geometry ids.
806                        push_sketch_construction_line(doc, vec![p0, p1]);
807                        push_sketch_construction_line(doc, vec![p3, p2]);
808                        edit.pending.clear();
809                    }
810                }
811            }
812            _ => return,
813        }
814        // Every draw click mutates the doc (a new point and/or geometry); re-solve so
815        // coordinates + mobility stay fresh, keeping the doc if the solve fails.
816        self.resolve_active_sketch("draw-tool");
817        self.refresh_sketch_overlay();
818        self.dirty = true;
819    }
820
821    /// Abort the in-progress draw geometry (Escape / right-click): clear the pending
822    /// clicks + preview and refresh. No-op when not in sketch mode.
823    pub fn sketch_tool_cancel(&mut self) {
824        if let Some(edit) = self.sketch_edit.as_mut() {
825            edit.pending.clear();
826        } else {
827            return;
828        }
829        self.refresh_sketch_overlay();
830        self.dirty = true;
831    }
832}
833
834/// Normalize a tool name to the stored form: `None`/`"select"`/`""` → selection mode
835/// (`None`), else the tool string (`"point"|"line"|"rect"|"circle"|"arc"|"bezier"|
836/// "trim"|"pickEdges"|"handdraw"`).
837fn normalize_sketch_tool(tool: Option<&str>) -> Option<String> {
838    match tool {
839        None | Some("select") | Some("") => None,
840        Some(t) => Some(t.to_string()),
841    }
842}
843
844/// Append a geometry to a sketch doc with a freshly minted id (the caller passes the
845/// solver `type` — `rect` corners are pushed as `line`s), carrying an explicit
846/// `construction: false` so it matches the authored shape and round-trips.
847fn push_sketch_geometry(
848    doc: &mut crate::sketch::SketchDoc,
849    geom_type: &str,
850    points: Vec<serde_json::Value>,
851) {
852    let id = doc.next_geometry_id();
853    let mut extra = serde_json::Map::new();
854    extra.insert("construction".to_string(), serde_json::Value::Bool(false));
855    doc.geometries.push(crate::sketch::SketchGeometry {
856        id,
857        geom_type: geom_type.to_string(),
858        points,
859        extra,
860    });
861}
862
863/// Append a CONSTRUCTION `line` geometry (dashed, non-modeling — `construction: true`)
864/// with a freshly minted id: the bezier tool's control-handle guide lines. Mirrors
865/// [`push_sketch_geometry`] but flips the construction flag so the line renders dashed
866/// and is excluded from profiles while still being constrainable.
867fn push_sketch_construction_line(
868    doc: &mut crate::sketch::SketchDoc,
869    points: Vec<serde_json::Value>,
870) {
871    let id = doc.next_geometry_id();
872    let mut extra = serde_json::Map::new();
873    extra.insert("construction".to_string(), serde_json::Value::Bool(true));
874    doc.geometries.push(crate::sketch::SketchGeometry {
875        id,
876        geom_type: "line".to_string(),
877        points,
878        extra,
879    });
880}
881
882/// Subdivide the spline under the plane click `(u, v)` — the bezier tool's "refine
883/// what I already drew" click. Delegates the pick + de Casteljau split to
884/// [`crate::sketch::spline::insert_anchor`] (which decides whether the click is a
885/// subdivision at all) and, when it lands, hangs the SAME two dashed construction
886/// guides on the new anchor that the 4-click path hangs on the two drawn ends:
887/// anchor→handle on each side. Consistency is the whole point — after a refine every
888/// anchor of the spline, drawn or inserted, has a guide to each of its neighbouring
889/// handles, so the handles stay visible and constrainable (a tangent on a guide is
890/// how a spline is made to meet a line smoothly) and a refined curve is
891/// indistinguishable from one drawn that way. The two ORIGINAL guides still read
892/// correctly without being touched, because the split reuses the end handles' ids and
893/// they remain the handles adjacent to those same two end anchors.
894///
895/// Returns whether the click was consumed as an insertion; `false` means the caller
896/// should treat it as an ordinary control-point placement.
897fn spline_insert_anchor(doc: &mut crate::sketch::SketchDoc, u: f64, v: f64, radius: f64) -> bool {
898    let Some(added) = crate::sketch::spline::insert_anchor(doc, u, v, radius) else {
899        return false;
900    };
901    push_sketch_construction_line(doc, vec![added.anchor.clone(), added.before]);
902    push_sketch_construction_line(doc, vec![added.anchor, added.after]);
903    true
904}
905
906/// Append the three perpendicular (`⟂`) constraints that keep a freshly drawn
907/// rectangle rectangular when a corner is dragged. `corners` are the rect's four
908/// points in loop order `[a, b1, b2, b3]` (edges a→b1, b1→b2, b2→b3, b3→a); the
909/// constraints go on the adjacent-edge pairs sharing corners b1 / b2 / b3. The fourth
910/// corner (a) is left implied — a closed quad with three right angles is a rectangle —
911/// so this is the MINIMAL rigid set (3 equations, no over-constraint / redundancy).
912///
913/// Each `⟂` stores the two edges' endpoint pairs `[l1a, l1b, l2a, l2b]`, swap-oriented
914/// exactly like a palette-added perpendicular ([`sketch_build_and_add_constraint`]), and
915/// is deduped on its signature. No-op unless the four corners are all distinct (a
916/// degenerate rect whose corners snapped together would otherwise carry a `⟂` on a
917/// zero-length edge, which is meaningless and can wedge the solver).
918fn push_rect_perpendicular_constraints(
919    doc: &mut crate::sketch::SketchDoc,
920    corners: [serde_json::Value; 4],
921) {
922    use crate::sketch::doc::id_key;
923    let [a, b1, b2, b3] = corners;
924    let keys = [id_key(&a), id_key(&b1), id_key(&b2), id_key(&b3)];
925    for i in 0..keys.len() {
926        for j in (i + 1)..keys.len() {
927            if keys[i] == keys[j] {
928                return; // two corners collapsed → skip (no zero-length-edge ⟂).
929            }
930        }
931    }
932    // Adjacent edge pairs sharing corner b1 / b2 / b3.
933    let pairs = [
934        [a.clone(), b1.clone(), b1.clone(), b2.clone()],
935        [b1.clone(), b2.clone(), b2.clone(), b3.clone()],
936        [b2.clone(), b3.clone(), b3.clone(), a.clone()],
937    ];
938    for pair in pairs {
939        let mut pts = pair.to_vec();
940        if sketch_perpendicular_should_swap(doc, &pts) {
941            pts.swap(0, 1);
942        }
943        push_geometric_constraint(doc, "⟂", pts);
944    }
945}
946
947/// Append a NON-dimensional geometric constraint (`type` + ordered `points`) with a
948/// freshly minted id and the same base fields a palette-added constraint carries
949/// (`labelX`/`labelY` = 0, `displayStyle` = "", `value` = null, `valueNeedsSetup` =
950/// true — see [`sketch_build_and_add_constraint`]). Deduped on `type + sorted-points`
951/// (the solver runs with `remove_implied_duplicates: false`, so this is the only
952/// dedup); a no-op on a duplicate.
953fn push_geometric_constraint(
954    doc: &mut crate::sketch::SketchDoc,
955    ctype: &str,
956    points: Vec<serde_json::Value>,
957) {
958    let sig = sketch_constraint_signature(ctype, &points);
959    let duplicate = doc.constraints.iter().any(|c| match c.ctype() {
960        Some(t) => sketch_constraint_signature(t, c.points()) == sig,
961        None => false,
962    });
963    if duplicate {
964        return;
965    }
966    let id = doc.next_constraint_id();
967    let mut raw = serde_json::Map::new();
968    raw.insert("id".to_string(), id);
969    raw.insert("type".to_string(), serde_json::Value::String(ctype.to_string()));
970    raw.insert("points".to_string(), serde_json::Value::Array(points));
971    raw.insert("labelX".to_string(), serde_json::Value::from(0));
972    raw.insert("labelY".to_string(), serde_json::Value::from(0));
973    raw.insert(
974        "displayStyle".to_string(),
975        serde_json::Value::String(String::new()),
976    );
977    raw.insert("value".to_string(), serde_json::Value::Null);
978    raw.insert("valueNeedsSetup".to_string(), serde_json::Value::Bool(true));
979    doc.constraints.push(crate::sketch::SketchConstraint { raw });
980}
981
982// ===========================================================================
983// Auto-constrain — infer the constraints implied by the rough-in geometry.
984//
985// A one-click "constrain what I drew": snap nearly-axis-aligned lines to `━`/`│` and
986// near-coincident points to `≡`, going through the same `push_geometric_constraint`
987// dedup the palette uses so the solver picks them up and a re-run is idempotent.
988// ===========================================================================
989
990/// Auto-constrain tolerances (v1 constants; a future pass could surface them as
991/// settings). A line whose direction is within [`AUTO_HV_ANGLE_TOL_DEG`] of an axis
992/// gets a horizontal/vertical constraint — loose enough to catch a rough-in, far
993/// below the slope a user clearly intended.
994const AUTO_HV_ANGLE_TOL_DEG: f64 = 3.0;
995/// Two points auto-snap to COINCIDENT when within this fraction of the sketch's
996/// bounding-box diagonal (scale-invariant, so it works at any sketch size)…
997const AUTO_COINCIDENT_FRAC: f64 = 0.01;
998/// …floored at this absolute distance for a tiny or single-cluster sketch.
999const AUTO_COINCIDENT_ABS: f64 = 1e-4;
1000
1001/// Infer + add the constraints implied by the current geometry: `━`/`│` on
1002/// nearly-axis-aligned lines and `≡` between near-coincident points. Conservative —
1003/// never adds an unsatisfiable constraint on two already-fixed points, never collapses
1004/// a curve by coinciding its own endpoints, never re-adds a coincident already implied
1005/// (directly or transitively), and dedups H/V via [`push_geometric_constraint`]. So a
1006/// second pass adds nothing (idempotent). Returns the number of constraints added; the
1007/// caller re-solves.
1008pub(super) fn auto_constrain_doc(doc: &mut crate::sketch::SketchDoc) -> usize {
1009    use crate::sketch::doc::id_key;
1010    use serde_json::Value;
1011    use std::collections::{HashMap, HashSet};
1012
1013    let before = doc.constraints.len();
1014
1015    // ---- Horizontal / vertical on nearly-axis-aligned lines. ----
1016    // Threshold on |unit component off the axis| = |sin(angle deviation)|.
1017    let hv_sin_tol = AUTO_HV_ANGLE_TOL_DEG.to_radians().sin();
1018    let mut hv: Vec<(&str, Vec<Value>)> = Vec::new();
1019    for g in &doc.geometries {
1020        if g.geom_type != "line" || g.points.len() < 2 {
1021            continue;
1022        }
1023        let (Some(a), Some(b)) = (doc.point(&g.points[0]), doc.point(&g.points[1])) else {
1024            continue;
1025        };
1026        // Skip a line pinned at BOTH ends (no freedom → an H/V that isn't already
1027        // exactly true is unsatisfiable). This also excludes linked reference lines,
1028        // whose endpoints are all fixed.
1029        if a.fixed && b.fixed {
1030            continue;
1031        }
1032        let (dx, dy) = (b.x - a.x, b.y - a.y);
1033        let len = dx.hypot(dy);
1034        if len < 1e-9 {
1035            continue;
1036        }
1037        // Skip a line that already carries an H or V constraint on these endpoints
1038        // (never add the opposite one; keeps the pass idempotent).
1039        let mut keys: Vec<String> = g.points[..2].iter().map(id_key).collect();
1040        keys.sort();
1041        let already_hv = doc.constraints.iter().any(|c| {
1042            if !matches!(c.ctype(), Some("━") | Some("│")) {
1043                return false;
1044            }
1045            let mut k: Vec<String> = c.points().iter().map(id_key).collect();
1046            k.sort();
1047            k == keys
1048        });
1049        if already_hv {
1050            continue;
1051        }
1052        let (ux, uy) = (dx / len, dy / len);
1053        if uy.abs() <= hv_sin_tol {
1054            hv.push(("━", vec![g.points[0].clone(), g.points[1].clone()]));
1055        } else if ux.abs() <= hv_sin_tol {
1056            hv.push(("│", vec![g.points[0].clone(), g.points[1].clone()]));
1057        }
1058    }
1059    for (ct, pts) in hv {
1060        push_geometric_constraint(doc, ct, pts);
1061    }
1062
1063    // ---- Coincident between near-coincident, mergeable point pairs. ----
1064    let n = doc.points.len();
1065    if n >= 2 {
1066        fn find(parent: &mut [usize], mut x: usize) -> usize {
1067            while parent[x] != x {
1068                parent[x] = parent[parent[x]]; // path halving
1069                x = parent[x];
1070            }
1071            x
1072        }
1073        fn union(parent: &mut [usize], a: usize, b: usize) {
1074            let (ra, rb) = (find(parent, a), find(parent, b));
1075            if ra != rb {
1076                parent[ra] = rb;
1077            }
1078        }
1079
1080        // Union-find over point indices, SEEDED with the existing coincidents so we
1081        // never re-add one (directly or transitively).
1082        let index: HashMap<String, usize> = doc
1083            .points
1084            .iter()
1085            .enumerate()
1086            .map(|(i, p)| (id_key(&p.id), i))
1087            .collect();
1088        let mut parent: Vec<usize> = (0..n).collect();
1089        for c in &doc.constraints {
1090            if c.ctype() == Some("≡") {
1091                let pts = c.points();
1092                if let (Some(p0), Some(p1)) = (pts.first(), pts.get(1)) {
1093                    if let (Some(&i), Some(&j)) = (index.get(&id_key(p0)), index.get(&id_key(p1))) {
1094                        union(&mut parent, i, j);
1095                    }
1096                }
1097            }
1098        }
1099
1100        // Distance tolerance relative to the sketch extent — the user's points only:
1101        // the part-origin reference may sit far from the drawing and must not widen it.
1102        let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
1103        for p in doc.points.iter().filter(|p| !brep_kernel::is_sketch_origin_point_id(&p.id)) {
1104            lo[0] = lo[0].min(p.x);
1105            lo[1] = lo[1].min(p.y);
1106            hi[0] = hi[0].max(p.x);
1107            hi[1] = hi[1].max(p.y);
1108        }
1109        let extent = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2)).sqrt();
1110        let tol = (extent * AUTO_COINCIDENT_FRAC).max(AUTO_COINCIDENT_ABS);
1111
1112        // Point-key set per geometry — skip a pair that are the two ends of the SAME
1113        // curve (coinciding them would collapse it).
1114        let geo_sets: Vec<HashSet<String>> = doc
1115            .geometries
1116            .iter()
1117            .map(|g| g.points.iter().map(id_key).collect())
1118            .collect();
1119
1120        let mut coincidents: Vec<Vec<Value>> = Vec::new();
1121        for i in 0..n {
1122            for j in (i + 1)..n {
1123                let (pi, pj) = (&doc.points[i], &doc.points[j]);
1124                if pi.fixed && pj.fixed {
1125                    continue; // both pinned → a coincident is unsatisfiable
1126                }
1127                let d = ((pi.x - pj.x).powi(2) + (pi.y - pj.y).powi(2)).sqrt();
1128                if d > tol {
1129                    continue;
1130                }
1131                if find(&mut parent, i) == find(&mut parent, j) {
1132                    continue; // already coincident (directly or transitively)
1133                }
1134                let (ki, kj) = (id_key(&pi.id), id_key(&pj.id));
1135                if geo_sets.iter().any(|s| s.contains(&ki) && s.contains(&kj)) {
1136                    continue; // endpoints of one curve — do not collapse it
1137                }
1138                union(&mut parent, i, j);
1139                coincidents.push(vec![pi.id.clone(), pj.id.clone()]);
1140            }
1141        }
1142        for pts in coincidents {
1143            push_geometric_constraint(doc, "≡", pts);
1144        }
1145    }
1146
1147    doc.constraints.len().saturating_sub(before)
1148}
1149
1150impl EngineState {
1151    /// Auto-constrain the active sketch (the toolbar's one-click "constrain what I
1152    /// roughed in"): infer `━`/`│` on nearly-axis-aligned lines and `≡` between
1153    /// near-coincident points, then re-solve. Records ONE undo step, popped when the
1154    /// pass adds nothing so a dead click neither pollutes undo nor clobbers redo.
1155    /// Returns the number of constraints added; a no-op (0) when not in sketch mode.
1156    pub fn sketch_auto_constrain(&mut self) -> usize {
1157        let Some(edit) = self.sketch_edit.as_mut() else {
1158            return 0;
1159        };
1160        edit.record_undo();
1161        let added = auto_constrain_doc(&mut edit.session.doc);
1162        if added == 0 {
1163            edit.undo_stack.pop();
1164            return 0;
1165        }
1166        self.resolve_active_sketch("auto-constrain");
1167        self.refresh_sketch_overlay();
1168        self.dirty = true;
1169        added
1170    }
1171}
1172
1173// ===========================================================================
1174// Sketch delete-selected (S3b) — remove the selected entities + orphan cleanup.
1175//
1176// Operates on the active `self.sketch_edit`. Rule (chosen so a remaining geometry
1177// NEVER references a missing point):
1178//   1. Partition the selection into selected geometry / point / constraint ids.
1179//   2. Drop every geometry that is SELECTED *or* references any selected point (the
1180//      remove-point cascade — deleting a vertex kills geometry that used it).
1181//   3. Drop the selected points.
1182//   4. Orphan cleanup: drop any point a dropped geometry used that NO surviving
1183//      geometry references (a shared vertex — still referenced — stays; a deleted
1184//      line's now unshared endpoints vanish). Points no geometry used before the
1185//      delete (a fillet's construction virtual sharp) are never orphaned by it.
1186//   5. Drop any constraint that is SELECTED *or* references a removed point (selected ∪
1187//      orphaned) — done LAST, over the full removed-point set, so no constraint dangles
1188//      either. A selected constraint drops ONLY itself; the geometry/points it
1189//      referenced are untouched (deleting a constraint never deletes geometry).
1190// Then clear selection + hover, re-solve (swallowing errors), refresh, mark dirty.
1191// Kept in ONE appended block so concurrent edits to the primary impl land clean.
1192// ===========================================================================
1193impl EngineState {
1194    /// Delete the selected sketch entities (S3b): the selected geometries + points,
1195    /// plus any geometry orphaned by a deleted vertex, plus orphaned points and the
1196    /// constraints referencing any removed point. Re-solves + refreshes the overlay.
1197    /// Returns `true` when something was deleted; `false` when not in sketch mode or
1198    /// the selection is empty.
1199    pub fn sketch_delete_selection(&mut self) -> bool {
1200        use crate::sketch::doc::id_key;
1201        use std::collections::HashSet;
1202
1203        let Some(edit) = self.sketch_edit.as_mut() else {
1204            return false;
1205        };
1206        if edit.session.selection.items.is_empty() {
1207            return false;
1208        }
1209        // A non-empty selection always removes something → snapshot for undo (S6a).
1210        edit.record_undo();
1211
1212        // 1. Partition the selection into selected geometry / point / constraint ids
1213        //    (keyed via `id_key`, so 4 / 4.0 / "4" all match).
1214        let mut sel_geo: HashSet<String> = HashSet::new();
1215        let mut sel_pt: HashSet<String> = HashSet::new();
1216        let mut sel_constraint: HashSet<String> = HashSet::new();
1217        for r in &edit.session.selection.items {
1218            match (r.get("kind").and_then(|v| v.as_str()), r.get("id")) {
1219                (Some("geometry"), Some(id)) => {
1220                    sel_geo.insert(id_key(id));
1221                }
1222                (Some("point"), Some(id)) => {
1223                    sel_pt.insert(id_key(id));
1224                }
1225                (Some("constraint"), Some(id)) => {
1226                    sel_constraint.insert(id_key(id));
1227                }
1228                _ => {}
1229            }
1230        }
1231
1232        // The part-origin reference and its ground are permanent: never deleted,
1233        // selected or orphaned.
1234        let origin_key = id_key(&serde_json::Value::String(
1235            brep_kernel::SKETCH_ORIGIN_POINT_ID.to_string(),
1236        ));
1237        sel_pt.remove(&origin_key);
1238        sel_constraint.remove(&origin_key);
1239
1240        let doc = &mut edit.session.doc;
1241
1242        let deleted_texts: HashSet<String> = doc.geometries.iter().filter(|g| g.geom_type == "text")
1243            .filter(|g| sel_geo.contains(&id_key(&g.id)) || g.points.iter().any(|p| sel_pt.contains(&id_key(p))) || doc.geometries.iter().any(|edge| edge.extra.get("textFrame") == Some(&g.id) && sel_geo.contains(&id_key(&edge.id))))
1244            .map(|g| id_key(&g.id)).collect();
1245        for g in &doc.geometries {
1246            if deleted_texts.contains(&id_key(&g.id)) || g.extra.get("textFrame").is_some_and(|id| deleted_texts.contains(&id_key(id))) {
1247                sel_geo.insert(id_key(&g.id));
1248            }
1249        }
1250
1251        // 2. Drop geometries that are selected OR reference any selected point (so a
1252        //    deleted vertex never leaves a geometry dangling). Remember every point a
1253        //    dropped geometry used: only those can be orphaned by this delete.
1254        let mut released: HashSet<String> = HashSet::new();
1255        doc.geometries.retain(|g| {
1256            let keep = !sel_geo.contains(&id_key(&g.id)) && !g.points.iter().any(|pid| sel_pt.contains(&id_key(pid)));
1257            if !keep {
1258                released.extend(g.points.iter().map(id_key));
1259            }
1260            keep
1261        });
1262
1263        // 3. Drop the explicitly-selected points.
1264        doc.points.retain(|p| !sel_pt.contains(&id_key(&p.id)));
1265
1266        // 4. Orphan cleanup: drop points a dropped geometry used that no surviving
1267        //    geometry references. A point no geometry used before the delete is
1268        //    left alone: a fillet's or chamfer's virtual sharp (the construction
1269        //    corner its trimmed lines and the width/height dimensions still hang
1270        //    on) is held only by constraints, and deleting an unrelated
1271        //    constraint must not take it, and every constraint on it, along.
1272        //    Accumulate every removed point
1273        //    id (selected ∪ orphaned).
1274        let referenced: HashSet<String> = doc
1275            .geometries
1276            .iter()
1277            .flat_map(|g| g.points.iter().map(id_key))
1278            .collect();
1279        let mut removed_pts = sel_pt;
1280        doc.points.retain(|p| {
1281            let key = id_key(&p.id);
1282            if referenced.contains(&key) || key == origin_key || !released.contains(&key) {
1283                true
1284            } else {
1285                removed_pts.insert(key);
1286                false
1287            }
1288        });
1289
1290        // 5. Drop constraints that are EXPLICITLY selected OR reference ANY removed
1291        //    point (done last, over the full removed set, so no constraint dangles onto
1292        //    a missing point). A selected constraint drops ONLY itself — the geometry /
1293        //    points it references are left intact (deleting a constraint never deletes
1294        //    geometry).
1295        doc.constraints.retain(|c| {
1296            if let Some(id) = c.raw.get("id") {
1297                if sel_constraint.contains(&id_key(id)) {
1298                    return false;
1299                }
1300            }
1301            !c.points().iter().any(|pid| removed_pts.contains(&id_key(pid)))
1302        });
1303
1304        // Drop any external-reference bookkeeping whose materialized entities this
1305        // delete removed — otherwise its stale entry (keyed by edge name, now holding
1306        // dangling point ids) permanently blocks RE-LINKING the same edge.
1307        crate::sketch::external_ref::prune_dead_refs(&edit.session.doc, &mut edit.external_refs);
1308
1309        // Clear the interaction state, re-solve (keep the doc on failure), refresh.
1310        edit.session.clear_selection();
1311        edit.session.set_hover(None);
1312        self.resolve_active_sketch("delete");
1313        self.refresh_sketch_overlay();
1314        self.dirty = true;
1315        true
1316    }
1317}