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
//! Geometric-constraint glyphs (S6c) — small, screen-constant line-art marks drawn
//! on the sketch overlay next to the geometry a NON-dimensional constraint acts on.
//!
//! The dimensional constraints (`⟺` distance, `↥` point-line, `∠` angle, and the
//! radial `⟺` radius/diameter) already draw leaders + value labels via
//! [`super::dimensions`]; this module is the counterpart for the GEOMETRIC
//! constraints, which the previous app annotated with tiny badge icons and the engine had
//! no visualization for. Each constraint contributes a little icon assembled from
//! line segments (the overlay channel draws lines, so glyphs are line art, not text):
//!
//! * `━` horizontal / `│` vertical — a dash offset off the segment midpoint,
//! * `∥` parallel — a chevron on each of the two lines,
//! * `⟂` perpendicular — a right-angle corner at the shared vertex, oriented to the
//!   two edges,
//! * `≡` coincident — a small square at the shared point,
//! * `⇌` equal-distance / `⊜` equal-radius — `=` ticks on each involved edge/rim,
//! * `⏛` point-on-line, `⋯` midpoint, `⋰` collinear, `⌒` tangent, `◎` concentric,
//!   `⋈` symmetric, `⏚` ground — each a small distinctive mark at a sensible anchor.
//!
//! Everything is sized by `world_per_pixel` so the glyphs stay a constant on-screen
//! size (like the sketch points + dimension arrowheads), and is painted in the shared
//! constraint green (`SketchColors::constraint`, from the display settings) so it reads
//! apart from the blue/white geometry. Solver-internal `temporary` constraints (injected mid-drag)
//! and the dimensional constraints are skipped. The output rides in its own overlay
//! group so it upserts/clears independently of geometry / points / preview / leaders.

use std::collections::HashMap;
use std::f64::consts::PI;

use serde_json::Value;

use super::dimensions::line_intersection;
use super::doc::{id_key, SketchConstraint, SketchDoc, SketchPoint};
use super::PlaneFrame;
use crate::style::SketchColors;

/// The constraint-glyph overlay group name (its own group so it upserts/clears
/// independently of the other sketch overlay groups).
pub const OVERLAY_CONSTRAINT_GLYPHS: &str = "sketch-constraint-glyphs";

/// The glyph "half size" in CSS px — a glyph spans roughly `2 × GLYPH_PX`. Sized a
/// touch larger than the 8px sketch point so the marks are legible without crowding.
const GLYPH_PX: f64 = 7.0;

/// Half the offset (in glyph half-sizes) that pushes a midpoint mark off its segment
/// so the glyph does not sit on top of the line it annotates.
const OFFSET_FACTOR: f64 = 2.2;

/// Resolve a constraint's point id to its solved plane `(u, v)`.
fn get<'a>(by_id: &HashMap<String, &'a SketchPoint>, id: &Value) -> Option<[f64; 2]> {
    by_id.get(&id_key(id)).map(|p| [p.x, p.y])
}

/// The screen-constant glyph scale (a glyph half-size in plane units) at this zoom.
fn glyph_scale(wpp: f64) -> f64 {
    (wpp * GLYPH_PX).max(0.05)
}

/// Whether a constraint contributes NO glyph here — the dimensional constraints
/// (owned by [`super::dimensions`]) and solver-internal `temporary` helpers.
fn is_dimensional_or_temporary(c: &SketchConstraint) -> bool {
    if c.temporary() {
        return true;
    }
    matches!(c.ctype(), Some("") | Some("") | Some(""))
}

/// Push a template — a set of local-frame strokes (`x`/`y` in roughly `[-1, 1]`) —
/// placed at `anchor`, scaled by `scale`, rotated by `rot` radians.
fn stamp(
    out: &mut Vec<([f64; 2], [f64; 2])>,
    anchor: [f64; 2],
    scale: f64,
    rot: f64,
    strokes: &[&[[f64; 2]]],
) {
    let (c, s) = (rot.cos(), rot.sin());
    let map = |p: [f64; 2]| {
        let (x, y) = (p[0] * scale, p[1] * scale);
        [anchor[0] + x * c - y * s, anchor[1] + x * s + y * c]
    };
    for stroke in strokes {
        for w in stroke.windows(2) {
            out.push((map(w[0]), map(w[1])));
        }
    }
}

// --- local-frame stroke templates ------------------------------------------------

const T_DASH_H: [[f64; 2]; 2] = [[-1.0, 0.0], [1.0, 0.0]]; // — horizontal dash
const T_DASH_V: [[f64; 2]; 2] = [[0.0, -1.0], [0.0, 1.0]]; // │ vertical dash
const T_CHEV: [[f64; 2]; 3] = [[-0.5, -0.8], [0.5, 0.0], [-0.5, 0.8]]; // › along +x
const T_EQ_A: [[f64; 2]; 2] = [[-0.8, -0.32], [0.8, -0.32]]; // = upper bar
const T_EQ_B: [[f64; 2]; 2] = [[-0.8, 0.32], [0.8, 0.32]]; // = lower bar
const T_SQUARE: [[f64; 2]; 5] = [
    [-0.8, -0.8],
    [0.8, -0.8],
    [0.8, 0.8],
    [-0.8, 0.8],
    [-0.8, -0.8],
]; // ▢ coincident
const T_DIAMOND: [[f64; 2]; 5] = [
    [0.0, -1.0],
    [1.0, 0.0],
    [0.0, 1.0],
    [-1.0, 0.0],
    [0.0, -1.0],
]; // ◇ midpoint
const T_DOT_A: [[f64; 2]; 2] = [[-0.85, 0.0], [-0.6, 0.0]]; // ⋰ three ticks along +x
const T_DOT_B: [[f64; 2]; 2] = [[-0.12, 0.0], [0.12, 0.0]];
const T_DOT_C: [[f64; 2]; 2] = [[0.6, 0.0], [0.85, 0.0]];
const T_BOW_L: [[f64; 2]; 4] = [[-1.0, -0.8], [0.0, 0.0], [-1.0, 0.8], [-1.0, -0.8]]; // ⋈ left wing
const T_BOW_R: [[f64; 2]; 4] = [[1.0, -0.8], [0.0, 0.0], [1.0, 0.8], [1.0, -0.8]]; // ⋈ right wing
const T_GND_STEM: [[f64; 2]; 2] = [[0.0, 1.0], [0.0, 0.0]]; // ⏚ stem
const T_GND_BASE: [[f64; 2]; 2] = [[-1.0, 0.0], [1.0, 0.0]]; // ⏚ base bar
const T_GND_H1: [[f64; 2]; 2] = [[-0.6, -0.5], [0.6, -0.5]]; // ⏚ hatch 1
const T_GND_H2: [[f64; 2]; 2] = [[-0.25, -1.0], [0.25, -1.0]]; // ⏚ hatch 2

/// A regular octagon outline (closed) at unit radius — the `◎` concentric ring shape.
fn octagon() -> Vec<[f64; 2]> {
    (0..=8)
        .map(|i| {
            let t = (i as f64 / 8.0) * 2.0 * PI;
            [t.cos(), t.sin()]
        })
        .collect()
}

/// A shallow upward arc (`⌒`) sampled as a polyline in the local frame.
fn arc_cup() -> Vec<[f64; 2]> {
    (0..=8)
        .map(|i| {
            let t = PI * (0.15 + 0.7 * (i as f64 / 8.0)); // ~27°..~153°
            [t.cos(), t.sin()]
        })
        .collect()
}

/// Unit direction from `a` to `b`, or `None` when the two coincide.
fn unit(a: [f64; 2], b: [f64; 2]) -> Option<[f64; 2]> {
    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
    let l = dx.hypot(dy);
    (l > 1e-9).then(|| [dx / l, dy / l])
}

fn midpoint(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
    [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]
}

/// The plane-space glyph segments for one geometric constraint, or `None` when the
/// constraint is dimensional / temporary / unresolvable. Every segment pair is in the
/// sketch's `(u, v)` frame (embedded in world space by the buffer builder).
fn glyph_segments(
    c: &SketchConstraint,
    by_id: &HashMap<String, &SketchPoint>,
    wpp: f64,
) -> Option<Vec<([f64; 2], [f64; 2])>> {
    if is_dimensional_or_temporary(c) {
        return None;
    }
    let ctype = c.ctype()?;
    let pts = c.points();
    let s = glyph_scale(wpp);
    let mut out: Vec<([f64; 2], [f64; 2])> = Vec::new();

    match ctype {
        // — horizontal / vertical: a dash offset off the segment midpoint.
        "" | "" => {
            let (a, b) = (get(by_id, pts.first()?)?, get(by_id, pts.get(1)?)?);
            let mid = midpoint(a, b);
            // Offset along the segment normal (fall back to +v for a degenerate span).
            let dir = unit(a, b).unwrap_or([1.0, 0.0]);
            let normal = [-dir[1], dir[0]];
            let anchor = [mid[0] + normal[0] * s * OFFSET_FACTOR, mid[1] + normal[1] * s * OFFSET_FACTOR];
            let tmpl: &[[f64; 2]] = if ctype == "" { &T_DASH_H } else { &T_DASH_V };
            stamp(&mut out, anchor, s, 0.0, &[tmpl]);
        }
        // ∥ parallel: a chevron on each of the two lines, pointing along the line.
        "" if pts.len() >= 4 => {
            for (pa, pb) in [(pts[0].clone(), pts[1].clone()), (pts[2].clone(), pts[3].clone())] {
                let (a, b) = (get(by_id, &pa)?, get(by_id, &pb)?);
                let dir = unit(a, b)?;
                let anchor = midpoint(a, b);
                stamp(&mut out, anchor, s, dir[1].atan2(dir[0]), &[&T_CHEV]);
            }
        }
        // ⟂ perpendicular: a right-angle corner at the shared vertex (or the two lines'
        // intersection), drawn from the two outgoing edge directions.
        "" if pts.len() >= 4 => {
            let (l1a, l1b) = (get(by_id, &pts[0])?, get(by_id, &pts[1])?);
            let (l2a, l2b) = (get(by_id, &pts[2])?, get(by_id, &pts[3])?);
            // The shared corner: whichever endpoint of line 1 coincides with an
            // endpoint of line 2 (adjacent edges); else the infinite-line intersection.
            let key = |p: [f64; 2]| (p[0].to_bits(), p[1].to_bits());
            let shared = [l1a, l1b]
                .into_iter()
                .find(|&e| key(e) == key(l2a) || key(e) == key(l2b));
            let (corner, d1, d2) = if let Some(corner) = shared {
                let o1 = if key(corner) == key(l1a) { l1b } else { l1a };
                let o2 = if key(corner) == key(l2a) { l2b } else { l2a };
                (corner, unit(corner, o1)?, unit(corner, o2)?)
            } else {
                let corner = line_intersection(l1a, l1b, l2a, l2b);
                (corner, unit(l1a, l1b)?, unit(l2a, l2b)?)
            };
            let p1 = [corner[0] + d1[0] * s, corner[1] + d1[1] * s];
            let p3 = [corner[0] + d2[0] * s, corner[1] + d2[1] * s];
            let p2 = [p1[0] + d2[0] * s, p1[1] + d2[1] * s];
            out.push((p1, p2));
            out.push((p2, p3));
        }
        // ≡ coincident: a small square at the (shared) point.
        "" => {
            let anchor = get(by_id, pts.first()?)?;
            stamp(&mut out, anchor, s, 0.0, &[&T_SQUARE]);
        }
        // ⇌ equal distance: `=` ticks at each of the two segments' midpoints.
        "" if pts.len() >= 4 => {
            for (pa, pb) in [(pts[0].clone(), pts[1].clone()), (pts[2].clone(), pts[3].clone())] {
                let (a, b) = (get(by_id, &pa)?, get(by_id, &pb)?);
                let dir = unit(a, b).unwrap_or([1.0, 0.0]);
                stamp(&mut out, midpoint(a, b), s, dir[1].atan2(dir[0]), &[&T_EQ_A, &T_EQ_B]);
            }
        }
        // ⊜ equal radius: `=` ticks at each circle's rim point (points[1], points[3]).
        "" if pts.len() >= 4 => {
            for rim in [pts[1].clone(), pts[3].clone()] {
                let anchor = get(by_id, &rim)?;
                stamp(&mut out, anchor, s, 0.0, &[&T_EQ_A, &T_EQ_B]);
            }
        }
        // ◎ concentric: two nested rings at the shared center.
        "" => {
            let anchor = get(by_id, pts.first()?)?;
            let ring = octagon();
            stamp(&mut out, anchor, s, 0.0, &[&ring]);
            stamp(&mut out, anchor, s * 0.45, 0.0, &[&ring]);
        }
        // ⌒ tangent: a small arch at the centroid of the involved points.
        "" => {
            let anchor = centroid(by_id, pts)?;
            let cup = arc_cup();
            stamp(&mut out, anchor, s, 0.0, &[&cup]);
        }
        // ⋰ collinear: three ticks along the point run.
        "" if pts.len() >= 2 => {
            let a = get(by_id, pts.first()?)?;
            let b = get(by_id, pts.last()?)?;
            let dir = unit(a, b).unwrap_or([1.0, 0.0]);
            stamp(&mut out, midpoint(a, b), s, dir[1].atan2(dir[0]), &[&T_DOT_A, &T_DOT_B, &T_DOT_C]);
        }
        // ⏛ point-on-line: a short line with a dot at the constrained point.
        "" if pts.len() >= 3 => {
            let (la, lb) = (get(by_id, &pts[0])?, get(by_id, &pts[1])?);
            let anchor = get(by_id, &pts[2])?;
            let dir = unit(la, lb).unwrap_or([1.0, 0.0]);
            let rot = dir[1].atan2(dir[0]);
            stamp(&mut out, anchor, s, rot, &[&T_DASH_H]);
            stamp(&mut out, anchor, s * 0.35, 0.0, &[&T_SQUARE]);
        }
        // ⋯ midpoint: a diamond at the point that sits mid-way between the other two.
        "" if pts.len() >= 3 => {
            let p: Vec<[f64; 2]> = pts.iter().take(3).map(|id| get(by_id, id)).collect::<Option<_>>()?;
            // The midpoint vertex minimizes its distance to the midpoint of the others.
            let mut best = (f64::INFINITY, 0usize);
            for k in 0..3 {
                let m = midpoint(p[(k + 1) % 3], p[(k + 2) % 3]);
                let d = (p[k][0] - m[0]).hypot(p[k][1] - m[1]);
                if d < best.0 {
                    best = (d, k);
                }
            }
            stamp(&mut out, p[best.1], s * 0.8, 0.0, &[&T_DIAMOND]);
        }
        // ⋈ symmetric: a bowtie at the midpoint of the two symmetric points.
        "" if pts.len() >= 4 => {
            let (p1, p2) = (get(by_id, &pts[2])?, get(by_id, &pts[3])?);
            stamp(&mut out, midpoint(p1, p2), s, 0.0, &[&T_BOW_L, &T_BOW_R]);
        }
        // ⏚ ground: a ground symbol at (just below) the fixed point.
        "" => {
            let p = get(by_id, pts.first()?)?;
            let anchor = [p[0], p[1] - s * 0.4];
            stamp(&mut out, anchor, s, 0.0, &[&T_GND_STEM, &T_GND_BASE, &T_GND_H1, &T_GND_H2]);
        }
        _ => return None,
    }

    (!out.is_empty()).then_some(out)
}

/// The centroid (average) of a constraint's resolvable points, or `None` if none
/// resolve.
fn centroid(by_id: &HashMap<String, &SketchPoint>, pts: &[Value]) -> Option<[f64; 2]> {
    let mut sum = [0.0, 0.0];
    let mut n = 0.0;
    for id in pts {
        if let Some(p) = get(by_id, id) {
            sum[0] += p[0];
            sum[1] += p[1];
            n += 1.0;
        }
    }
    (n > 0.0).then(|| [sum[0] / n, sum[1] / n])
}

/// The plane-space glyph line segments for ONE geometric constraint, resolved
/// against `doc` (empty for a dimensional / temporary / unresolvable constraint).
/// The picking + selection-emphasis path measures the cursor against exactly these
/// segments, so "click near the glyph mark" is precisely the drawn glyph.
pub fn constraint_glyph_segments(
    c: &SketchConstraint,
    doc: &SketchDoc,
    world_per_pixel: f64,
) -> Vec<([f64; 2], [f64; 2])> {
    let by_id = super::dimensions::point_index(doc);
    glyph_segments(c, &by_id, world_per_pixel).unwrap_or_default()
}

/// The world-space glyph line segments for every geometric constraint, as flat
/// `(positions, colors)` buffers (6 position + 6 color floats per segment) ready to
/// feed the `sketch-constraint-glyphs` overlay group.
pub fn constraint_glyphs_buffers(
    doc: &SketchDoc,
    plane: &PlaneFrame,
    world_per_pixel: f64,
    colors: &SketchColors,
) -> (Vec<f32>, Vec<f32>) {
    constraint_glyphs_buffers_with_state(doc, plane, world_per_pixel, colors, None, &[])
}

/// Like [`constraint_glyphs_buffers`], but emphasizes the hovered / selected
/// constraint (matched by a `{"kind":"constraint","id":…}` ref) in the SAME amber /
/// light-blue as a selected / hovered point or geometry (via
/// [`super::tessellate::interaction_color`]); an empty hover + selection reproduce the
/// plain-green output.
pub fn constraint_glyphs_buffers_with_state(
    doc: &SketchDoc,
    plane: &PlaneFrame,
    world_per_pixel: f64,
    colors: &SketchColors,
    hovered: Option<&Value>,
    selection: &[Value],
) -> (Vec<f32>, Vec<f32>) {
    let by_id = super::dimensions::point_index(doc);
    let mut positions: Vec<f32> = Vec::new();
    let mut color_buf: Vec<f32> = Vec::new();
    for c in &doc.constraints {
        let Some(segments) = glyph_segments(c, &by_id, world_per_pixel) else {
            continue;
        };
        // Emphasis is keyed by the constraint's own id (green normally, amber when
        // selected, light blue when hovered).
        let color = match c.raw.get("id") {
            Some(id) => super::tessellate::interaction_color(
                colors,
                colors.constraint,
                hovered,
                selection,
                "constraint",
                id,
            ),
            None => colors.constraint,
        };
        let rgb = super::tessellate::rgb(color);
        for (a, b) in segments {
            let wa = plane.to_world(a[0], a[1]);
            let wb = plane.to_world(b[0], b[1]);
            positions.extend_from_slice(&[
                wa[0] as f32,
                wa[1] as f32,
                wa[2] as f32,
                wb[0] as f32,
                wb[1] as f32,
                wb[2] as f32,
            ]);
            color_buf.extend_from_slice(&[rgb[0], rgb[1], rgb[2], rgb[0], rgb[1], rgb[2]]);
        }
    }
    (positions, color_buf)
}

/// The `set_overlay` JSON for the `sketch-constraint-glyphs` group (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(
    doc: &SketchDoc,
    plane: &PlaneFrame,
    world_per_pixel: f64,
    colors: &SketchColors,
) -> String {
    constraint_glyphs_overlay_json_with_state(doc, plane, world_per_pixel, colors, None, &[])
}

/// Like [`constraint_glyphs_overlay_json`], but colors the hovered / selected
/// constraint's glyph distinctly (S: constraint selection).
pub fn constraint_glyphs_overlay_json_with_state(
    doc: &SketchDoc,
    plane: &PlaneFrame,
    world_per_pixel: f64,
    colors: &SketchColors,
    hovered: Option<&Value>,
    selection: &[Value],
) -> String {
    let (positions, color_buf) =
        constraint_glyphs_buffers_with_state(doc, plane, world_per_pixel, colors, hovered, selection);
    serde_json::json!({
        "groups": [
            {
                "name": OVERLAY_CONSTRAINT_GLYPHS,
                "renderOrder": 10004,
                "lines": { "positions": positions, "colors": color_buf },
            }
        ]
    })
    .to_string()
}

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

    fn doc_from(value: Value) -> SketchDoc {
        serde_json::from_value(value).expect("sketch doc")
    }

    /// The glyph segments (plane space) for the single constraint in a one-constraint
    /// doc — the per-type unit under test.
    fn segs_for(doc: &SketchDoc) -> Vec<([f64; 2], [f64; 2])> {
        let by_id = super::super::dimensions::point_index(doc);
        glyph_segments(&doc.constraints[0], &by_id, 0.05).unwrap_or_default()
    }

    #[test]
    fn perpendicular_draws_a_right_angle_at_the_shared_corner() {
        // Two adjacent edges meeting at (1,0): (0,0)-(1,0) and (1,0)-(1,1).
        let doc = doc_from(json!({
            "points": [
                { "id": 0, "x": 0.0, "y": 0.0 },
                { "id": 1, "x": 1.0, "y": 0.0 },
                { "id": 2, "x": 1.0, "y": 1.0 }
            ],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1, 1, 2] }]
        }));
        let segs = segs_for(&doc);
        // A right-angle corner is two segments, sitting a glyph's-width off the shared
        // vertex (1,0) — the whole mark clusters within ~2 glyph half-sizes of it.
        assert_eq!(segs.len(), 2, "right-angle mark = 2 strokes");
        let bound = 2.0 * glyph_scale(0.05);
        let d = |p: [f64; 2]| (p[0] - 1.0).hypot(p[1] - 0.0);
        assert!(
            segs.iter().all(|(a, b)| d(*a) < bound && d(*b) < bound),
            "mark clusters by the shared corner (1,0)"
        );
        assert!(segs.iter().all(|(a, b)| a.iter().chain(b).all(|f| f.is_finite())));
    }

    #[test]
    fn horizontal_and_vertical_each_emit_a_dash() {
        for ty in ["", ""] {
            let doc = doc_from(json!({
                "points": [{ "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 4.0, "y": 0.0 }],
                "geometries": [],
                "constraints": [{ "id": 0, "type": ty, "points": [0, 1] }]
            }));
            assert_eq!(segs_for(&doc).len(), 1, "{ty} → one dash stroke");
        }
    }

    #[test]
    fn parallel_and_equal_mark_both_edges() {
        // Parallel: a chevron (2 strokes) per line → 4 strokes.
        let par = doc_from(json!({
            "points": [
                { "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 4.0, "y": 0.0 },
                { "id": 2, "x": 0.0, "y": 3.0 }, { "id": 3, "x": 4.0, "y": 3.0 }
            ],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1, 2, 3] }]
        }));
        assert_eq!(segs_for(&par).len(), 4, "chevron per line");
        // Equal distance: an `=` (2 bars) per segment → 4 strokes.
        let eq = doc_from(json!({
            "points": [
                { "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 4.0, "y": 0.0 },
                { "id": 2, "x": 0.0, "y": 3.0 }, { "id": 3, "x": 4.0, "y": 3.0 }
            ],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1, 2, 3] }]
        }));
        assert_eq!(segs_for(&eq).len(), 4, "= per segment");
    }

    #[test]
    fn coincident_and_ground_and_concentric_emit_marks() {
        let coincident = doc_from(json!({
            "points": [{ "id": 0, "x": 2.0, "y": 2.0 }, { "id": 1, "x": 2.0, "y": 2.0 }],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1] }]
        }));
        assert!(!segs_for(&coincident).is_empty(), "coincident square");
        let ground = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0] }]
        }));
        assert!(!segs_for(&ground).is_empty(), "ground mark");
        let concentric = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 5.0, "y": 0.0 }],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1] }]
        }));
        assert!(!segs_for(&concentric).is_empty(), "concentric rings");
    }

    #[test]
    fn dimensional_and_temporary_constraints_are_skipped() {
        let by_id_of = |doc: &SketchDoc| -> bool {
            let by_id = super::super::dimensions::point_index(doc);
            glyph_segments(&doc.constraints[0], &by_id, 0.05).is_none()
        };
        // A distance dim → no glyph (owned by dimensions.rs).
        let dim = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 4.0, "y": 0.0 }],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1], "value": 4.0 }]
        }));
        assert!(by_id_of(&dim), "distance dim skipped");
        // A temporary helper (even a geometric one) → no glyph.
        let temp = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 4.0, "y": 0.0 }],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1], "temporary": true }]
        }));
        assert!(by_id_of(&temp), "temporary constraint skipped");
    }

    #[test]
    fn overlay_json_names_the_group_and_carries_a_marker_per_constraint() {
        let doc = doc_from(json!({
            "points": [
                { "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 4.0, "y": 0.0 },
                { "id": 2, "x": 4.0, "y": 3.0 }, { "id": 3, "x": 0.0, "y": 3.0 }
            ],
            "geometries": [],
            "constraints": [
                { "id": 0, "type": "", "points": [0, 1, 1, 2] },
                { "id": 1, "type": "", "points": [0, 1] },
                { "id": 2, "type": "", "points": [0, 1], "value": 4.0 }
            ]
        }));
        let json: Value =
            serde_json::from_str(&constraint_glyphs_overlay_json(&doc, &PlaneFrame::xy(), 0.05, &Default::default()))
                .unwrap();
        let group = &json["groups"][0];
        assert_eq!(group["name"], OVERLAY_CONSTRAINT_GLYPHS);
        assert_eq!(group["renderOrder"], 10004);
        // The two GEOMETRIC constraints contribute segments; the dim contributes none.
        let positions = group["lines"]["positions"].as_array().unwrap();
        assert!(!positions.is_empty(), "geometric constraints emit markers");
        assert_eq!(positions.len() % 6, 0, "6 floats per segment");
        assert!(positions.iter().all(|v| v.as_f64().unwrap().is_finite()));
    }

    #[test]
    fn selected_constraint_glyph_paints_amber_else_green() {
        // A single horizontal geometric constraint; its glyph is green normally and
        // amber (0xffa500) when the constraint is selected — the same emphasis as a
        // selected point/geometry.
        let doc = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }, { "id": 1, "x": 4.0, "y": 0.0 }],
            "geometries": [],
            "constraints": [{ "id": 0, "type": "", "points": [0, 1] }]
        }));
        let plane = PlaneFrame::xy();
        // Unselected → the constraint green (SketchColors::default().constraint =
        // 0x4ade80, r = 0x4a).
        let (_p, green) = constraint_glyphs_buffers_with_state(&doc, &plane, 0.05, &Default::default(), None, &[]);
        assert!(!green.is_empty(), "geometric constraint emits a glyph");
        assert!(
            (green[0] - 0x4a as f32 / 255.0).abs() < 1e-3,
            "unselected glyph not green: {:?}",
            &green[..3]
        );
        // Selected → amber (0xff, 0xa5, 0x00).
        let selection = vec![json!({ "kind": "constraint", "id": 0 })];
        let (_p2, amber) =
            constraint_glyphs_buffers_with_state(&doc, &plane, 0.05, &Default::default(), None, &selection);
        assert!(
            (amber[0] - 0xff as f32 / 255.0).abs() < 1e-3
                && (amber[1] - 0xa5 as f32 / 255.0).abs() < 1e-3,
            "selected glyph not amber: {:?}",
            &amber[..3]
        );
    }

    #[test]
    fn empty_doc_emits_an_empty_but_named_group() {
        let doc = SketchDoc::default();
        let json: Value =
            serde_json::from_str(&constraint_glyphs_overlay_json(&doc, &PlaneFrame::xy(), 0.05, &Default::default()))
                .unwrap();
        let group = &json["groups"][0];
        assert_eq!(group["name"], OVERLAY_CONSTRAINT_GLYPHS);
        assert!(group["lines"]["positions"].as_array().unwrap().is_empty());
    }
}