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
//! `SketchDoc` — the engine-native mirror of the 2D solver's sketch JSON.
//!
//! The Rust 2D constraint solver (`brep_kernel::solve_sketch`) consumes and
//! emits a sketch object shaped `{points, geometries, constraints}` (plus a
//! read-only `diagnostics` block on the solved output). This module is the typed
//! serde mirror of that shape, so the engine-native sketcher can hold, solve, and
//! render a sketch WITHOUT a JSON round-trip through the previous app.
//!
//! Faithful round-trip is a hard requirement (S0 test): a document deserialized
//! from the solver's output and re-serialized must equal the original JSON. To
//! that end the passthrough-heavy sub-objects keep an `#[serde(flatten)]` bag of
//! any fields this slice does not model explicitly (geometry `construction` flag,
//! the solver's constraint bookkeeping — `status`, `previousPointValues`, the
//! `_distance*` fields, …), so nothing is lost across a load/save.

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

/// A sketch point: a solved 2D coordinate in the plane's `(u, v)` frame, plus the
/// three role flags the solver tracks. Emitted by the solver as exactly these six
/// fields (`solvers/sketch_solver.rs` solve output).
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SketchPoint {
    /// Stable point id (a number in practice, but the solver keys by `Value`, so
    /// strings are legal too — kept as a `Value` for a lossless round-trip).
    pub id: Value,
    pub x: f64,
    pub y: f64,
    /// Ground/pinned: the solver removes this point's coordinates from the free
    /// set entirely (always `locked`).
    #[serde(default)]
    pub fixed: bool,
    /// Construction point: constrains but never models a profile edge; drawn in
    /// the construction color.
    #[serde(default)]
    pub construction: bool,
    /// A point adopted from an external reference (a picked edge endpoint).
    #[serde(default, rename = "externalReference")]
    pub external_reference: bool,
}

/// A sketch geometry: `line = [p0,p1]`, `circle = [center,radiusPoint]`,
/// `arc = [center,start,end]` (CCW start→end), `ellipse = [center,majEnd,minEnd]`,
/// `bezier = [p0,p1,p2,p3,…]` (every 3 ids a new cubic span). Point semantics are
/// the ground truth from the sketch feature's edge builder.
///
/// `points` are point ids (matched against [`SketchPoint::id`] via [`id_key`]).
/// The `construction` flag (dashed, non-modeling) and any other authored fields
/// ride along in `extra`, so the geometry round-trips losslessly.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SketchGeometry {
    pub id: Value,
    #[serde(rename = "type")]
    pub geom_type: String,
    #[serde(default)]
    pub points: Vec<Value>,
    /// Every field this slice does not model explicitly (`construction`, authoring
    /// metadata, …) — preserved verbatim so a load/save is lossless.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

impl SketchGeometry {
    /// Whether this geometry is construction-only (dashed, excluded from profiles).
    pub fn construction(&self) -> bool {
        self.extra
            .get("construction")
            .and_then(Value::as_bool)
            .unwrap_or(false)
    }
}

/// A sketch constraint. The solver mutates constraints with a large amount of
/// bookkeeping (`status`, `error`, `previousPointValues`, `_previousSolveValue`,
/// the `_distance*` slide state, …) that must persist between solves EXACTLY, so
/// the whole object is kept as a transparent map rather than a lossy typed struct.
/// Typed accessors ([`ctype`](Self::ctype), [`points`](Self::points)) read the
/// fields this slice needs.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(transparent)]
pub struct SketchConstraint {
    pub raw: Map<String, Value>,
}

impl SketchConstraint {
    /// The constraint glyph/type (`"⏚"` ground, `"━"` horizontal, `"⟺"` distance, …).
    pub fn ctype(&self) -> Option<&str> {
        self.raw.get("type").and_then(Value::as_str)
    }

    /// The point ids this constraint references (empty if absent).
    pub fn points(&self) -> &[Value] {
        self.raw
            .get("points")
            .and_then(Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Whether this is a solver-internal helper constraint (excluded from the DOF
    /// diagnostics and from the "constrained points" fallback coloring).
    pub fn temporary(&self) -> bool {
        self.raw
            .get("temporary")
            .and_then(Value::as_bool)
            .unwrap_or(false)
    }
}

/// The editable sketch document — a typed mirror of the solver's
/// `{points, geometries, constraints}`. Unknown top-level keys (e.g. the solved
/// output's `diagnostics`) are ignored on load; [`crate::sketch::solve`] pulls
/// diagnostics out into [`SketchDiagnostics`] separately.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct SketchDoc {
    #[serde(default)]
    pub points: Vec<SketchPoint>,
    #[serde(default)]
    pub geometries: Vec<SketchGeometry>,
    #[serde(default)]
    pub constraints: Vec<SketchConstraint>,
}

impl SketchDoc {
    /// Look up a point by id (matched via [`id_key`], mirroring the solver's
    /// `point_key` identity).
    pub fn point(&self, id: &Value) -> Option<&SketchPoint> {
        let key = id_key(id);
        self.points.iter().find(|p| id_key(&p.id) == key)
    }

    /// Mutable lookup of a point by id (used by the interactive point drag to write
    /// a solved coordinate / toggle the transient `fixed` anchor flag).
    pub fn point_mut(&mut self, id: &Value) -> Option<&mut SketchPoint> {
        let key = id_key(id);
        self.points.iter_mut().find(|p| id_key(&p.id) == key)
    }

    /// The set of non-temporary constrained point ids (as [`id_key`] strings) —
    /// the fallback used to color under-constrained points when the solver did not
    /// supply per-point mobility (it always does, so this is a safety net).
    pub fn constrained_point_keys(&self) -> std::collections::HashSet<String> {
        let mut set = std::collections::HashSet::new();
        for c in &self.constraints {
            if c.temporary() {
                continue;
            }
            for pid in c.points() {
                set.insert(id_key(pid));
            }
        }
        set
    }
}

/// The solver's read-only constraint diagnostics: degrees of freedom, over/under
/// status, and per-point / per-geometry mobility (movable vs locked) derived from
/// the constraint-Jacobian null space. Keys in the mobility maps are [`id_key`]
/// strings.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct SketchDiagnostics {
    #[serde(default)]
    pub dof: i64,
    #[serde(default)]
    pub rank: i64,
    #[serde(default)]
    pub unknowns: i64,
    #[serde(default)]
    pub equations: i64,
    #[serde(default)]
    pub redundant: i64,
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub conflicting: bool,
    /// `id_key -> "movable" | "locked"` per point (`BTreeMap` for a deterministic,
    /// solver-matching key order).
    #[serde(default, rename = "pointMobility")]
    pub point_mobility: std::collections::BTreeMap<String, String>,
    #[serde(default, rename = "geometryMobility")]
    pub geometry_mobility: std::collections::BTreeMap<String, String>,
}

impl SketchDiagnostics {
    /// `Some(true)` movable, `Some(false)` locked, `None` if the solver gave no
    /// mobility for this point id.
    pub fn point_movable(&self, id: &Value) -> Option<bool> {
        self.point_mobility
            .get(&id_key(id))
            .map(|v| v == "movable")
    }

    /// `Some(true)` movable, `Some(false)` locked, `None` if unknown.
    pub fn geometry_movable(&self, id: &Value) -> Option<bool> {
        self.geometry_mobility
            .get(&id_key(id))
            .map(|v| v == "movable")
    }
}

/// Canonical string key for a point/geometry id — a faithful port of the solver's
/// `fmt_id`/`fmt_number` so mobility-map lookups (keyed by that formatting) and
/// point matching agree byte-for-byte. Integral floats print without a decimal
/// point (`10.0 -> "10"`), `-0`/`0` collapse to `"0"`.
pub fn id_key(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        Value::Number(number) => number
            .as_f64()
            .map(fmt_number)
            .unwrap_or_else(|| number.to_string()),
        Value::Bool(flag) => flag.to_string(),
        Value::Null => "null".to_string(),
        other => other.to_string(),
    }
}

fn fmt_number(x: f64) -> String {
    if x.is_nan() {
        "NaN".to_string()
    } else if x == 0.0 {
        "0".to_string()
    } else {
        format!("{x}")
    }
}

// ---------------------------------------------------------------------------
// S3a: id minting + snap-or-add (the draw tools' point/geometry factory).
//
// Points and geometries have SEPARATE id spaces; a fresh id is `max(numeric ids)
// + 1`, or a count-based id when nothing parses as a number, and is guaranteed
// not to collide (under [`id_key`]) with any existing id in the collection.
// [`SketchDoc::snap_or_add_point`] reuses an existing point within a grab radius
// so shared vertices coincide (chained lines, closed loops, arc endpoints).
// ---------------------------------------------------------------------------

impl SketchDoc {
    /// Mint the next unused POINT id (`max numeric id + 1`, else a count-based id),
    /// non-colliding within `self.points`.
    pub fn next_point_id(&self) -> Value {
        let ids: Vec<&Value> = self.points.iter().map(|p| &p.id).collect();
        mint_next_id(&ids)
    }

    /// Mint the next unused GEOMETRY id (`max numeric id + 1`, else a count-based
    /// id), non-colliding within `self.geometries`.
    pub fn next_geometry_id(&self) -> Value {
        let ids: Vec<&Value> = self.geometries.iter().map(|g| &g.id).collect();
        mint_next_id(&ids)
    }

    /// Return the id of the existing point within `radius` of `(u, v)` (the nearest
    /// one, so drawn vertices coincide), else mint a new free point at `(u, v)` and
    /// return its id. The `radius` is the same ~8px→world grab tolerance S2 uses.
    pub fn snap_or_add_point(&mut self, u: f64, v: f64, radius: f64) -> Value {
        let mut best: Option<(f64, Value)> = None;
        for p in &self.points {
            let d = ((p.x - u).powi(2) + (p.y - v).powi(2)).sqrt();
            if d <= radius && best.as_ref().map_or(true, |(bd, _)| d < *bd) {
                best = Some((d, p.id.clone()));
            }
        }
        if let Some((_, id)) = best {
            return id;
        }
        let id = self.next_point_id();
        self.points.push(SketchPoint {
            id: id.clone(),
            x: u,
            y: v,
            fixed: false,
            construction: false,
            external_reference: false,
        });
        id
    }
}

// ---------------------------------------------------------------------------
// S4: constraint id minting + geometry lookup (the constraint palette's factory).
//
// Constraints have their OWN id space (like points/geometries): a fresh id is
// `max(numeric constraint ids) + 1`. Geometry lookup mirrors [`SketchDoc::point`]
// so the palette can resolve a selected geometry ref back to its `SketchGeometry`
// (its point roles + type) to assemble a constraint's ordered point list.
// ---------------------------------------------------------------------------

impl SketchDoc {
    /// Mint the next unused CONSTRAINT id (`max numeric id + 1`, else a count-based
    /// id), non-colliding within `self.constraints`. Constraints carry their id in
    /// the raw map's `"id"` field.
    pub fn next_constraint_id(&self) -> Value {
        let ids: Vec<&Value> = self
            .constraints
            .iter()
            .filter_map(|c| c.raw.get("id"))
            .collect();
        mint_next_id(&ids)
    }

    /// Look up a geometry by id (matched via [`id_key`], mirroring [`Self::point`]).
    pub fn geometry(&self, id: &Value) -> Option<&SketchGeometry> {
        let key = id_key(id);
        self.geometries.iter().find(|g| id_key(&g.id) == key)
    }

    /// Mutable lookup of a geometry by id (used by the construction toggle to flip a
    /// selected geometry's `construction` flag in its `extra` bag).
    pub fn geometry_mut(&mut self, id: &Value) -> Option<&mut SketchGeometry> {
        let key = id_key(id);
        self.geometries.iter_mut().find(|g| id_key(&g.id) == key)
    }
}

/// Parse an id `Value` as a number (numeric ids, or numeric strings like `"12"`),
/// or `None` for a non-numeric id.
fn id_num(value: &Value) -> Option<f64> {
    match value {
        Value::Number(number) => number.as_f64(),
        Value::String(text) => text.trim().parse::<f64>().ok(),
        _ => None,
    }
}

/// Mint the next id for a collection: `max(numeric ids) + 1`, falling back to the
/// element count when nothing parses as a number, then bumped until it does not
/// collide (under [`id_key`]) with any existing id.
fn mint_next_id(ids: &[&Value]) -> Value {
    let mut max: Option<i64> = None;
    for &id in ids {
        if let Some(n) = id_num(id) {
            if n.is_finite() {
                let i = n.floor() as i64;
                max = Some(max.map_or(i, |m| m.max(i)));
            }
        }
    }
    let mut candidate = max.map(|m| m + 1).unwrap_or(ids.len() as i64);
    let existing: std::collections::HashSet<String> = ids.iter().map(|&id| id_key(id)).collect();
    while existing.contains(&id_key(&Value::from(candidate))) {
        candidate += 1;
    }
    Value::from(candidate)
}

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

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

    #[test]
    fn next_ids_are_max_numeric_plus_one_per_collection() {
        let doc = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }, { "id": 5, "x": 1.0, "y": 1.0 }],
            "geometries": [{ "id": 10, "type": "line", "points": [0, 5] }],
            "constraints": []
        }));
        // Separate id spaces: points seed 0/5 → 6; geometries seed 10 → 11.
        assert_eq!(doc.next_point_id(), json!(6));
        assert_eq!(doc.next_geometry_id(), json!(11));
    }

    #[test]
    fn next_id_falls_back_to_count_when_non_numeric_and_avoids_collision() {
        let doc = doc_from(json!({
            "points": [{ "id": "a", "x": 0.0, "y": 0.0 }, { "id": "b", "x": 1.0, "y": 1.0 }],
            "geometries": [],
            "constraints": []
        }));
        // No numeric ids → count-based (2); "2" doesn't collide with "a"/"b".
        assert_eq!(doc.next_point_id(), json!(2));
    }

    #[test]
    fn next_ids_on_empty_doc_start_at_zero() {
        let doc = SketchDoc::default();
        assert_eq!(doc.next_point_id(), json!(0));
        assert_eq!(doc.next_geometry_id(), json!(0));
    }

    #[test]
    fn next_id_handles_float_and_string_numbers() {
        let doc = doc_from(json!({
            "points": [{ "id": 3.0, "x": 0.0, "y": 0.0 }, { "id": "7", "x": 1.0, "y": 1.0 }],
            "geometries": [],
            "constraints": []
        }));
        // max(3, 7) + 1 = 8.
        assert_eq!(doc.next_point_id(), json!(8));
    }

    #[test]
    fn snap_or_add_reuses_within_radius_else_mints() {
        let mut doc = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }],
            "geometries": [],
            "constraints": []
        }));
        // Within radius → reuse id 0, no new point.
        let a = doc.snap_or_add_point(0.1, 0.0, 1.0);
        assert_eq!(id_key(&a), "0");
        assert_eq!(doc.points.len(), 1);
        // Outside radius → mint a fresh point (id 1).
        let b = doc.snap_or_add_point(10.0, 0.0, 1.0);
        assert_eq!(id_key(&b), "1");
        assert_eq!(doc.points.len(), 2);
        let p = doc.point(&b).unwrap();
        assert!((p.x - 10.0).abs() < 1e-9 && p.y.abs() < 1e-9 && !p.fixed && !p.construction);
    }

    #[test]
    fn next_constraint_id_is_max_numeric_plus_one() {
        let doc = doc_from(json!({
            "points": [{ "id": 0, "x": 0.0, "y": 0.0 }],
            "geometries": [],
            "constraints": [
                { "id": 0, "type": "", "points": [0] },
                { "id": 6, "type": "", "points": [0, 1] }
            ]
        }));
        // Constraints have their own id space: seed 0/6 → 7.
        assert_eq!(doc.next_constraint_id(), json!(7));
        // Empty constraints → count-based 0.
        let empty = SketchDoc::default();
        assert_eq!(empty.next_constraint_id(), json!(0));
    }

    #[test]
    fn geometry_lookup_matches_via_id_key() {
        let doc = doc_from(json!({
            "points": [],
            "geometries": [{ "id": 10, "type": "line", "points": [0, 1] }],
            "constraints": []
        }));
        assert_eq!(doc.geometry(&json!(10.0)).map(|g| g.geom_type.as_str()), Some("line"));
        assert!(doc.geometry(&json!(99)).is_none());
    }

    #[test]
    fn snap_or_add_picks_the_nearest_point_within_radius() {
        let mut doc = doc_from(json!({
            "points": [
                { "id": 0, "x": 0.0, "y": 0.0 },
                { "id": 1, "x": 0.5, "y": 0.0 }
            ],
            "geometries": [],
            "constraints": []
        }));
        // Closer to id 1 than id 0.
        let hit = doc.snap_or_add_point(0.6, 0.0, 2.0);
        assert_eq!(id_key(&hit), "1");
        assert_eq!(doc.points.len(), 2);
    }
}