Skip to main content

brep_render/sketch/
session.rs

1//! A sketch's solved document, plane, diagnostics, and interaction state.
2
3use crate::geometry2d::point_segment_distance;
4
5use serde_json::{json, Value};
6
7use super::doc::{id_key, SketchDiagnostics, SketchDoc};
8use super::tessellate::{self, SketchTessellation};
9use super::{solve, PlaneFrame};
10use crate::style::SketchColors;
11
12/// State for one active sketch.
13pub struct SketchSession {
14    /// The solved sketch (points carry solved coordinates).
15    pub doc: SketchDoc,
16    /// The plane the sketch's `(u, v)` coordinates are embedded in.
17    pub plane: PlaneFrame,
18    /// The last solve's read-only diagnostics (DOF, over/under status, mobility).
19    pub diagnostics: SketchDiagnostics,
20
21    // --- interaction state ---------------------------------------------------
22    /// Selected entities — a set of entity refs
23    /// (`{"kind":"point"|"geometry","id":<id>}`; see [`point_ref`]/[`geometry_ref`])
24    /// — and the one under the cursor.
25    pub selection: RefSelection,
26    /// The active drawing tool.
27    pub tool: Option<String>,
28    /// Persisted dimension label offsets.
29    pub dim_offsets: serde_json::Map<String, Value>,
30    /// The overlay color palette — a live [`SketchColors`] view of the display
31    /// settings (`RenderSettings::sketch_colors`). The engine sets this on entry and
32    /// re-syncs it when the settings change; every overlay builder reads from here so
33    /// the sketch colors are managed in the settings like the rest of the display.
34    /// Defaults to [`SketchColors::default`] so a session built in a test (or before
35    /// the engine syncs) renders the standard theme.
36    pub colors: SketchColors,
37    /// User-tunable solver knobs (the Solver Settings panel). Read by every
38    /// [`resolve`](Self::resolve); default reproduces the historical solve.
39    pub solver_settings: solve::SketchSolverSettings,
40    /// The fillet and chamfer tools' options.
41    pub corner_options: super::corner::CornerOptions,
42    /// Why the last fillet or chamfer click changed nothing (a refusal), shown
43    /// in the tool's options panel; cleared by the next edit that succeeds.
44    pub corner_message: Option<String>,
45}
46
47/// A sketch session's selection set and hover — ONE implementation for the
48/// planar session and the 3D one ([`crate::sketch3d::Sketch3dSession`]):
49/// entity refs, matched through [`refs_equal`].
50#[derive(Debug, Clone, Default, PartialEq)]
51pub struct RefSelection {
52    /// The selected entity refs, in selection order.
53    pub items: Vec<Value>,
54    /// The entity ref under the cursor, or `None`.
55    pub hovered: Option<Value>,
56}
57
58impl RefSelection {
59    /// Whether `entity_ref` is selected (matched via [`refs_equal`]).
60    pub fn is_selected(&self, entity_ref: &Value) -> bool {
61        self.items.iter().any(|r| refs_equal(r, entity_ref))
62    }
63
64    /// Remove `entity_ref` if selected, else add it.
65    pub fn toggle(&mut self, entity_ref: Value) {
66        if let Some(pos) = self.items.iter().position(|r| refs_equal(r, &entity_ref)) {
67            self.items.remove(pos);
68        } else {
69            self.items.push(entity_ref);
70        }
71    }
72
73    /// Select nothing (the hover is left alone).
74    pub fn clear(&mut self) {
75        self.items.clear();
76    }
77}
78
79impl SketchSession {
80    /// Build a session from a (possibly unsolved) doc + plane, solving it once.
81    pub fn new(doc: SketchDoc, plane: PlaneFrame) -> Result<Self, String> {
82        let (solved, diagnostics) = solve::solve(&doc)?;
83        Ok(Self {
84            doc: solved,
85            plane,
86            diagnostics,
87            selection: RefSelection::default(),
88            tool: None,
89            dim_offsets: serde_json::Map::new(),
90            colors: SketchColors::default(),
91            solver_settings: solve::SketchSolverSettings::default(),
92            corner_options: super::corner::CornerOptions::default(),
93            corner_message: None,
94        })
95    }
96
97    /// Re-solve the current doc, refreshing coordinates + diagnostics in place,
98    /// honoring the session's [`solver_settings`](Self::solver_settings).
99    pub fn resolve(&mut self) -> Result<(), String> {
100        let (solved, diagnostics) = solve::solve_with(&self.doc, &self.solver_settings)?;
101        self.doc = solved;
102        self.diagnostics = diagnostics;
103        Ok(())
104    }
105
106    /// Re-solve one interactive drag frame: with `BREP_SKETCH_DRAG_MIN_CHANGE` on,
107    /// the smallest change from the current coordinates
108    /// ([`resolve_min_change`](Self::resolve_min_change)); otherwise a plain
109    /// [`resolve`](Self::resolve).
110    pub fn resolve_drag(&mut self) -> Result<(), String> {
111        if solve::drag_min_change() {
112            self.resolve_min_change()
113        } else {
114            self.resolve()
115        }
116    }
117
118    /// Re-solve by the smallest change of the free coordinates that meets every
119    /// constraint ([`solve::solve_drag_with`]), relaxing only when that fails.
120    pub fn resolve_min_change(&mut self) -> Result<(), String> {
121        let (solved, diagnostics) = solve::solve_drag_with(&self.doc, &self.solver_settings)?;
122        self.doc = solved;
123        self.diagnostics = diagnostics;
124        Ok(())
125    }
126
127    /// The `set_overlay` JSON for this solved sketch (see
128    /// [`tessellate::overlay_json`]). `world_per_pixel` sizes construction dashes.
129    pub fn overlay_json(&self, world_per_pixel: f64) -> String {
130        tessellate::overlay_json(
131            &self.doc,
132            &self.diagnostics,
133            &self.plane,
134            world_per_pixel,
135            &self.colors,
136        )
137    }
138
139    /// The flat overlay buffers (for tests / verification stats).
140    pub fn tessellation(&self, world_per_pixel: f64) -> SketchTessellation {
141        tessellate::tessellate(
142            &self.doc,
143            &self.diagnostics,
144            &self.plane,
145            world_per_pixel,
146            &self.colors,
147        )
148    }
149
150    /// The `set_overlay` JSON with the live hover + selection colored in (S2). Empty
151    /// hover + selection reproduce [`overlay_json`](Self::overlay_json) exactly.
152    pub fn overlay_json_with_state(&self, world_per_pixel: f64) -> String {
153        tessellate::overlay_json_with_state(
154            &self.doc,
155            &self.diagnostics,
156            &self.plane,
157            world_per_pixel,
158            &self.colors,
159            self.selection.hovered.as_ref(),
160            &self.selection.items,
161        )
162    }
163
164    /// The `set_overlay` JSON for the `sketch-dim-leaders` group (S5): the per-type
165    /// leader/arrow segments for every dimensional constraint, offset by its stored
166    /// `{du, dv}` (see [`dimensions`](super::dimensions)). Always emitted (empty when
167    /// the sketch has no dimensions) so a stale group clears on the next refresh.
168    pub fn dim_leaders_overlay_json(&self, world_per_pixel: f64) -> String {
169        super::dimensions::dimension_leaders_overlay_json(
170            &self.doc,
171            &self.diagnostics,
172            &self.plane,
173            &self.dim_offsets,
174            world_per_pixel,
175            &self.colors,
176        )
177    }
178
179    /// Like [`dim_leaders_overlay_json`](Self::dim_leaders_overlay_json) but emphasizes
180    /// the live hovered / selected dimensional constraint (amber selected, light-blue
181    /// hovered — matching points/geometry). Used by the interactive overlay refresh.
182    pub fn dim_leaders_overlay_json_with_state(&self, world_per_pixel: f64) -> String {
183        super::dimensions::dimension_leaders_overlay_json_with_state(
184            &self.doc,
185            &self.diagnostics,
186            &self.plane,
187            &self.dim_offsets,
188            world_per_pixel,
189            &self.colors,
190            self.selection.hovered.as_ref(),
191            &self.selection.items,
192        )
193    }
194
195    /// The `set_overlay` JSON for the `sketch-dof-arrows` group: the free directions
196    /// of the hovered point (or of each point of the hovered geometry), drawn as
197    /// double-headed arrows. Empty when nothing movable is hovered.
198    pub fn freedom_arrows_overlay_json(&self, world_per_pixel: f64) -> String {
199        super::freedom::freedom_arrows_overlay_json(
200            &self.doc,
201            &self.diagnostics,
202            &self.plane,
203            world_per_pixel,
204            &self.colors,
205            self.selection.hovered.as_ref(),
206        )
207    }
208
209    /// The `set_overlay` JSON for the `sketch-constraint-glyphs` group (S6c): the small
210    /// screen-constant line-art marks for every GEOMETRIC (non-dimensional) constraint
211    /// — perpendicular, parallel, horizontal/vertical, coincident, equal, … (see
212    /// [`constraint_glyphs`](super::constraint_glyphs)). Painted in the shared
213    /// constraint green. Always emitted (empty when the sketch has no geometric
214    /// constraints) so a stale group clears on the next refresh.
215    pub fn constraint_glyphs_overlay_json(&self, world_per_pixel: f64) -> String {
216        super::constraint_glyphs::constraint_glyphs_overlay_json(
217            &self.doc,
218            &self.diagnostics,
219            &self.plane,
220            &self.dim_offsets,
221            world_per_pixel,
222            &self.colors,
223        )
224    }
225
226    /// Like [`constraint_glyphs_overlay_json`](Self::constraint_glyphs_overlay_json) but
227    /// emphasizes the live hovered / selected geometric constraint (amber selected,
228    /// light-blue hovered — matching points/geometry). Used by the interactive refresh.
229    pub fn constraint_glyphs_overlay_json_with_state(&self, world_per_pixel: f64) -> String {
230        super::constraint_glyphs::constraint_glyphs_overlay_json_with_state(
231            &self.doc,
232            &self.diagnostics,
233            &self.plane,
234            &self.dim_offsets,
235            world_per_pixel,
236            &self.colors,
237            self.selection.hovered.as_ref(),
238            &self.selection.items,
239        )
240    }
241
242    /// The per-constraint dimension labels (S5): one [`DimLabel`](super::dimensions::DimLabel)
243    /// per dimensional constraint, each anchored in world space (`plane.to_world` of
244    /// the label uv + its stored offset). brep-app projects `world` → screen and
245    /// draws the editable value text there.
246    pub fn dimension_labels(&self, world_per_pixel: f64) -> Vec<super::dimensions::DimLabel> {
247        super::dimensions::dimension_labels(
248            &self.doc,
249            &self.diagnostics,
250            &self.plane,
251            &self.dim_offsets,
252            world_per_pixel,
253        )
254    }
255
256    /// The `set_overlay` JSON for the active draw tool's in-progress rubber-band
257    /// preview (S3a): the dim dashed geometry from the `pending` anchor points (their
258    /// ids, resolved to uv against the live doc) toward `hover_uv`, plus the raw
259    /// freehand `stroke` (S6b-3) as a dim solid polyline while a handdraw drag is live.
260    /// Always a `sketch-preview` group (empty when there is nothing to preview yet).
261    pub fn preview_overlay_json(
262        &self,
263        world_per_pixel: f64,
264        pending: &[Value],
265        hover_uv: Option<(f64, f64)>,
266        stroke: &[(f64, f64)],
267    ) -> String {
268        let pending_uv: Vec<[f64; 2]> = pending
269            .iter()
270            .filter_map(|id| self.doc.point(id).map(|p| [p.x, p.y]))
271            .collect();
272        let stroke_uv: Vec<[f64; 2]> = stroke.iter().map(|&(u, v)| [u, v]).collect();
273        tessellate::preview_overlay_json(
274            self.tool.as_deref(),
275            &pending_uv,
276            hover_uv,
277            &stroke_uv,
278            &self.plane,
279            world_per_pixel,
280            &self.colors,
281        )
282    }
283
284    // --- S2 hover / selection state ------------------------------------------
285
286    /// Whether `entity_ref` is in the selection set (matched via [`refs_equal`]).
287    pub fn is_selected(&self, entity_ref: &Value) -> bool {
288        self.selection.is_selected(entity_ref)
289    }
290
291    /// Toggle `entity_ref` in the selection set: remove it if present, else add it.
292    pub fn toggle_selection(&mut self, entity_ref: Value) {
293        self.selection.toggle(entity_ref)
294    }
295
296    /// Clear the selection set.
297    pub fn clear_selection(&mut self) {
298        self.selection.clear()
299    }
300
301    /// Set (or clear) the hovered entity ref.
302    pub fn set_hover(&mut self, entity_ref: Option<Value>) {
303        self.selection.hovered = entity_ref;
304    }
305
306    // --- S2 hit-testing ------------------------------------------------------
307
308    /// The entity ref nearest to plane coordinate `(u, v)` within `radius` — a
309    /// POINT wins over geometry when one is in range (points take priority), else
310    /// the nearest geometry whose polyline passes within `radius`. Construction
311    /// geometry is included (it is pickable). `None` when nothing is in range.
312    /// The points and curves a BOX takes, `quad` being the screen box's four
313    /// corners on the sketch plane (in order): every entity of the sketch is
314    /// drawn and visible, so WINDOW (`crossing == false`) takes what lies
315    /// fully inside and CROSSING anything that touches it. Point refs first,
316    /// then geometry refs, in document order.
317    pub fn box_refs(&self, quad: [(f64, f64); 4], crossing: bool) -> Vec<Value> {
318        let inside = |p: (f64, f64)| quad_contains(&quad, p);
319        let mut out = Vec::new();
320        for p in &self.doc.points {
321            if inside((p.x, p.y)) {
322                out.push(point_ref(&p.id));
323            }
324        }
325        for g in &self.doc.geometries {
326            let poly = tessellate::geometry_polyline_uv(g, &self.doc);
327            if poly.is_empty() {
328                continue;
329            }
330            let all = poly.iter().all(|q| inside((q[0], q[1])));
331            let touches = all
332                || poly.iter().any(|q| inside((q[0], q[1])))
333                || poly.windows(2).any(|seg| quad_crosses(&quad, (seg[0][0], seg[0][1]), (seg[1][0], seg[1][1])));
334            if if crossing { touches } else { all } {
335                out.push(geometry_ref(&g.id));
336            }
337        }
338        out
339    }
340
341    pub fn pick_entity(&self, u: f64, v: f64, radius: f64) -> Option<Value> {
342        // Points first (priority over geometry under the cursor).
343        let mut best_pt: Option<(f64, &Value)> = None;
344        for p in &self.doc.points {
345            let d = ((p.x - u).powi(2) + (p.y - v).powi(2)).sqrt();
346            if d <= radius && best_pt.map_or(true, |(bd, _)| d < bd) {
347                best_pt = Some((d, &p.id));
348            }
349        }
350        if let Some((_, id)) = best_pt {
351            return Some(point_ref(id));
352        }
353
354        // Else the nearest geometry polyline within radius.
355        let mut best_geo: Option<(f64, &Value)> = None;
356        for g in &self.doc.geometries {
357            let poly = tessellate::geometry_polyline_uv(g, &self.doc);
358            if poly.len() < 2 {
359                continue;
360            }
361            let mut dmin = f64::INFINITY;
362            for seg in poly.windows(2) {
363                let d = point_segment_distance((u, v), seg[0].into(), seg[1].into()).0;
364                if d < dmin {
365                    dmin = d;
366                }
367            }
368            if dmin <= radius && best_geo.map_or(true, |(bd, _)| dmin < bd) {
369                best_geo = Some((dmin, &g.id));
370            }
371        }
372        if let Some((_, id)) = best_geo { return Some(geometry_ref(id)); }
373        // Glyph outlines pick their owning object, never a glyph handle/segment.
374        if !self.doc.geometries.iter().any(|g| g.geom_type == "text") { return None; }
375        let expanded = super::text::expanded(&self.doc).ok()?;
376        let mut best: Option<(f64, Value)> = None;
377        for g in expanded.geometries.iter().filter(|g| g.extra.contains_key("textOwner")) {
378            let poly = tessellate::geometry_polyline_uv(g, &expanded);
379            for seg in poly.windows(2) {
380                let distance = point_segment_distance((u,v),seg[0].into(),seg[1].into()).0;
381                if distance <= radius && best.as_ref().is_none_or(|(d,_)| distance < *d) {
382                    best = Some((distance, geometry_ref(&g.extra["textOwner"])));
383                }
384            }
385        }
386        best.map(|(_, id)|id)
387    }
388
389    /// The CONSTRAINT nearest to `(u, v)` within `radius` — a `constraint` entity ref
390    /// (`{"kind":"constraint","id":<id>}`), or `None`. A GEOMETRIC constraint is picked
391    /// near its glyph line-art (the exact segments [`constraint_glyphs`] draws); a
392    /// DIMENSIONAL one near its leader/arrow lines (NOT its value label — the label is
393    /// the egui value-editor affordance). Solver-internal `temporary` helpers are never
394    /// pickable. `world_per_pixel` sizes the screen-constant glyph/leader placement (so
395    /// picking tracks what is drawn). The CALLER enforces priority: points > geometry >
396    /// constraint (see `EngineState::sketch_entity_at`), so a glyph over a point never
397    /// shadows the point.
398    ///
399    /// [`constraint_glyphs`]: super::constraint_glyphs
400    pub fn pick_constraint(&self, u: f64, v: f64, radius: f64, world_per_pixel: f64) -> Option<Value> {
401        let mut best: Option<(f64, &Value)> = None;
402        let mut glyphs: std::collections::HashMap<usize, Vec<([f64; 2], [f64; 2])>> =
403            super::constraint_glyphs::glyph_layout_segments(&self.doc, &self.dim_offsets, world_per_pixel)
404                .into_iter()
405                .collect();
406        for (index, c) in self.doc.constraints.iter().enumerate() {
407            if c.temporary() {
408                continue;
409            }
410            let Some(id) = c.raw.get("id") else { continue };
411            // A constraint contributes glyph segments (geometric) XOR leader segments
412            // (dimensional); measure the cursor against whichever it draws.
413            let mut dmin = f64::INFINITY;
414            for (a, b) in glyphs.remove(&index).unwrap_or_default() {
415                let d = point_segment_distance((u, v), a.into(), b.into()).0;
416                if d < dmin {
417                    dmin = d;
418                }
419            }
420            if let Some(segments) = super::dimensions::constraint_dim_segments(
421                c,
422                &self.doc,
423                &self.dim_offsets,
424                world_per_pixel,
425            ) {
426                for (a, b) in segments {
427                    let d = point_segment_distance((u, v), a.into(), b.into()).0;
428                    if d < dmin {
429                        dmin = d;
430                    }
431                }
432            }
433            if dmin <= radius && best.map_or(true, |(bd, _)| dmin < bd) {
434                best = Some((dmin, id));
435            }
436        }
437        best.map(|(_, id)| constraint_ref(id))
438    }
439
440    /// The nearest DRAGGABLE point to `(u, v)` within `radius` (its id + authored
441    /// `fixed` flag), or `None`. A point is draggable only if the solver reports it
442    /// movable (a locked / grounded point has no free coordinates to drag), so a
443    /// drag on a fully-constrained point falls through to a camera orbit.
444    pub fn pick_draggable_point(&self, u: f64, v: f64, radius: f64) -> Option<(Value, bool)> {
445        let mut best: Option<(f64, &super::doc::SketchPoint)> = None;
446        for p in &self.doc.points {
447            let movable = self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed);
448            if !movable {
449                continue;
450            }
451            let d = ((p.x - u).powi(2) + (p.y - v).powi(2)).sqrt();
452            if d <= radius && best.map_or(true, |(bd, _)| d < bd) {
453                best = Some((d, p));
454            }
455        }
456        best.map(|(_, p)| (p.id.clone(), p.fixed))
457    }
458
459    /// The point-set to DRAG for a hovered entity ref (`{"kind","id"}`) — the grab
460    /// path grabs exactly what's highlighted rather than re-picking at egui's
461    /// offset drag-start position. A `"point"` ref → that point iff it is MOVABLE;
462    /// a `"geometry"` ref → its movable (deduped) points. Free geometry
463    /// translates rigidly; locked endpoints stay anchored during the solve.
464    /// Each entry is `(id, orig_x, orig_y, orig_fixed)`. `None`
465    /// for a locked point, a fully-locked geometry, or a stale/unknown ref (the
466    /// caller then falls through to a camera gesture — it never drags something the
467    /// user is not pointing at).
468    pub fn drag_points_from_ref(&self, entity_ref: &Value) -> Option<Vec<(Value, f64, f64, bool)>> {
469        let kind = entity_ref.get("kind").and_then(Value::as_str)?;
470        let id = entity_ref.get("id")?;
471        match kind {
472            "point" => {
473                let p = self.doc.point(id)?;
474                let movable = self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed);
475                movable.then(|| vec![(p.id.clone(), p.x, p.y, p.fixed)])
476            }
477            "geometry" => {
478                // Raw doc ids compare via `id_key` (numeric identity) — NOT
479                // `refs_equal`, which is for `{"kind","id"}` entity refs and treats
480                // every bare id as equal.
481                let g = self
482                    .doc
483                    .geometries
484                    .iter()
485                    .find(|g| id_key(&g.id) == id_key(id))?;
486                let mut out: Vec<(Value, f64, f64, bool)> = Vec::new();
487                for pid in &g.points {
488                    // A closed polyline repeats its start id — dedupe so a point is
489                    // pinned once.
490                    if out.iter().any(|(pt_id, ..)| id_key(pt_id) == id_key(pid)) {
491                        continue;
492                    }
493                    if let Some(p) = self.doc.point(pid) {
494                        // Ground constraints anchor the coordinates supplied to the
495                        // solver. Moving a locked endpoint here would re-ground it
496                        // at the drag target (including the sketch origin).
497                        if self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed) {
498                            out.push((p.id.clone(), p.x, p.y, p.fixed));
499                        }
500                    }
501                }
502                (!out.is_empty()).then_some(out)
503            }
504            _ => None,
505        }
506    }
507
508    /// Seed a standalone demo sketch (S0 milestone): a fully-constrained 20×12
509    /// rectangle grounded at the origin PLUS a free (unconstrained) circle beside
510    /// it, both on the XY plane. The mix proves the pipeline end to end — the
511    /// rectangle solves to `locked` (white), the circle stays `movable` (blue),
512    /// and the sketch reports `dof = 4` (the circle's four free coordinates).
513    pub fn seed_rectangle_circle() -> Result<Self, String> {
514        Self::new(seed_doc(), PlaneFrame::xy())
515    }
516}
517
518/// The seed document consumed by [`SketchSession::seed_rectangle_circle`].
519fn seed_doc() -> SketchDoc {
520    let value = json!({
521        "points": [
522            // rectangle corners (p0 grounded at the origin)
523            { "id": 0, "x": 0.0,  "y": 0.0,  "fixed": false, "construction": false, "externalReference": false },
524            { "id": 1, "x": 20.0, "y": 0.0,  "fixed": false, "construction": false, "externalReference": false },
525            { "id": 2, "x": 20.0, "y": 12.0, "fixed": false, "construction": false, "externalReference": false },
526            { "id": 3, "x": 0.0,  "y": 12.0, "fixed": false, "construction": false, "externalReference": false },
527            // free circle (center + radius point), unconstrained -> 4 DOF, movable
528            { "id": 4, "x": 34.0, "y": 6.0,  "fixed": false, "construction": false, "externalReference": false },
529            { "id": 5, "x": 40.0, "y": 6.0,  "fixed": false, "construction": false, "externalReference": false }
530        ],
531        "geometries": [
532            { "id": 10, "type": "line",   "points": [0, 1], "construction": false },
533            { "id": 11, "type": "line",   "points": [1, 2], "construction": false },
534            { "id": 12, "type": "line",   "points": [2, 3], "construction": false },
535            { "id": 13, "type": "line",   "points": [3, 0], "construction": false },
536            { "id": 20, "type": "circle", "points": [4, 5], "construction": false }
537        ],
538        "constraints": [
539            { "id": 0, "type": "⏚", "points": [0] },
540            { "id": 1, "type": "━", "points": [0, 1] },
541            { "id": 2, "type": "⟺", "points": [0, 1], "value": 20.0 },
542            { "id": 3, "type": "│", "points": [1, 2] },
543            { "id": 4, "type": "⟺", "points": [1, 2], "value": 12.0 },
544            { "id": 5, "type": "━", "points": [2, 3] },
545            { "id": 6, "type": "│", "points": [3, 0] }
546        ]
547    });
548    serde_json::from_value(value).expect("seed sketch doc is valid")
549}
550
551// --- S2 entity-ref convention --------------------------------------------------
552//
553// Hover + selection both use ONE ref shape: `{"kind":"point"|"geometry","id":<id>}`
554// where `<id>` is the raw doc id `Value` (a number in practice). Two refs are equal
555// when their kinds match and their ids agree under the solver's [`id_key`] identity
556// (so numeric `4` and string `"4"` are the same entity).
557
558/// Build a `{"kind":"point","id":<id>}` entity ref.
559/// Whether `p` lies in the convex quad (either winding).
560fn quad_contains(quad: &[(f64, f64); 4], p: (f64, f64)) -> bool {
561    let mut sign = 0.0_f64;
562    for i in 0..4 {
563        let (a, b) = (quad[i], quad[(i + 1) % 4]);
564        let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
565        if cross.abs() < 1e-12 {
566            continue;
567        }
568        if sign == 0.0 {
569            sign = cross.signum();
570        } else if cross.signum() != sign {
571            return false;
572        }
573    }
574    true
575}
576
577/// Whether segment `a`-`b` crosses an edge of the quad.
578fn quad_crosses(quad: &[(f64, f64); 4], a: (f64, f64), b: (f64, f64)) -> bool {
579    let orient = |p: (f64, f64), q: (f64, f64), r: (f64, f64)| (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0);
580    (0..4).any(|i| {
581        let (c, d) = (quad[i], quad[(i + 1) % 4]);
582        let (o1, o2) = (orient(a, b, c), orient(a, b, d));
583        let (o3, o4) = (orient(c, d, a), orient(c, d, b));
584        o1 * o2 < 0.0 && o3 * o4 < 0.0
585    })
586}
587
588pub fn point_ref(id: &Value) -> Value {
589    json!({ "kind": "point", "id": id.clone() })
590}
591
592/// Build a `{"kind":"geometry","id":<id>}` entity ref.
593pub fn geometry_ref(id: &Value) -> Value {
594    json!({ "kind": "geometry", "id": id.clone() })
595}
596
597/// Build a `{"kind":"constraint","id":<id>}` entity ref — a CONSTRAINT is selectable
598/// like a point/geometry (picked near its glyph or dimension leader) so it can be
599/// emphasized + deleted; deleting it drops only the constraint, never its geometry.
600pub fn constraint_ref(id: &Value) -> Value {
601    json!({ "kind": "constraint", "id": id.clone() })
602}
603
604/// Whether two entity refs name the same entity (same `kind`, same `id` under
605/// [`id_key`]).
606pub fn refs_equal(a: &Value, b: &Value) -> bool {
607    a.get("kind") == b.get("kind") && a.get("id").map(id_key) == b.get("id").map(id_key)
608}
609
610/// Whether two optional entity refs are equal (both absent, or both present and
611/// [`refs_equal`]) — the hover-changed test.
612pub fn entity_ref_eq(a: Option<&Value>, b: Option<&Value>) -> bool {
613    match (a, b) {
614        (None, None) => true,
615        (Some(x), Some(y)) => refs_equal(x, y),
616        _ => false,
617    }
618}
619