BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! `SketchSession` — the in-flight editing/display state for one sketch.
//!
//! S0 holds the essentials the read-only overlay needs — the solved
//! [`SketchDoc`], the plane [`PlaneFrame`] it lives on, and the last
//! [`SketchDiagnostics`] (DOF + mobility) — plus stub fields the interactive
//! slices (S2 picking, S3 tools, S5 dimensions) will fill in. Constructing a
//! session solves the doc once; [`resolve`](Self::resolve) re-solves after edits.

use serde_json::{json, Value};

use super::doc::{id_key, SketchDiagnostics, SketchDoc};
use super::tessellate::{self, SketchTessellation};
use super::{solve, PlaneFrame};
use crate::style::SketchColors;

/// One sketch's live session: solved document + plane + diagnostics, with stubs
/// for the interaction state later slices own.
pub struct SketchSession {
    /// The solved sketch (points carry solved coordinates).
    pub doc: SketchDoc,
    /// The plane the sketch's `(u, v)` coordinates are embedded in.
    pub plane: PlaneFrame,
    /// The last solve's read-only diagnostics (DOF, over/under status, mobility).
    pub diagnostics: SketchDiagnostics,

    // --- interaction state ---------------------------------------------------
    /// Selected entities (S2) — a set of entity refs
    /// (`{"kind":"point"|"geometry","id":<id>}`; see [`point_ref`]/[`geometry_ref`]).
    pub selection: Vec<Value>,
    /// The entity ref currently under the cursor (S2), or `None`.
    pub hovered: Option<Value>,
    /// The active drawing tool (S3). Unused in S0.
    pub tool: Option<String>,
    /// Persisted dimension label offsets (S5). Unused in S0.
    pub dim_offsets: serde_json::Map<String, Value>,
    /// The overlay color palette — a live [`SketchColors`] view of the display
    /// settings (`RenderSettings::sketch_colors`). The engine sets this on entry and
    /// re-syncs it when the settings change; every overlay builder reads from here so
    /// the sketch colors are managed in the settings like the rest of the display.
    /// Defaults to [`SketchColors::default`] so a session built in a test (or before
    /// the engine syncs) renders the standard theme.
    pub colors: SketchColors,
    /// User-tunable solver knobs (the Solver Settings panel). Read by every
    /// [`resolve`](Self::resolve); default reproduces the historical solve.
    pub solver_settings: solve::SketchSolverSettings,
}

impl SketchSession {
    /// Build a session from a (possibly unsolved) doc + plane, solving it once.
    pub fn new(doc: SketchDoc, plane: PlaneFrame) -> Result<Self, String> {
        let (solved, diagnostics) = solve::solve(&doc)?;
        Ok(Self {
            doc: solved,
            plane,
            diagnostics,
            selection: Vec::new(),
            hovered: None,
            tool: None,
            dim_offsets: serde_json::Map::new(),
            colors: SketchColors::default(),
            solver_settings: solve::SketchSolverSettings::default(),
        })
    }

    /// Re-solve the current doc, refreshing coordinates + diagnostics in place,
    /// honoring the session's [`solver_settings`](Self::solver_settings).
    pub fn resolve(&mut self) -> Result<(), String> {
        let (solved, diagnostics) = solve::solve_with(&self.doc, &self.solver_settings)?;
        self.doc = solved;
        self.diagnostics = diagnostics;
        Ok(())
    }

    /// The `set_overlay` JSON for this solved sketch (see
    /// [`tessellate::overlay_json`]). `world_per_pixel` sizes construction dashes.
    pub fn overlay_json(&self, world_per_pixel: f64) -> String {
        tessellate::overlay_json(
            &self.doc,
            &self.diagnostics,
            &self.plane,
            world_per_pixel,
            &self.colors,
        )
    }

    /// The flat overlay buffers (for tests / verification stats).
    pub fn tessellation(&self, world_per_pixel: f64) -> SketchTessellation {
        tessellate::tessellate(
            &self.doc,
            &self.diagnostics,
            &self.plane,
            world_per_pixel,
            &self.colors,
        )
    }

    /// The `set_overlay` JSON with the live hover + selection colored in (S2). Empty
    /// hover + selection reproduce [`overlay_json`](Self::overlay_json) exactly.
    pub fn overlay_json_with_state(&self, world_per_pixel: f64) -> String {
        tessellate::overlay_json_with_state(
            &self.doc,
            &self.diagnostics,
            &self.plane,
            world_per_pixel,
            &self.colors,
            self.hovered.as_ref(),
            &self.selection,
        )
    }

    /// The `set_overlay` JSON for the `sketch-dim-leaders` group (S5): the per-type
    /// leader/arrow segments for every dimensional constraint, offset by its stored
    /// `{du, dv}` (see [`dimensions`](super::dimensions)). Always emitted (empty when
    /// the sketch has no dimensions) so a stale group clears on the next refresh.
    pub fn dim_leaders_overlay_json(&self, world_per_pixel: f64) -> String {
        super::dimensions::dimension_leaders_overlay_json(
            &self.doc,
            &self.plane,
            &self.dim_offsets,
            world_per_pixel,
            &self.colors,
        )
    }

    /// Like [`dim_leaders_overlay_json`](Self::dim_leaders_overlay_json) but emphasizes
    /// the live hovered / selected dimensional constraint (amber selected, light-blue
    /// hovered — matching points/geometry). Used by the interactive overlay refresh.
    pub fn dim_leaders_overlay_json_with_state(&self, world_per_pixel: f64) -> String {
        super::dimensions::dimension_leaders_overlay_json_with_state(
            &self.doc,
            &self.plane,
            &self.dim_offsets,
            world_per_pixel,
            &self.colors,
            self.hovered.as_ref(),
            &self.selection,
        )
    }

    /// The `set_overlay` JSON for the `sketch-constraint-glyphs` group (S6c): the small
    /// screen-constant line-art marks for every GEOMETRIC (non-dimensional) constraint
    /// — perpendicular, parallel, horizontal/vertical, coincident, equal, … (see
    /// [`constraint_glyphs`](super::constraint_glyphs)). Painted in the shared
    /// constraint green. Always emitted (empty when the sketch has no geometric
    /// constraints) so a stale group clears on the next refresh.
    pub fn constraint_glyphs_overlay_json(&self, world_per_pixel: f64) -> String {
        super::constraint_glyphs::constraint_glyphs_overlay_json(
            &self.doc,
            &self.plane,
            world_per_pixel,
            &self.colors,
        )
    }

    /// Like [`constraint_glyphs_overlay_json`](Self::constraint_glyphs_overlay_json) but
    /// emphasizes the live hovered / selected geometric constraint (amber selected,
    /// light-blue hovered — matching points/geometry). Used by the interactive refresh.
    pub fn constraint_glyphs_overlay_json_with_state(&self, world_per_pixel: f64) -> String {
        super::constraint_glyphs::constraint_glyphs_overlay_json_with_state(
            &self.doc,
            &self.plane,
            world_per_pixel,
            &self.colors,
            self.hovered.as_ref(),
            &self.selection,
        )
    }

    /// The per-constraint dimension labels (S5): one [`DimLabel`](super::dimensions::DimLabel)
    /// per dimensional constraint, each anchored in world space (`plane.to_world` of
    /// the label uv + its stored offset). brep-app projects `world` → screen and
    /// draws the editable value text there.
    pub fn dimension_labels(&self, world_per_pixel: f64) -> Vec<super::dimensions::DimLabel> {
        super::dimensions::dimension_labels(
            &self.doc,
            &self.plane,
            &self.dim_offsets,
            world_per_pixel,
        )
    }

    /// The `set_overlay` JSON for the active draw tool's in-progress rubber-band
    /// preview (S3a): the dim dashed geometry from the `pending` anchor points (their
    /// ids, resolved to uv against the live doc) toward `hover_uv`, plus the raw
    /// freehand `stroke` (S6b-3) as a dim solid polyline while a handdraw drag is live.
    /// Always a `sketch-preview` group (empty when there is nothing to preview yet).
    pub fn preview_overlay_json(
        &self,
        world_per_pixel: f64,
        pending: &[Value],
        hover_uv: Option<(f64, f64)>,
        stroke: &[(f64, f64)],
    ) -> String {
        let pending_uv: Vec<[f64; 2]> = pending
            .iter()
            .filter_map(|id| self.doc.point(id).map(|p| [p.x, p.y]))
            .collect();
        let stroke_uv: Vec<[f64; 2]> = stroke.iter().map(|&(u, v)| [u, v]).collect();
        tessellate::preview_overlay_json(
            self.tool.as_deref(),
            &pending_uv,
            hover_uv,
            &stroke_uv,
            &self.plane,
            world_per_pixel,
            &self.colors,
        )
    }

    // --- S2 hover / selection state ------------------------------------------

    /// Whether `entity_ref` is in the selection set (matched via [`refs_equal`]).
    pub fn is_selected(&self, entity_ref: &Value) -> bool {
        self.selection.iter().any(|r| refs_equal(r, entity_ref))
    }

    /// Toggle `entity_ref` in the selection set: remove it if present, else add it.
    pub fn toggle_selection(&mut self, entity_ref: Value) {
        if let Some(pos) = self.selection.iter().position(|r| refs_equal(r, &entity_ref)) {
            self.selection.remove(pos);
        } else {
            self.selection.push(entity_ref);
        }
    }

    /// Clear the selection set.
    pub fn clear_selection(&mut self) {
        self.selection.clear();
    }

    /// Set (or clear) the hovered entity ref.
    pub fn set_hover(&mut self, entity_ref: Option<Value>) {
        self.hovered = entity_ref;
    }

    // --- S2 hit-testing ------------------------------------------------------

    /// The entity ref nearest to plane coordinate `(u, v)` within `radius` — a
    /// POINT wins over geometry when one is in range (points take priority), else
    /// the nearest geometry whose polyline passes within `radius`. Construction
    /// geometry is included (it is pickable). `None` when nothing is in range.
    pub fn pick_entity(&self, u: f64, v: f64, radius: f64) -> Option<Value> {
        // Points first (priority over geometry under the cursor).
        let mut best_pt: Option<(f64, &Value)> = None;
        for p in &self.doc.points {
            let d = ((p.x - u).powi(2) + (p.y - v).powi(2)).sqrt();
            if d <= radius && best_pt.map_or(true, |(bd, _)| d < bd) {
                best_pt = Some((d, &p.id));
            }
        }
        if let Some((_, id)) = best_pt {
            return Some(point_ref(id));
        }

        // Else the nearest geometry polyline within radius.
        let mut best_geo: Option<(f64, &Value)> = None;
        for g in &self.doc.geometries {
            let poly = tessellate::geometry_polyline_uv(g, &self.doc);
            if poly.len() < 2 {
                continue;
            }
            let mut dmin = f64::INFINITY;
            for seg in poly.windows(2) {
                let d = point_segment_distance(u, v, seg[0], seg[1]);
                if d < dmin {
                    dmin = d;
                }
            }
            if dmin <= radius && best_geo.map_or(true, |(bd, _)| dmin < bd) {
                best_geo = Some((dmin, &g.id));
            }
        }
        best_geo.map(|(_, id)| geometry_ref(id))
    }

    /// The CONSTRAINT nearest to `(u, v)` within `radius` — a `constraint` entity ref
    /// (`{"kind":"constraint","id":<id>}`), or `None`. A GEOMETRIC constraint is picked
    /// near its glyph line-art (the exact segments [`constraint_glyphs`] draws); a
    /// DIMENSIONAL one near its leader/arrow lines (NOT its value label — the label is
    /// the egui value-editor affordance). Solver-internal `temporary` helpers are never
    /// pickable. `world_per_pixel` sizes the screen-constant glyph/leader placement (so
    /// picking tracks what is drawn). The CALLER enforces priority: points > geometry >
    /// constraint (see `EngineState::sketch_entity_at`), so a glyph over a point never
    /// shadows the point.
    ///
    /// [`constraint_glyphs`]: super::constraint_glyphs
    pub fn pick_constraint(&self, u: f64, v: f64, radius: f64, world_per_pixel: f64) -> Option<Value> {
        let mut best: Option<(f64, &Value)> = None;
        for c in &self.doc.constraints {
            if c.temporary() {
                continue;
            }
            let Some(id) = c.raw.get("id") else { continue };
            // A constraint contributes glyph segments (geometric) XOR leader segments
            // (dimensional); measure the cursor against whichever it draws.
            let mut dmin = f64::INFINITY;
            for (a, b) in
                super::constraint_glyphs::constraint_glyph_segments(c, &self.doc, world_per_pixel)
            {
                let d = point_segment_distance(u, v, a, b);
                if d < dmin {
                    dmin = d;
                }
            }
            if let Some(segments) = super::dimensions::constraint_dim_segments(
                c,
                &self.doc,
                &self.dim_offsets,
                world_per_pixel,
            ) {
                for (a, b) in segments {
                    let d = point_segment_distance(u, v, a, b);
                    if d < dmin {
                        dmin = d;
                    }
                }
            }
            if dmin <= radius && best.map_or(true, |(bd, _)| dmin < bd) {
                best = Some((dmin, id));
            }
        }
        best.map(|(_, id)| constraint_ref(id))
    }

    /// The nearest DRAGGABLE point to `(u, v)` within `radius` (its id + authored
    /// `fixed` flag), or `None`. A point is draggable only if the solver reports it
    /// movable (a locked / grounded point has no free coordinates to drag), so a
    /// drag on a fully-constrained point falls through to a camera orbit.
    pub fn pick_draggable_point(&self, u: f64, v: f64, radius: f64) -> Option<(Value, bool)> {
        let mut best: Option<(f64, &super::doc::SketchPoint)> = None;
        for p in &self.doc.points {
            let movable = self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed);
            if !movable {
                continue;
            }
            let d = ((p.x - u).powi(2) + (p.y - v).powi(2)).sqrt();
            if d <= radius && best.map_or(true, |(bd, _)| d < bd) {
                best = Some((d, p));
            }
        }
        best.map(|(_, p)| (p.id.clone(), p.fixed))
    }

    /// The point-set to DRAG for a hovered entity ref (`{"kind","id"}`) — the grab
    /// path grabs exactly what's highlighted rather than re-picking at egui's
    /// offset drag-start position. A `"point"` ref → that point iff it is MOVABLE;
    /// a `"geometry"` ref → ALL of its (deduped) points when at least one is movable
    /// (a rigid translate). Each entry is `(id, orig_x, orig_y, orig_fixed)`. `None`
    /// for a locked point, a fully-locked geometry, or a stale/unknown ref (the
    /// caller then falls through to a camera gesture — it never drags something the
    /// user is not pointing at).
    pub fn drag_points_from_ref(&self, entity_ref: &Value) -> Option<Vec<(Value, f64, f64, bool)>> {
        let kind = entity_ref.get("kind").and_then(Value::as_str)?;
        let id = entity_ref.get("id")?;
        match kind {
            "point" => {
                let p = self.doc.point(id)?;
                let movable = self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed);
                movable.then(|| vec![(p.id.clone(), p.x, p.y, p.fixed)])
            }
            "geometry" => {
                // Raw doc ids compare via `id_key` (numeric identity) — NOT
                // `refs_equal`, which is for `{"kind","id"}` entity refs and treats
                // every bare id as equal.
                let g = self
                    .doc
                    .geometries
                    .iter()
                    .find(|g| id_key(&g.id) == id_key(id))?;
                let mut out: Vec<(Value, f64, f64, bool)> = Vec::new();
                let mut any_movable = false;
                for pid in &g.points {
                    // A closed polyline repeats its start id — dedupe so a point is
                    // pinned once.
                    if out.iter().any(|(pt_id, ..)| id_key(pt_id) == id_key(pid)) {
                        continue;
                    }
                    if let Some(p) = self.doc.point(pid) {
                        any_movable |= self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed);
                        out.push((p.id.clone(), p.x, p.y, p.fixed));
                    }
                }
                (any_movable && !out.is_empty()).then_some(out)
            }
            _ => None,
        }
    }

    /// Seed a standalone demo sketch (S0 milestone): a fully-constrained 20×12
    /// rectangle grounded at the origin PLUS a free (unconstrained) circle beside
    /// it, both on the XY plane. The mix proves the pipeline end to end — the
    /// rectangle solves to `locked` (white), the circle stays `movable` (blue),
    /// and the sketch reports `dof = 4` (the circle's four free coordinates).
    pub fn seed_rectangle_circle() -> Result<Self, String> {
        Self::new(seed_doc(), PlaneFrame::xy())
    }
}

/// The seed document consumed by [`SketchSession::seed_rectangle_circle`].
fn seed_doc() -> SketchDoc {
    let value = json!({
        "points": [
            // rectangle corners (p0 grounded at the origin)
            { "id": 0, "x": 0.0,  "y": 0.0,  "fixed": false, "construction": false, "externalReference": false },
            { "id": 1, "x": 20.0, "y": 0.0,  "fixed": false, "construction": false, "externalReference": false },
            { "id": 2, "x": 20.0, "y": 12.0, "fixed": false, "construction": false, "externalReference": false },
            { "id": 3, "x": 0.0,  "y": 12.0, "fixed": false, "construction": false, "externalReference": false },
            // free circle (center + radius point), unconstrained -> 4 DOF, movable
            { "id": 4, "x": 34.0, "y": 6.0,  "fixed": false, "construction": false, "externalReference": false },
            { "id": 5, "x": 40.0, "y": 6.0,  "fixed": false, "construction": false, "externalReference": false }
        ],
        "geometries": [
            { "id": 10, "type": "line",   "points": [0, 1], "construction": false },
            { "id": 11, "type": "line",   "points": [1, 2], "construction": false },
            { "id": 12, "type": "line",   "points": [2, 3], "construction": false },
            { "id": 13, "type": "line",   "points": [3, 0], "construction": false },
            { "id": 20, "type": "circle", "points": [4, 5], "construction": false }
        ],
        "constraints": [
            { "id": 0, "type": "", "points": [0] },
            { "id": 1, "type": "", "points": [0, 1] },
            { "id": 2, "type": "", "points": [0, 1], "value": 20.0 },
            { "id": 3, "type": "", "points": [1, 2] },
            { "id": 4, "type": "", "points": [1, 2], "value": 12.0 },
            { "id": 5, "type": "", "points": [2, 3] },
            { "id": 6, "type": "", "points": [3, 0] }
        ]
    });
    serde_json::from_value(value).expect("seed sketch doc is valid")
}

// --- S2 entity-ref convention --------------------------------------------------
//
// Hover + selection both use ONE ref shape: `{"kind":"point"|"geometry","id":<id>}`
// where `<id>` is the raw doc id `Value` (a number in practice). Two refs are equal
// when their kinds match and their ids agree under the solver's [`id_key`] identity
// (so numeric `4` and string `"4"` are the same entity).

/// Build a `{"kind":"point","id":<id>}` entity ref.
pub fn point_ref(id: &Value) -> Value {
    json!({ "kind": "point", "id": id.clone() })
}

/// Build a `{"kind":"geometry","id":<id>}` entity ref.
pub fn geometry_ref(id: &Value) -> Value {
    json!({ "kind": "geometry", "id": id.clone() })
}

/// Build a `{"kind":"constraint","id":<id>}` entity ref — a CONSTRAINT is selectable
/// like a point/geometry (picked near its glyph or dimension leader) so it can be
/// emphasized + deleted; deleting it drops only the constraint, never its geometry.
pub fn constraint_ref(id: &Value) -> Value {
    json!({ "kind": "constraint", "id": id.clone() })
}

/// Whether two entity refs name the same entity (same `kind`, same `id` under
/// [`id_key`]).
pub fn refs_equal(a: &Value, b: &Value) -> bool {
    a.get("kind") == b.get("kind") && a.get("id").map(id_key) == b.get("id").map(id_key)
}

/// Whether two optional entity refs are equal (both absent, or both present and
/// [`refs_equal`]) — the hover-changed test.
pub fn entity_ref_eq(a: Option<&Value>, b: Option<&Value>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(x), Some(y)) => refs_equal(x, y),
        _ => false,
    }
}

/// Euclidean distance from point `(px, py)` to the segment `a`–`b` (all in plane
/// `(u, v)` coordinates) — the geometry hit-test metric.
fn point_segment_distance(px: f64, py: f64, a: [f64; 2], b: [f64; 2]) -> f64 {
    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
    let len2 = dx * dx + dy * dy;
    let t = if len2 <= 1e-18 {
        0.0
    } else {
        (((px - a[0]) * dx + (py - a[1]) * dy) / len2).clamp(0.0, 1.0)
    };
    let (cx, cy) = (a[0] + t * dx, a[1] + t * dy);
    ((px - cx).powi(2) + (py - cy).powi(2)).sqrt()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn refs_equal_matches_kind_and_id_under_id_key() {
        assert!(refs_equal(&point_ref(&json!(4)), &point_ref(&json!(4.0))));
        assert!(!refs_equal(&point_ref(&json!(4)), &geometry_ref(&json!(4))));
        assert!(!refs_equal(&point_ref(&json!(4)), &point_ref(&json!(5))));
        assert!(entity_ref_eq(None, None));
        assert!(!entity_ref_eq(Some(&point_ref(&json!(4))), None));
        assert!(entity_ref_eq(
            Some(&point_ref(&json!(4))),
            Some(&point_ref(&json!(4)))
        ));
    }

    #[test]
    fn toggle_and_is_selected_add_then_remove() {
        let mut s = SketchSession::seed_rectangle_circle().expect("seed");
        let r = point_ref(&json!(4));
        assert!(!s.is_selected(&r));
        s.toggle_selection(r.clone());
        assert!(s.is_selected(&r));
        assert_eq!(s.selection.len(), 1);
        s.toggle_selection(r.clone());
        assert!(!s.is_selected(&r));
        assert_eq!(s.selection.len(), 0);
    }

    #[test]
    fn pick_entity_prefers_the_nearest_point_within_radius() {
        let s = SketchSession::seed_rectangle_circle().expect("seed");
        // Right on the free circle center (id 4 at (34, 6)).
        let hit = s.pick_entity(34.1, 6.05, 0.5).expect("point hit");
        assert!(refs_equal(&hit, &point_ref(&json!(4))), "hit = {hit}");
    }

    #[test]
    fn pick_entity_returns_none_outside_radius() {
        let s = SketchSession::seed_rectangle_circle().expect("seed");
        // Far from every point AND every edge.
        assert!(s.pick_entity(100.0, 100.0, 0.5).is_none());
    }

    #[test]
    fn drag_points_from_ref_resolves_point_and_geometry() {
        let s = SketchSession::seed_rectangle_circle().expect("seed");
        // A MOVABLE point (the free circle center p4) → just itself.
        let pt = s
            .drag_points_from_ref(&point_ref(&json!(4)))
            .expect("movable point grabs");
        assert_eq!(pt.len(), 1);
        assert!(refs_equal(&point_ref(&pt[0].0), &point_ref(&json!(4))));
        assert!(!pt[0].3, "p4 is not fixed");
        // A LOCKED point (grounded corner p0) → None: the drag must fall to the camera,
        // never steal a nearby unhighlighted point.
        assert!(s.drag_points_from_ref(&point_ref(&json!(0))).is_none());
        // A geometry with movable points (the free circle 20 → points 4 + 5) → both,
        // for a rigid translate.
        let circle = s
            .drag_points_from_ref(&geometry_ref(&json!(20)))
            .expect("movable geometry grabs");
        assert_eq!(circle.len(), 2, "the circle translates both its points");
        // A fully-locked geometry (rectangle edge 10 → grounded points 0,1) → None.
        assert!(s.drag_points_from_ref(&geometry_ref(&json!(10))).is_none());
        // A stale / unknown ref → None (a hover left dangling after delete/undo).
        assert!(s.drag_points_from_ref(&point_ref(&json!(999))).is_none());
        assert!(s.drag_points_from_ref(&geometry_ref(&json!(999))).is_none());
    }

    #[test]
    fn pick_entity_falls_through_to_geometry_mid_segment() {
        let s = SketchSession::seed_rectangle_circle().expect("seed");
        // Mid the bottom edge (line id 10, (0,0)->(20,0)); nearest point is a
        // corner 10 units away, so with a tight radius geometry wins.
        let hit = s.pick_entity(10.0, 0.05, 0.2).expect("geometry hit");
        assert!(refs_equal(&hit, &geometry_ref(&json!(10))), "hit = {hit}");
    }

    #[test]
    fn pick_draggable_point_skips_locked_points() {
        let s = SketchSession::seed_rectangle_circle().expect("seed");
        // The grounded corner p0 (locked) is not draggable.
        assert!(s.pick_draggable_point(0.0, 0.0, 0.5).is_none());
        // The free circle center p4 is.
        let (id, fixed) = s.pick_draggable_point(34.0, 6.0, 0.5).expect("draggable");
        assert!(id == json!(4) && !fixed, "id = {id}, fixed = {fixed}");
    }

    #[test]
    fn pick_constraint_finds_glyph_and_leader_but_not_far() {
        // A single horizontal line (0,0)-(10,0) with a horizontal geometric constraint
        // (id 0, glyph pushed off the midpoint) + a distance dim (id 1, leader above).
        let doc: crate::sketch::SketchDoc = serde_json::from_value(json!({
            "points": [
                { "id": 0, "x": 0.0, "y": 0.0, "fixed": true },
                { "id": 1, "x": 10.0, "y": 0.0 }
            ],
            "geometries": [{ "id": 10, "type": "line", "points": [0, 1] }],
            "constraints": [
                { "id": 0, "type": "", "points": [0, 1] },
                { "id": 1, "type": "", "points": [0, 1], "value": 10.0 }
            ]
        }))
        .expect("doc");
        let s = SketchSession::new(doc, PlaneFrame::xy()).expect("session");
        let (wpp, radius) = (0.05, 0.3);
        // Near the horizontal glyph (midpoint (5,0) pushed off +v ~0.77) → a constraint.
        let hit = s.pick_constraint(5.0, 0.77, radius, wpp).expect("glyph hit");
        assert_eq!(hit["kind"], "constraint", "glyph pick is a constraint ref");
        // Near the distance-dim leader line (default offset ~+v 1.0 at the midpoint).
        let hit2 = s.pick_constraint(5.0, 1.0, radius, wpp).expect("leader hit");
        assert_eq!(hit2["kind"], "constraint", "leader pick is a constraint ref");
        // Far from every glyph + leader → None.
        assert!(s.pick_constraint(5.0, 20.0, radius, wpp).is_none(), "nothing far off");
    }

    #[test]
    fn custom_settings_color_reaches_the_tessellation() {
        // A non-default sketch color set on the session (as the engine does from
        // `RenderSettings::sketch_colors`) actually paints the overlay buffer: a
        // custom movable color lands on the free (movable) circle center point.
        let mut s = SketchSession::seed_rectangle_circle().expect("seed");
        s.colors = crate::style::RenderSettings::default().sketch_colors();
        s.colors.movable = 0x123456;
        let tess = s.tessellation(0.05);
        // The movable circle center (id 4) carries the custom movable color.
        let p4 = s.doc.point(&json!(4)).unwrap();
        let idx = tess
            .point_positions
            .chunks(3)
            .position(|c| (c[0] - p4.x as f32).abs() < 1e-4 && (c[1] - p4.y as f32).abs() < 1e-4)
            .expect("circle center among overlay points");
        let col = &tess.point_colors[idx * 3..idx * 3 + 3];
        assert!((col[0] - 0x12 as f32 / 255.0).abs() < 1e-3, "r wrong: {col:?}");
        assert!((col[1] - 0x34 as f32 / 255.0).abs() < 1e-3, "g wrong: {col:?}");
        assert!((col[2] - 0x56 as f32 / 255.0).abs() < 1e-3, "b wrong: {col:?}");
    }

    #[test]
    fn overlay_state_colors_selected_amber_over_mobility() {
        let mut s = SketchSession::seed_rectangle_circle().expect("seed");
        s.toggle_selection(point_ref(&json!(4)));
        s.set_hover(Some(point_ref(&json!(5))));
        let tess = tessellate::tessellate_with_state(
            &s.doc,
            &s.diagnostics,
            &s.plane,
            0.05,
            &s.colors,
            s.hovered.as_ref(),
            &s.selection,
        );
        // Point 4 (selected) is amber (0xffa500); point 5 (hovered) is light blue.
        let p4 = s.doc.point(&json!(4)).unwrap();
        let idx4 = tess
            .point_positions
            .chunks(3)
            .position(|c| (c[0] - p4.x as f32).abs() < 1e-4 && (c[1] - p4.y as f32).abs() < 1e-4)
            .expect("p4 among points");
        let c4 = &tess.point_colors[idx4 * 3..idx4 * 3 + 3];
        assert!((c4[0] - 0xff as f32 / 255.0).abs() < 1e-3, "selected not amber: {c4:?}");
        assert!((c4[1] - 0xa5 as f32 / 255.0).abs() < 1e-3, "selected not amber: {c4:?}");
    }
}