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