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
//! External-reference edges (S6b-2) — link a picked 3D solid edge into the sketch
//! as a construction reference.
//!
//! The pickEdges tool projects a scene edge's world-space polyline into the active
//! sketch plane, classifies the projected shape (straight → `line`, a fitted
//! circle → `circle`/`arc`, else a faithful `line`-chain fallback), and materializes
//! it as external-reference geometry: `{fixed, construction, externalReference}`
//! points, a `⏚` GROUND constraint per point (so the solver pins them), and the
//! construction geometry referencing them. A per-session [`ExternalRef`] mapping
//! (keyed by edge name) dedups a re-pick — the SAME edge UPDATES its points'
//! coordinates instead of duplicating — and round-trips through
//! `persistentData.externalRefs`.
//!
//! This mirrors `#ensureExternalRefForEdge`/`#projectWorldToUV`,
//! extended to also emit the reference GEOMETRY (the previous version stored only the two
//! endpoints) so the linked edge is visible and constrainable in the sketch.

use std::collections::HashSet;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use super::doc::{id_key, SketchConstraint, SketchDoc, SketchGeometry, SketchPoint};
use super::PlaneFrame;

/// The classification of a projected edge polyline, in plane `(u, v)` coordinates.
#[derive(Clone, Debug, PartialEq)]
pub enum EdgeLink {
    /// A straight edge — link as a `line` through the two endpoints.
    Line { a: (f64, f64), b: (f64, f64) },
    /// A closed circular edge — link as a `circle` (center + a rim point).
    Circle { center: (f64, f64), rim: (f64, f64) },
    /// A circular ARC — link as an `arc` (center, start, end; CCW start→end).
    Arc {
        center: (f64, f64),
        start: (f64, f64),
        end: (f64, f64),
    },
    /// A faithful fallback for anything else — a chain of `line` segments through the
    /// projected polyline samples.
    Polyline { pts: Vec<(f64, f64)> },
}

impl EdgeLink {
    /// The solver geometry `type` this link materializes as (`polyline` fallback is a
    /// chain of `line`s, so its representative type is `"line"`).
    pub fn kind(&self) -> &'static str {
        match self {
            EdgeLink::Line { .. } => "line",
            EdgeLink::Circle { .. } => "circle",
            EdgeLink::Arc { .. } => "arc",
            EdgeLink::Polyline { .. } => "polyline",
        }
    }

    /// The ordered `(u, v)` coordinates of the points this link materializes (its
    /// geometry references them in order).
    pub fn point_uvs(&self) -> Vec<(f64, f64)> {
        match self {
            EdgeLink::Line { a, b } => vec![*a, *b],
            EdgeLink::Circle { center, rim } => vec![*center, *rim],
            EdgeLink::Arc { center, start, end } => vec![*center, *start, *end],
            EdgeLink::Polyline { pts } => pts.clone(),
        }
    }
}

/// Project a world-space polyline into the plane's `(u, v)` frame (orthogonal
/// projection; the off-plane component is dropped). Mirrors the previous
/// world→UV projection applied per vertex.
pub fn project_polyline(plane: &PlaneFrame, world: &[[f64; 3]]) -> Vec<(f64, f64)> {
    world.iter().map(|&w| plane.to_uv(w)).collect()
}

/// Classify a projected polyline (in plane `(u, v)`) as a straight line, a circle /
/// arc, or a polyline fallback. Tolerances are RELATIVE to the polyline's extent so
/// the same thresholds work at any sketch scale:
///
/// - **STRAIGHT** when every interior sample lies within `1e-4·extent` of the chord
///   between the endpoints (a 2-sample polyline is trivially straight).
/// - **CIRCULAR** when a circle fit through 3 well-spaced samples has a max radial
///   residual under `1e-3·extent` (and a non-degenerate radius). Coincident
///   endpoints → a closed `Circle`; else an `Arc`.
/// - else the **Polyline** fallback.
pub fn classify_uv(uv: &[(f64, f64)]) -> EdgeLink {
    let n = uv.len();
    if n < 2 {
        // Degenerate — surface it as a (possibly zero-length) polyline; callers guard
        // against < 2 samples before linking.
        return EdgeLink::Polyline { pts: uv.to_vec() };
    }
    let a = uv[0];
    let b = uv[n - 1];
    let extent = polyline_extent(uv).max(1e-9);
    let straight_tol = 1e-4 * extent;
    let closed = dist(a, b) <= straight_tol;

    // Two samples (or all-interior-on-chord and open) → a straight line.
    if !closed {
        let max_dev = uv[1..n - 1]
            .iter()
            .map(|&p| point_segment_distance(p, a, b))
            .fold(0.0_f64, f64::max);
        if n == 2 || max_dev <= straight_tol {
            return EdgeLink::Line { a, b };
        }
    }

    // Circle fit through three well-spaced samples. Sampling at 0 / n/3 / 2n/3 (NOT
    // the last index) keeps the three distinct even for a CLOSED loop, where the
    // first and last samples coincide.
    if n >= 3 {
        if let Some((cx, cy, r)) = fit_circle(uv[0], uv[n / 3], uv[(2 * n) / 3]) {
            let circle_tol = 1e-3 * extent;
            let residual = uv
                .iter()
                .map(|&p| (dist(p, (cx, cy)) - r).abs())
                .fold(0.0_f64, f64::max);
            if r.is_finite() && r > straight_tol && residual <= circle_tol {
                if closed {
                    return EdgeLink::Circle {
                        center: (cx, cy),
                        rim: (cx + r, cy),
                    };
                }
                return EdgeLink::Arc {
                    center: (cx, cy),
                    start: a,
                    end: b,
                };
            }
        }
    }

    EdgeLink::Polyline { pts: uv.to_vec() }
}

/// A per-session external-reference mapping: the linked scene edge (by name + owning
/// solid) and the sketch entities materialized for it. Persisted to / loaded from
/// `persistentData.externalRefs` so a linked edge round-trips a commit + re-enter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExternalRef {
    /// Kernel edge name (the dedup key).
    #[serde(rename = "edgeName")]
    pub edge_name: String,
    /// Owning solid's scene name (metadata; may be empty).
    #[serde(rename = "solidName", default)]
    pub solid_name: String,
    /// The materialized point ids (order matches the link's geometry).
    #[serde(rename = "pointIds", default)]
    pub point_ids: Vec<Value>,
    /// The materialized geometry ids (one for line/circle/arc; N-1 for a polyline
    /// chain).
    #[serde(rename = "geomIds", default)]
    pub geom_ids: Vec<Value>,
    /// The link classification (`"line"|"circle"|"arc"|"polyline"`).
    #[serde(default)]
    pub kind: String,
}

/// Link (or update) a picked scene edge into the sketch as an external reference.
///
/// Projects `world_poly` into `plane`, classifies it, and materializes external-ref
/// points + `⏚` grounds + construction geometry, recording an [`ExternalRef`] in
/// `refs`. Dedup: when `refs` already holds an entry for `edge_name` whose structure
/// matches the new classification, the existing points are UPDATED in place (no
/// duplication); when the structure differs, the old entities are removed and fresh
/// ones created; otherwise a new ref is appended.
///
/// Returns whether the doc actually changed (a new/rebuilt ref, or moved coordinates)
/// — `false` on a redundant re-link of an unchanged edge, so the caller can drop a
/// dead undo step. Never solves; the caller re-solves.
pub fn link_or_update(
    doc: &mut SketchDoc,
    refs: &mut Vec<ExternalRef>,
    edge_name: &str,
    solid_name: &str,
    world_poly: &[[f64; 3]],
    plane: &PlaneFrame,
) -> bool {
    if world_poly.len() < 2 {
        return false;
    }
    let uv = project_polyline(plane, world_poly);
    let link = classify_uv(&uv);
    let new_uvs = link.point_uvs();

    if let Some(pos) = refs.iter().position(|r| r.edge_name == edge_name) {
        let structure_matches =
            refs[pos].kind == link.kind() && refs[pos].point_ids.len() == new_uvs.len();
        if structure_matches {
            // Update the existing points' coordinates in place (keeps ids + geometry).
            let mut moved = false;
            let point_ids = refs[pos].point_ids.clone();
            for (id, (u, v)) in point_ids.iter().zip(new_uvs.iter()) {
                if let Some(p) = doc.point_mut(id) {
                    if (p.x - u).abs() > 1e-12 || (p.y - v).abs() > 1e-12 {
                        moved = true;
                    }
                    p.x = *u;
                    p.y = *v;
                    p.fixed = true;
                    p.construction = true;
                    p.external_reference = true;
                }
            }
            if refs[pos].solid_name != solid_name {
                refs[pos].solid_name = solid_name.to_string();
            }
            return moved;
        }
        // Structure changed (e.g. a straight edge became curved after a model edit) —
        // drop the stale entities and rebuild the ref fresh.
        remove_ref_entities(doc, &refs[pos].clone());
        let (point_ids, geom_ids) = add_external_ref(doc, &link);
        refs[pos] = ExternalRef {
            edge_name: edge_name.to_string(),
            solid_name: solid_name.to_string(),
            point_ids,
            geom_ids,
            kind: link.kind().to_string(),
        };
        return true;
    }

    // A brand-new reference for this edge.
    let (point_ids, geom_ids) = add_external_ref(doc, &link);
    refs.push(ExternalRef {
        edge_name: edge_name.to_string(),
        solid_name: solid_name.to_string(),
        point_ids,
        geom_ids,
        kind: link.kind().to_string(),
    });
    true
}

/// Materialize an [`EdgeLink`] into the doc: push external-ref points (`fixed`,
/// `construction`, `externalReference`) with a `⏚` ground each, then the construction
/// geometry referencing them. Returns `(point_ids, geom_ids)`.
pub fn add_external_ref(doc: &mut SketchDoc, link: &EdgeLink) -> (Vec<Value>, Vec<Value>) {
    let mut point_ids = Vec::new();
    for (u, v) in link.point_uvs() {
        let id = doc.next_point_id();
        doc.points.push(SketchPoint {
            id: id.clone(),
            x: u,
            y: v,
            fixed: true,
            construction: true,
            external_reference: true,
        });
        push_ground(doc, &id);
        point_ids.push(id);
    }
    let geom_ids = match link {
        EdgeLink::Line { .. } => vec![push_construction_geometry(
            doc,
            "line",
            vec![point_ids[0].clone(), point_ids[1].clone()],
        )],
        EdgeLink::Circle { .. } => vec![push_construction_geometry(
            doc,
            "circle",
            vec![point_ids[0].clone(), point_ids[1].clone()],
        )],
        EdgeLink::Arc { .. } => vec![push_construction_geometry(
            doc,
            "arc",
            vec![
                point_ids[0].clone(),
                point_ids[1].clone(),
                point_ids[2].clone(),
            ],
        )],
        EdgeLink::Polyline { .. } => point_ids
            .windows(2)
            .map(|w| push_construction_geometry(doc, "line", vec![w[0].clone(), w[1].clone()]))
            .collect(),
    };
    (point_ids, geom_ids)
}

/// Remove every entity an [`ExternalRef`] materialized: its geometries, its points,
/// and any constraint referencing one of its points (the `⏚` grounds).
fn remove_ref_entities(doc: &mut SketchDoc, r: &ExternalRef) {
    let pt_keys: HashSet<String> = r.point_ids.iter().map(id_key).collect();
    let geo_keys: HashSet<String> = r.geom_ids.iter().map(id_key).collect();
    doc.geometries.retain(|g| !geo_keys.contains(&id_key(&g.id)));
    doc.points.retain(|p| !pt_keys.contains(&id_key(&p.id)));
    doc.constraints
        .retain(|c| !c.points().iter().any(|p| pt_keys.contains(&id_key(p))));
}

/// Push a `⏚` GROUND constraint pinning point `pid` (mirrors the S4 toggle-ground
/// factory).
fn push_ground(doc: &mut SketchDoc, pid: &Value) {
    let cid = doc.next_constraint_id();
    let mut raw = Map::new();
    raw.insert("id".to_string(), cid);
    raw.insert("type".to_string(), Value::String("".to_string()));
    raw.insert("points".to_string(), Value::Array(vec![pid.clone()]));
    doc.constraints.push(SketchConstraint { raw });
}

/// Push a construction geometry (`construction: true` — dashed, non-modeling) with a
/// freshly minted id, returning that id.
fn push_construction_geometry(doc: &mut SketchDoc, geom_type: &str, points: Vec<Value>) -> Value {
    let id = doc.next_geometry_id();
    let mut extra = Map::new();
    extra.insert("construction".to_string(), Value::Bool(true));
    doc.geometries.push(SketchGeometry {
        id: id.clone(),
        geom_type: geom_type.to_string(),
        points,
        extra,
    });
    id
}

// --- geometry helpers ---------------------------------------------------------

/// Euclidean distance between two `(u, v)` points.
fn dist(a: (f64, f64), b: (f64, f64)) -> f64 {
    ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt()
}

/// The bounding-box diagonal of a `(u, v)` polyline — the relative-tolerance scale.
fn polyline_extent(uv: &[(f64, f64)]) -> f64 {
    let (mut minx, mut miny) = (f64::INFINITY, f64::INFINITY);
    let (mut maxx, mut maxy) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
    for &(x, y) in uv {
        minx = minx.min(x);
        miny = miny.min(y);
        maxx = maxx.max(x);
        maxy = maxy.max(y);
    }
    ((maxx - minx).powi(2) + (maxy - miny).powi(2)).sqrt()
}

/// Distance from point `p` to segment `a`–`b` (all in `(u, v)`).
fn point_segment_distance(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> 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 {
        (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0)
    };
    dist(p, (a.0 + t * dx, a.1 + t * dy))
}

/// Fit a circle through three points (circumcenter + radius), or `None` when the
/// points are (near) collinear.
fn fit_circle(p1: (f64, f64), p2: (f64, f64), p3: (f64, f64)) -> Option<(f64, f64, f64)> {
    let (ax, ay) = p1;
    let (bx, by) = p2;
    let (cx, cy) = p3;
    // 2·(signed area of the triangle) — zero when collinear.
    let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
    if d.abs() < 1e-12 {
        return None;
    }
    let a2 = ax * ax + ay * ay;
    let b2 = bx * bx + by * by;
    let c2 = cx * cx + cy * cy;
    let ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d;
    let uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d;
    let r = dist((ux, uy), p1);
    if !ux.is_finite() || !uy.is_finite() || !r.is_finite() {
        return None;
    }
    Some((ux, uy, r))
}

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

    fn empty_doc() -> SketchDoc {
        SketchDoc::default()
    }

    /// A straight polyline (2 samples) classifies as a line.
    #[test]
    fn classify_two_point_polyline_is_a_line() {
        let link = classify_uv(&[(0.0, 0.0), (10.0, 5.0)]);
        assert_eq!(link, EdgeLink::Line { a: (0.0, 0.0), b: (10.0, 5.0) });
    }

    /// A densely sampled straight polyline (interior on the chord) classifies as a
    /// line, not a curve.
    #[test]
    fn classify_collinear_samples_is_a_line() {
        let uv: Vec<(f64, f64)> = (0..=10).map(|i| (i as f64, 2.0 * i as f64)).collect();
        assert_eq!(classify_uv(&uv).kind(), "line");
    }

    /// A closed circular polyline classifies as a circle with the fitted center +
    /// radius.
    #[test]
    fn classify_closed_circle() {
        let (cx, cy, r) = (3.0, -1.0, 5.0);
        let n = 64;
        let uv: Vec<(f64, f64)> = (0..=n)
            .map(|i| {
                let t = i as f64 / n as f64 * std::f64::consts::TAU;
                (cx + r * t.cos(), cy + r * t.sin())
            })
            .collect();
        match classify_uv(&uv) {
            EdgeLink::Circle { center, rim } => {
                assert!((center.0 - cx).abs() < 1e-6 && (center.1 - cy).abs() < 1e-6);
                assert!((dist(center, rim) - r).abs() < 1e-6);
            }
            other => panic!("expected circle, got {other:?}"),
        }
    }

    /// A quarter-circle (open) classifies as an arc through its endpoints.
    #[test]
    fn classify_open_arc() {
        let (cx, cy, r) = (0.0, 0.0, 4.0);
        let n = 16;
        let uv: Vec<(f64, f64)> = (0..=n)
            .map(|i| {
                let t = i as f64 / n as f64 * (std::f64::consts::PI / 2.0);
                (cx + r * t.cos(), cy + r * t.sin())
            })
            .collect();
        match classify_uv(&uv) {
            EdgeLink::Arc { center, start, end } => {
                assert!((center.0 - cx).abs() < 1e-6 && (center.1 - cy).abs() < 1e-6);
                assert!((start.0 - r).abs() < 1e-6 && start.1.abs() < 1e-6);
                assert!(end.0.abs() < 1e-6 && (end.1 - r).abs() < 1e-6);
            }
            other => panic!("expected arc, got {other:?}"),
        }
    }

    /// A wavy (non-circular, non-straight) polyline falls back to a line chain.
    #[test]
    fn classify_wavy_is_polyline_fallback() {
        let uv: Vec<(f64, f64)> = (0..=8)
            .map(|i| (i as f64, if i % 2 == 0 { 0.0 } else { 3.0 }))
            .collect();
        assert_eq!(classify_uv(&uv).kind(), "polyline");
    }

    /// Materializing a line link adds 2 external-ref points (each grounded) + a
    /// construction line geometry.
    #[test]
    fn add_external_ref_line_marks_points_and_grounds() {
        let mut doc = empty_doc();
        let link = EdgeLink::Line { a: (1.0, 2.0), b: (7.0, 2.0) };
        let (pids, gids) = add_external_ref(&mut doc, &link);
        assert_eq!(pids.len(), 2);
        assert_eq!(gids.len(), 1);
        for id in &pids {
            let p = doc.point(id).unwrap();
            assert!(p.fixed && p.construction && p.external_reference, "point flags: {p:?}");
            // Exactly one ⏚ ground referencing this point.
            let grounds = doc
                .constraints
                .iter()
                .filter(|c| c.ctype() == Some("") && c.points().first().map(id_key) == Some(id_key(id)))
                .count();
            assert_eq!(grounds, 1, "point {id} should have one ground");
        }
        let g = doc.geometry(&gids[0]).unwrap();
        assert_eq!(g.geom_type, "line");
        assert!(g.construction(), "reference geometry must be construction");
    }

    /// Re-linking the SAME edge with the SAME projection does not duplicate; a
    /// DIFFERENT projection updates the points in place; a DIFFERENT edge adds a ref.
    #[test]
    fn link_or_update_dedups_and_updates() {
        let mut doc = empty_doc();
        let mut refs: Vec<ExternalRef> = Vec::new();
        let plane = PlaneFrame::xy();
        let poly = [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]];

        // First link → a new ref (2 points + 1 geometry).
        assert!(link_or_update(&mut doc, &mut refs, "edgeA", "Solid", &poly, &plane));
        assert_eq!(refs.len(), 1);
        assert_eq!(doc.points.len(), 2);
        assert_eq!(doc.geometries.len(), 1);

        // Re-link the SAME edge, SAME geometry → no change, no duplication.
        assert!(!link_or_update(&mut doc, &mut refs, "edgeA", "Solid", &poly, &plane));
        assert_eq!(refs.len(), 1);
        assert_eq!(doc.points.len(), 2);
        assert_eq!(doc.geometries.len(), 1);

        // Re-link the SAME edge with a MOVED endpoint (a model change) → updates the
        // existing points in place (still 2 points, 1 geometry), coords refreshed.
        let moved = [[0.0, 0.0, 0.0], [10.0, 4.0, 0.0]];
        assert!(link_or_update(&mut doc, &mut refs, "edgeA", "Solid", &moved, &plane));
        assert_eq!(doc.points.len(), 2);
        let p_end = doc.point(&refs[0].point_ids[1]).unwrap();
        assert!((p_end.x - 10.0).abs() < 1e-9 && (p_end.y - 4.0).abs() < 1e-9);

        // A DIFFERENT edge → a second ref.
        let poly2 = [[0.0, 0.0, 0.0], [0.0, 8.0, 0.0]];
        assert!(link_or_update(&mut doc, &mut refs, "edgeB", "Solid", &poly2, &plane));
        assert_eq!(refs.len(), 2);
        assert_eq!(doc.points.len(), 4);
        assert_eq!(doc.geometries.len(), 2);
    }

    /// A structure change (line → circle for the same edge) rebuilds the ref rather
    /// than leaving stale entities.
    #[test]
    fn link_or_update_rebuilds_on_structure_change() {
        let mut doc = empty_doc();
        let mut refs: Vec<ExternalRef> = Vec::new();
        let plane = PlaneFrame::xy();

        let line = [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]];
        link_or_update(&mut doc, &mut refs, "edgeA", "Solid", &line, &plane);
        assert_eq!(refs[0].kind, "line");
        assert_eq!(doc.points.len(), 2);

        // Same edge now projects to a closed circle → the ref rebuilds as a circle.
        let (cx, cy, r) = (0.0, 0.0, 5.0);
        let n = 48;
        let circle: Vec<[f64; 3]> = (0..=n)
            .map(|i| {
                let t = i as f64 / n as f64 * std::f64::consts::TAU;
                [cx + r * t.cos(), cy + r * t.sin(), 0.0]
            })
            .collect();
        link_or_update(&mut doc, &mut refs, "edgeA", "Solid", &circle, &plane);
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].kind, "circle");
        // Circle = center + rim = 2 points, 1 geometry; the old line's entities are gone.
        assert_eq!(doc.points.len(), 2);
        assert_eq!(doc.geometries.len(), 1);
        assert_eq!(doc.geometry(&refs[0].geom_ids[0]).unwrap().geom_type, "circle");
    }

    /// `ExternalRef` round-trips through JSON (persistence shape).
    #[test]
    fn external_ref_json_round_trips() {
        let r = ExternalRef {
            edge_name: "e".into(),
            solid_name: "s".into(),
            point_ids: vec![json!(7), json!(8)],
            geom_ids: vec![json!(20)],
            kind: "line".into(),
        };
        let v = serde_json::to_value(&r).unwrap();
        assert_eq!(v["edgeName"], "e");
        assert_eq!(v["pointIds"], json!([7, 8]));
        let back: ExternalRef = serde_json::from_value(v).unwrap();
        assert_eq!(back, r);
    }
}