Skip to main content

brep_render/sketch3d/
mod.rs

1//! The engine-native 3D SKETCH editor's session: the solved document, its
2//! diagnostics, the interaction state (selection, hover, armed tool, working
3//! plane), screen-space picking and the overlay tessellation.
4//!
5//! The planar sketcher (`crate::sketch`) lives in a plane's `(u, v)` frame
6//! and hit-tests there. A 3D sketch has no such frame: its points are world
7//! points, so picking is done in SCREEN space (every point and polyline
8//! sample projected through the live camera, distances measured in pixels)
9//! and a click lands in 3D through the WORKING PLANE — one of the three world
10//! planes through the sketch's current anchor (the last placed point) — or on
11//! model geometry under the cursor (see `EngineState::sketch3d_cursor_world`).
12//!
13//! The document and the solver are the kernel's ([`brep_kernel::Sketch3dDoc`],
14//! [`brep_kernel::solve_sketch3d_doc`]); the feature (`S3D`) solves the same
15//! document on every regenerate, so what the editor shows is what the model
16//! gets.
17
18use serde_json::{json, Value};
19
20pub use brep_kernel::{
21    Sketch3dConstraint, Sketch3dDiagnostics, Sketch3dDoc, Sketch3dGeometry, Sketch3dPoint,
22    SKETCH3D_CONSTRAINT_TYPES,
23};
24use brep_kernel::{sketch3d_constraint_type, Vec3};
25
26use crate::sketch::session::{constraint_ref, geometry_ref, point_ref, refs_equal, RefSelection};
27use crate::sketch::tessellate::{interaction_color, SketchTessellation, POINT_SIZE_PX};
28use crate::sketch::PlaneFrame;
29use crate::style::SketchColors;
30use crate::view::ViewCamera;
31
32/// The `set_overlay` group names. Separate from the planar sketch's so the
33/// two editors never clear each other's groups.
34pub const OVERLAY_GEOMETRY: &str = "sketch3d-geometry";
35pub const OVERLAY_POINTS: &str = "sketch3d-points";
36pub const OVERLAY_PREVIEW: &str = "sketch3d-preview";
37pub const OVERLAY_WORKPLANE: &str = "sketch3d-workplane";
38/// Every group, for a clear.
39pub const OVERLAY_GLYPHS: &str = "sketch3d-constraints";
40pub const OVERLAY_GROUPS: &[&str] =
41    &[OVERLAY_GEOMETRY, OVERLAY_POINTS, OVERLAY_PREVIEW, OVERLAY_WORKPLANE, OVERLAY_GLYPHS];
42
43/// Half-size of a constraint glyph, and how far apart stacked glyphs sit, in
44/// pixels.
45const GLYPH_HALF_PX: f64 = 6.0;
46const GLYPH_STEP_PX: f64 = 16.0;
47/// The direction glyphs step away from their anchor: not along any axis, so a
48/// glyph stays clear of its point from the usual views.
49const GLYPH_OFFSET_DIR: [f64; 3] = [0.76, 0.56, 0.33];
50
51/// Samples per arc and per bezier span when drawing / hit-testing.
52const ARC_SEGMENTS: usize = 48;
53const BEZIER_SEGMENTS_PER_SPAN: usize = 24;
54/// Half-size of the drawn working-plane square, in pixels.
55const WORKPLANE_HALF_PX: f64 = 90.0;
56/// Half-size of a drawn reference plane's square, in pixels.
57const REF_PLANE_HALF_PX: f64 = 40.0;
58
59/// The draw tools the 3D editor arms (`select` is the neutral state, stored
60/// as `None`).
61pub const TOOLS: &[&str] = &["select", "point", "line", "arc", "bezier", "pickRef"];
62
63/// The three working planes, by name.
64pub const WORK_PLANES: &[&str] = &["XY", "YZ", "XZ"];
65
66/// The working plane: one of the three world planes through an anchor.
67#[derive(Clone, Debug, PartialEq)]
68pub struct WorkPlane {
69    /// `"XY"`, `"YZ"` or `"XZ"`.
70    pub name: String,
71    /// The point the plane passes through (the sketch's current anchor).
72    pub anchor: [f64; 3],
73}
74
75impl WorkPlane {
76    pub fn new(name: &str, anchor: [f64; 3]) -> Option<Self> {
77        if !WORK_PLANES.contains(&name) {
78            return None;
79        }
80        Some(Self {
81            name: name.to_string(),
82            anchor,
83        })
84    }
85
86    /// The plane as a frame through the anchor.
87    pub fn frame(&self) -> PlaneFrame {
88        let mut frame = match self.name.as_str() {
89            "YZ" => PlaneFrame::yz(),
90            "XZ" => PlaneFrame::xz(),
91            _ => PlaneFrame::xy(),
92        };
93        frame.origin = self.anchor;
94        frame
95    }
96
97    /// The next plane in the `XY → YZ → XZ → XY` cycle.
98    pub fn next_name(&self) -> &'static str {
99        match self.name.as_str() {
100            "XY" => "YZ",
101            "YZ" => "XZ",
102            _ => "XY",
103        }
104    }
105}
106
107impl Default for WorkPlane {
108    fn default() -> Self {
109        Self {
110            name: "XY".into(),
111            anchor: [0.0; 3],
112        }
113    }
114}
115
116/// One dimension label the app draws as editable text at a projected world
117/// anchor — the 3D sibling of [`crate::sketch::dimensions::DimLabel`], in the
118/// same JSON shape so the app's label pass draws both.
119#[derive(Clone, Debug, serde::Serialize)]
120pub struct Sketch3dDimLabel {
121    pub id: Value,
122    pub text: String,
123    pub world: [f64; 3],
124    pub value: Option<f64>,
125    #[serde(rename = "valueExpr")]
126    pub value_expr: Option<String>,
127    pub mode: &'static str,
128    pub conflicting: bool,
129}
130
131/// A constraint the palette can add for the current selection: the type and
132/// the ordered point ids it would take.
133#[derive(Clone, Debug, PartialEq, serde::Serialize)]
134pub struct ApplicableConstraint {
135    /// The solver type (`distance`, `onPlane`, …).
136    #[serde(rename = "type")]
137    pub ctype: &'static str,
138    /// The palette label (`"Normal to plane"` for a line–plane `parallel`).
139    pub label: &'static str,
140    /// The ordered point ids the constraint takes.
141    pub points: Vec<Value>,
142    /// Whether it carries a value (seeded from the current geometry).
143    pub dimensional: bool,
144}
145
146/// State for one active 3D sketch.
147pub struct Sketch3dSession {
148    /// The solved document (points carry solved coordinates).
149    pub doc: Sketch3dDoc,
150    /// The last solve's diagnostics.
151    pub diagnostics: Sketch3dDiagnostics,
152    /// Selected entity refs (`{"kind":"point"|"geometry"|"constraint","id":…}`)
153    /// and the entity under the cursor — the planar session's set.
154    pub selection: RefSelection,
155    /// The armed draw tool (`None` = select).
156    pub tool: Option<String>,
157    /// The working plane a free click lands on.
158    pub work_plane: WorkPlane,
159    /// The overlay palette (the planar sketch's, shared).
160    pub colors: SketchColors,
161    /// Linked references the backdrop can no longer resolve: `(name, the
162    /// fixed point ids holding its last position)`.
163    pub lost_references: Vec<(String, Vec<Value>)>,
164}
165
166impl Sketch3dSession {
167    /// Build a session from a (possibly unsolved) doc, solving it once.
168    pub fn new(doc: Sketch3dDoc) -> Result<Self, String> {
169        let mut session = Self {
170            doc,
171            diagnostics: Sketch3dDiagnostics::default(),
172            selection: RefSelection::default(),
173            tool: None,
174            work_plane: WorkPlane::default(),
175            colors: SketchColors::default(),
176            lost_references: Vec::new(),
177        };
178        session.resolve()?;
179        Ok(session)
180    }
181
182    /// Re-solve the document in place.
183    pub fn resolve(&mut self) -> Result<(), String> {
184        let diagnostics = brep_kernel::solve_sketch3d_doc(
185            &mut self.doc,
186            &brep_kernel::Sketch3dSolveOptions::default(),
187        )?;
188        self.diagnostics = diagnostics;
189        Ok(())
190    }
191
192    // --- selection / hover -------------------------------------------------
193
194    pub fn is_selected(&self, entity_ref: &Value) -> bool {
195        self.selection.is_selected(entity_ref)
196    }
197
198    pub fn toggle_selection(&mut self, entity_ref: Value) {
199        self.selection.toggle(entity_ref)
200    }
201
202    pub fn clear_selection(&mut self) {
203        self.selection.clear()
204    }
205
206    pub fn set_hover(&mut self, entity_ref: Option<Value>) {
207        self.selection.hovered = entity_ref;
208    }
209
210    /// The selected entity refs split by kind: `(point ids, geometry ids,
211    /// constraint ids)`.
212    pub fn selection_by_kind(&self) -> (Vec<Value>, Vec<Value>, Vec<Value>) {
213        let mut points = Vec::new();
214        let mut geometries = Vec::new();
215        let mut constraints = Vec::new();
216        for r in &self.selection.items {
217            let Some(id) = r.get("id").cloned() else { continue };
218            match r.get("kind").and_then(Value::as_str) {
219                Some("point") => points.push(id),
220                Some("geometry") => geometries.push(id),
221                Some("constraint") => constraints.push(id),
222                _ => {}
223            }
224        }
225        (points, geometries, constraints)
226    }
227
228    // --- geometry sampling ---------------------------------------------------
229
230    /// A point's world position.
231    pub fn point_world(&self, id: &Value) -> Option<[f64; 3]> {
232        self.doc.point(id).map(|p| [p.x, p.y, p.z])
233    }
234
235    /// Sample a geometry into an ordered world polyline (`None` for a missing
236    /// point or a degenerate shape). A `point` geometry samples to nothing; a
237    /// reference `plane` draws as a square about its origin, sized in pixels.
238    pub fn sample_geometry(&self, geometry: &Sketch3dGeometry, world_per_pixel: f64) -> Option<Vec<[f64; 3]>> {
239        let positions = self.doc.geometry_positions(geometry)?;
240        let out: Vec<[f64; 3]> = match (geometry.geom_type.as_str(), positions.len()) {
241            ("line", n) if n >= 2 => vec![arr(positions[0]), arr(positions[1])],
242            ("arc", n) if n >= 3 => sample_arc(positions[0], positions[1], positions[2])?,
243            ("bezier", n) if n >= 4 && (n - 1) % 3 == 0 => sample_bezier(&positions),
244            ("plane", n) if n >= 2 => {
245                let frame = plane_frame_of(positions[0], positions[1])?;
246                plane_square(&frame, REF_PLANE_HALF_PX * world_per_pixel)
247            }
248            _ => return None,
249        };
250        (out.len() >= 2).then_some(out)
251    }
252
253    // --- screen-space picking ------------------------------------------------
254
255    /// The entity under CSS-pixel `(x, y)` within `radius_px`: a POINT wins over
256    /// geometry when one is in range, else the nearest geometry whose projected
257    /// polyline passes within range. Construction geometry is pickable.
258    pub fn pick_entity(&self, camera: &ViewCamera, x: f64, y: f64, radius_px: f64) -> Option<Value> {
259        let mut best_pt: Option<(f64, &Value)> = None;
260        for p in &self.doc.points {
261            let Some((sx, sy)) = project(camera, [p.x, p.y, p.z]) else { continue };
262            let d = (sx - x).hypot(sy - y);
263            if d <= radius_px && best_pt.map_or(true, |(bd, _)| d < bd) {
264                best_pt = Some((d, &p.id));
265            }
266        }
267        if let Some((_, id)) = best_pt {
268            return Some(point_ref(id));
269        }
270        let wpp = camera.world_per_pixel();
271        let mut best_glyph: Option<(f64, Value)> = None;
272        for (id, centre, _) in self.constraint_glyphs(wpp) {
273            let Some((sx, sy)) = project(camera, centre) else { continue };
274            let d = (sx - x).hypot(sy - y);
275            if d <= radius_px.min(GLYPH_HALF_PX) && best_glyph.as_ref().map_or(true, |(bd, _)| d < *bd) {
276                best_glyph = Some((d, id));
277            }
278        }
279        let mut best_geo: Option<(f64, &Value)> = None;
280        for g in &self.doc.geometries {
281            let Some(poly) = self.sample_geometry(g, wpp) else { continue };
282            let screen: Vec<Option<(f64, f64)>> = poly.iter().map(|w| project(camera, *w)).collect();
283            let mut dmin = f64::INFINITY;
284            for pair in screen.windows(2) {
285                let (Some(a), Some(b)) = (pair[0], pair[1]) else { continue };
286                let d = crate::geometry2d::point_segment_distance((x, y), a, b).0;
287                if d < dmin {
288                    dmin = d;
289                }
290            }
291            if dmin <= radius_px && best_geo.map_or(true, |(bd, _)| dmin < bd) {
292                best_geo = Some((dmin, &g.id));
293            }
294        }
295        // A glyph near a line must not steal a click aimed at the line.
296        match (best_glyph, best_geo) {
297            (Some((glyph, id)), Some((geo, _))) if glyph < geo => Some(entity_constraint_ref(&id)),
298            (Some((_, id)), None) => Some(entity_constraint_ref(&id)),
299            (_, geo) => geo.map(|(_, id)| geometry_ref(id)),
300        }
301    }
302
303    /// One mark per non-dimensional constraint: `(id, centre, shape)`. Marks
304    /// sharing an anchor are stacked, so each stays selectable.
305    pub fn constraint_glyphs(&self, world_per_pixel: f64) -> Vec<(Value, [f64; 3], &'static str)> {
306        let mut stacks: std::collections::HashMap<[i64; 3], usize> = std::collections::HashMap::new();
307        let step = GLYPH_STEP_PX * world_per_pixel;
308        let mut out = Vec::new();
309        for constraint in &self.doc.constraints {
310            let (Some(id), Some(ctype)) = (constraint.id(), constraint.ctype()) else { continue };
311            if sketch3d_constraint_type(ctype).map_or(true, |t| t.dimensional) {
312                continue;
313            }
314            let ids = constraint.points();
315            let at = |i: usize| ids.get(i).and_then(|id| self.point_world(id));
316            let (anchor, shape) = match ctype {
317                "fixed" | "coincident" => (at(0), "star"),
318                "onLine" | "onPlane" | "onArc" | "onCircle" | "onCurve" | "midpoint" => (at(0), "diamond"),
319                "symmetric" => (at(0).zip(at(1)).map(|(a, b)| [0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1]), 0.5 * (a[2] + b[2])]), "diamond"),
320                _ => (at(0).zip(at(1)).map(|(a, b)| [0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1]), 0.5 * (a[2] + b[2])]), "box"),
321            };
322            let Some(anchor) = anchor else { continue };
323            let key = anchor.map(|c| (c / step.max(1e-9)).round() as i64);
324            let slot = stacks.entry(key).or_insert(0);
325            *slot += 1;
326            let distance = step * *slot as f64;
327            let centre = [
328                anchor[0] + GLYPH_OFFSET_DIR[0] * distance,
329                anchor[1] + GLYPH_OFFSET_DIR[1] * distance,
330                anchor[2] + GLYPH_OFFSET_DIR[2] * distance,
331            ];
332            out.push((id.clone(), centre, shape));
333        }
334        out
335    }
336
337    fn glyph_tessellation(&self, world_per_pixel: f64) -> SketchTessellation {
338        let mut out = SketchTessellation::default();
339        let half = GLYPH_HALF_PX * world_per_pixel;
340        let colors = &self.colors;
341        for (id, c, shape) in self.constraint_glyphs(world_per_pixel) {
342            let color = interaction_color(colors, colors.preview, self.selection.hovered.as_ref(), &self.selection.items, "constraint", &id);
343            let rgb = rgb_of(color);
344            let at = |x: f64, y: f64, z: f64| [c[0] + x * half, c[1] + y * half, c[2] + z * half];
345            let segments: Vec<([f64; 3], [f64; 3])> = match shape {
346                "star" => vec![(at(-1.0, 0.0, 0.0), at(1.0, 0.0, 0.0)), (at(0.0, -1.0, 0.0), at(0.0, 1.0, 0.0)), (at(0.0, 0.0, -1.0), at(0.0, 0.0, 1.0))],
347                "diamond" => {
348                    let ring = [at(1.0, 0.0, 0.0), at(0.0, 1.0, 0.0), at(-1.0, 0.0, 0.0), at(0.0, -1.0, 0.0)];
349                    (0..4)
350                        .flat_map(|i| [(ring[i], ring[(i + 1) % 4]), (ring[i], at(0.0, 0.0, 1.0)), (ring[i], at(0.0, 0.0, -1.0))])
351                        .collect()
352                }
353                _ => {
354                    let corner = |i: usize| at(if i & 1 == 0 { -0.8 } else { 0.8 }, if i & 2 == 0 { -0.8 } else { 0.8 }, if i & 4 == 0 { -0.8 } else { 0.8 });
355                    (0..8usize)
356                        .flat_map(|i| [1usize, 2, 4].map(|bit| (i, i | bit)))
357                        .filter(|(i, j)| i != j)
358                        .map(|(i, j)| (corner(i), corner(j)))
359                        .collect()
360                }
361            };
362            for (a, b) in segments {
363                push_seg(&mut out, a, b, rgb);
364            }
365        }
366        out
367    }
368
369    /// The nearest DRAGGABLE point under `(x, y)` (id + its authored `fixed`
370    /// flag): a point the solver reports movable.
371    pub fn pick_draggable_point(&self, camera: &ViewCamera, x: f64, y: f64, radius_px: f64) -> Option<(Value, bool)> {
372        let mut best: Option<(f64, &Sketch3dPoint)> = None;
373        for p in &self.doc.points {
374            if self.diagnostics.point_movable(&p.id) != Some(true) {
375                continue;
376            }
377            let Some((sx, sy)) = project(camera, [p.x, p.y, p.z]) else { continue };
378            let d = (sx - x).hypot(sy - y);
379            if d <= radius_px && best.map_or(true, |(bd, _)| d < bd) {
380                best = Some((d, p));
381            }
382        }
383        best.map(|(_, p)| (p.id.clone(), p.fixed))
384    }
385
386    /// The points a drag of `entity_ref` moves: the one point, or every
387    /// (deduped, movable) point of a geometry; `None` for a locked point or a
388    /// constraint.
389    pub fn drag_points_from_ref(&self, entity_ref: &Value) -> Option<Vec<(Value, [f64; 3], bool)>> {
390        let id = entity_ref.get("id")?;
391        match entity_ref.get("kind").and_then(Value::as_str) {
392            Some("point") => {
393                if self.diagnostics.point_movable(id) != Some(true) {
394                    return None;
395                }
396                let p = self.doc.point(id)?;
397                Some(vec![(p.id.clone(), [p.x, p.y, p.z], p.fixed)])
398            }
399            Some("geometry") => {
400                let g = self.doc.geometry(id)?;
401                if g.geom_type == "plane" {
402                    return None;
403                }
404                let mut out: Vec<(Value, [f64; 3], bool)> = Vec::new();
405                for pid in &g.points {
406                    if out.iter().any(|(seen, _, _)| refs_equal(&point_ref(seen), &point_ref(pid))) {
407                        continue;
408                    }
409                    let Some(p) = self.doc.point(pid) else { continue };
410                    if self.diagnostics.point_movable(pid) != Some(true) {
411                        continue;
412                    }
413                    out.push((p.id.clone(), [p.x, p.y, p.z], p.fixed));
414                }
415                (!out.is_empty()).then_some(out)
416            }
417            _ => None,
418        }
419    }
420
421    // --- overlay -----------------------------------------------------------
422
423    /// Tessellate the solved sketch with hover + selection coloring.
424    pub fn tessellation(&self, world_per_pixel: f64) -> SketchTessellation {
425        let mut out = SketchTessellation::default();
426        let colors = &self.colors;
427        let hovered = self.selection.hovered.as_ref();
428        let selection = &self.selection.items;
429        let dash_len = (8.0 * world_per_pixel).max(0.02);
430        let gap_len = (6.0 * world_per_pixel).max(0.01);
431        for g in &self.doc.geometries {
432            let Some(pts) = self.sample_geometry(g, world_per_pixel) else { continue };
433            let mobility = match self.diagnostics.geometry_movable(&g.id) {
434                None => colors.geometry,
435                Some(true) => colors.movable,
436                Some(false) => colors.locked,
437            };
438            let color = interaction_color(colors, mobility, hovered, selection, "geometry", &g.id);
439            let rgb = rgb_of(color);
440            if g.construction() {
441                push_dashed(&mut out, &pts, rgb, dash_len, gap_len);
442            } else {
443                push_solid(&mut out, &pts, rgb);
444            }
445        }
446        for p in &self.doc.points {
447            let base = if p.construction {
448                // Locked construction points take the locked colour, as lines do.
449                if self.diagnostics.point_movable(&p.id) == Some(false) {
450                    colors.locked
451                } else {
452                    colors.construction_point
453                }
454            } else {
455                match self.diagnostics.point_movable(&p.id) {
456                    Some(true) => colors.movable,
457                    Some(false) => colors.locked,
458                    None => colors.point,
459                }
460            };
461            let color = interaction_color(colors, base, hovered, selection, "point", &p.id);
462            out.point_positions.extend_from_slice(&[p.x as f32, p.y as f32, p.z as f32]);
463            out.point_colors.extend_from_slice(&rgb_of(color));
464        }
465        out
466    }
467
468    /// The `set_overlay` JSON for the solved geometry + points.
469    pub fn overlay_json(&self, world_per_pixel: f64) -> String {
470        let tess = self.tessellation(world_per_pixel);
471        let glyphs = self.glyph_tessellation(world_per_pixel);
472        json!({
473            "groups": [
474                {
475                    "name": OVERLAY_GLYPHS,
476                    "renderOrder": 10001,
477                    "lines": { "positions": glyphs.line_positions, "colors": glyphs.line_colors },
478                },
479                {
480                    "name": OVERLAY_GEOMETRY,
481                    "renderOrder": 10000,
482                    "lines": { "positions": tess.line_positions, "colors": tess.line_colors },
483                },
484                {
485                    "name": OVERLAY_POINTS,
486                    "renderOrder": 10001,
487                    "points": {
488                        "positions": tess.point_positions,
489                        "colors": tess.point_colors,
490                        "size": POINT_SIZE_PX,
491                    },
492                },
493            ]
494        })
495        .to_string()
496    }
497
498    /// The `set_overlay` JSON for the armed tool's rubber band: the pending
499    /// points joined, and the last one joined to the hovered world point.
500    /// Always the `sketch3d-preview` group (empty when nothing is pending).
501    pub fn preview_overlay_json(&self, pending: &[Value], hover: Option<[f64; 3]>) -> String {
502        let mut pts: Vec<[f64; 3]> = pending.iter().filter_map(|id| self.point_world(id)).collect();
503        if let Some(h) = hover {
504            pts.push(h);
505        }
506        let mut out = SketchTessellation::default();
507        let rgb = rgb_of(self.colors.preview);
508        match self.tool.as_deref() {
509            Some("arc") if pts.len() >= 3 => {
510                // center, start, end: preview the arc itself.
511                if let Some(arc) = sample_arc(vec(pts[0]), vec(pts[1]), vec(pts[2])) {
512                    push_solid(&mut out, &arc, rgb);
513                }
514                push_solid(&mut out, &pts[..2], rgb);
515            }
516            Some("bezier") if pts.len() == 4 => {
517                let controls: Vec<Vec3> = pts.iter().map(|p| vec(*p)).collect();
518                push_solid(&mut out, &sample_bezier(&controls), rgb);
519                push_solid(&mut out, &pts, rgb);
520            }
521            _ if pts.len() >= 2 => push_solid(&mut out, &pts, rgb),
522            _ => {}
523        }
524        json!({
525            "groups": [{
526                "name": OVERLAY_PREVIEW,
527                "renderOrder": 10002,
528                "lines": { "positions": out.line_positions, "colors": out.line_colors },
529            }]
530        })
531        .to_string()
532    }
533
534    /// The `set_overlay` JSON for the working plane: a dashed square through
535    /// the anchor with its two in-plane axes, sized in pixels so it reads the
536    /// same at any zoom. Hidden (empty group) while the select tool is armed —
537    /// it matters only where a click lands.
538    pub fn workplane_overlay_json(&self, world_per_pixel: f64) -> String {
539        let mut out = SketchTessellation::default();
540        if self.tool.is_some() {
541            let frame = self.work_plane.frame();
542            let half = WORKPLANE_HALF_PX * world_per_pixel;
543            let rgb = rgb_of(self.colors.preview);
544            let square = plane_square(&frame, half);
545            push_dashed(&mut out, &square, rgb, (8.0 * world_per_pixel).max(0.02), (6.0 * world_per_pixel).max(0.01));
546            let o = frame.origin;
547            push_solid(&mut out, &[frame.to_world(-half, 0.0), frame.to_world(half, 0.0)], rgb);
548            push_solid(&mut out, &[frame.to_world(0.0, -half), frame.to_world(0.0, half)], rgb);
549            let _ = o;
550        }
551        json!({
552            "groups": [{
553                "name": OVERLAY_WORKPLANE,
554                "renderOrder": 9999,
555                "lines": { "positions": out.line_positions, "colors": out.line_colors },
556            }]
557        })
558        .to_string()
559    }
560
561    // --- dimensions ------------------------------------------------------------
562
563    /// One label per dimensional constraint, anchored at the dimension's
564    /// natural midpoint.
565    pub fn dimension_labels(&self) -> Vec<Sketch3dDimLabel> {
566        let mut out = Vec::new();
567        for c in &self.doc.constraints {
568            let (Some(ctype), Some(id)) = (c.ctype(), c.id()) else { continue };
569            let Some(spec) = sketch3d_constraint_type(ctype) else { continue };
570            if !spec.dimensional {
571                continue;
572            }
573            let pts: Vec<[f64; 3]> = c.points().iter().filter_map(|pid| self.point_world(pid)).collect();
574            if pts.len() < spec.arity {
575                continue;
576            }
577            let (world, mode) = match ctype {
578                "distance" => (mid(pts[0], pts[1]), "distance"),
579                "angle" => (mid(mid(pts[0], pts[1]), mid(pts[2], pts[3])), "angle"),
580                _ => (pts[0], "distance"),
581            };
582            let value = c.value();
583            let text = match (mode, value) {
584                ("angle", Some(v)) => format!("{v:.2}°"),
585                (_, Some(v)) => format!("{v:.3}"),
586                _ => "?".to_string(),
587            };
588            out.push(Sketch3dDimLabel {
589                id: id.clone(),
590                text,
591                world,
592                value,
593                value_expr: c.raw.get("valueExpr").and_then(Value::as_str).map(String::from),
594                mode,
595                conflicting: self.diagnostics.constraint_conflicting(id),
596            });
597        }
598        out
599    }
600
601    // --- the constraint palette ------------------------------------------------
602
603    /// The constraints the palette offers for the current selection, each with
604    /// the point ids it would take, in palette order.
605    pub fn applicable_constraints(&self) -> Vec<ApplicableConstraint> {
606        let (points, geometries, _) = self.selection_by_kind();
607        let geos: Vec<&Sketch3dGeometry> = geometries.iter().filter_map(|id| self.doc.geometry(id)).collect();
608        let lines: Vec<&Sketch3dGeometry> = geos.iter().copied().filter(|g| g.geom_type == "line" && g.points.len() >= 2).collect();
609        let arcs: Vec<&Sketch3dGeometry> = geos.iter().copied().filter(|g| g.geom_type == "arc" && g.points.len() >= 3).collect();
610        let planes: Vec<&Sketch3dGeometry> = geos.iter().copied().filter(|g| g.geom_type == "plane" && g.points.len() >= 2).collect();
611        let others = geos.len() - lines.len() - arcs.len() - planes.len();
612        let mut out = Vec::new();
613        let mut push = |ctype: &'static str, label: &'static str, ids: Vec<Value>| {
614            let dimensional = sketch3d_constraint_type(ctype).map_or(false, |t| t.dimensional);
615            out.push(ApplicableConstraint { ctype, label, points: ids, dimensional });
616        };
617        let line_pts = |g: &Sketch3dGeometry| vec![g.points[0].clone(), g.points[1].clone()];
618        let plane_pts = |g: &Sketch3dGeometry| vec![g.points[0].clone(), g.points[1].clone()];
619        if let ([point], [curve]) = (points.as_slice(), geos.as_slice()) {
620            if curve.geom_type == "bezier" && curve.points.len() >= 4 {
621                let mut ids = vec![point.clone()];
622                ids.extend(curve.points.iter().cloned());
623                push("onCurve", "On curve", ids);
624                return out;
625            }
626        }
627        if others > 0 {
628            return out;
629        }
630        match (points.len(), lines.len(), arcs.len(), planes.len()) {
631            (1, 0, 0, 0) => {
632                let fixed = self.doc.point(&points[0]).map_or(false, |p| p.fixed);
633                if !fixed {
634                    push("fixed", "Fix", vec![points[0].clone()]);
635                }
636            }
637            (2, 0, 0, 0) => {
638                push("coincident", "Coincident", vec![points[0].clone(), points[1].clone()]);
639                push("distance", "Distance", vec![points[0].clone(), points[1].clone()]);
640            }
641            (0, 1, 0, 0) => {
642                let ids = line_pts(lines[0]);
643                push("distance", "Length", ids.clone());
644                push("alongX", "Along X", ids.clone());
645                push("alongY", "Along Y", ids.clone());
646                push("alongZ", "Along Z", ids);
647            }
648            (0, 2, 0, 0) => {
649                let mut ids = line_pts(lines[0]);
650                ids.extend(line_pts(lines[1]));
651                push("parallel", "Parallel", ids.clone());
652                push("perpendicular", "Perpendicular", ids.clone());
653                push("angle", "Angle", ids.clone());
654                push("equal", "Equal length", ids);
655            }
656            // A linked circle is published as its axis line, flagged `circle`.
657            (1, 1, 0, 0) if lines[0].extra.get("circle").and_then(Value::as_bool) == Some(true) => {
658                let mut ids = vec![points[0].clone()];
659                ids.extend(line_pts(lines[0]));
660                push("coincident", "At centre", vec![points[0].clone(), lines[0].points[0].clone()]);
661                push("onCircle", "On circle", ids);
662            }
663            (1, 1, 0, 0) => {
664                let mut ids = vec![points[0].clone()];
665                ids.extend(line_pts(lines[0]));
666                push("onLine", "On line", ids.clone());
667                push("lineDistance", "Distance to line", ids.clone());
668                push("midpoint", "At midpoint", ids);
669            }
670            (1, 0, 1, 0) => {
671                let mut ids = vec![points[0].clone()];
672                ids.extend(arcs[0].points[..3].iter().cloned());
673                push("coincident", "At centre", vec![points[0].clone(), arcs[0].points[0].clone()]);
674                push("onArc", "On arc", ids);
675            }
676            (2, 0, 0, 1) => {
677                let mut ids = vec![points[0].clone(), points[1].clone()];
678                ids.extend(plane_pts(planes[0]));
679                push("symmetric", "Symmetric", ids);
680            }
681            (1, 0, 0, 1) => {
682                let mut ids = vec![points[0].clone()];
683                ids.extend(plane_pts(planes[0]));
684                push("onPlane", "On plane", ids.clone());
685                push("planeDistance", "Distance to plane", ids);
686            }
687            (0, 1, 0, 1) => {
688                let mut ids = line_pts(lines[0]);
689                ids.extend(plane_pts(planes[0]));
690                push("parallel", "Normal to plane", ids.clone());
691                push("perpendicular", "Parallel to plane", ids);
692            }
693            (0, 1, 1, 0) => {
694                let mut ids = line_pts(lines[0]);
695                ids.extend(arcs[0].points[..3].iter().cloned());
696                push("tangent", "Tangent", ids);
697            }
698            (0, 0, 1, 0) => {
699                let a = &arcs[0].points;
700                push("distance", "Radius", vec![a[0].clone(), a[1].clone()]);
701            }
702            (0, 0, 2, 0) => {
703                let (a, b) = (&arcs[0].points, &arcs[1].points);
704                push("equal", "Equal radius", vec![a[0].clone(), a[1].clone(), b[0].clone(), b[1].clone()]);
705            }
706            _ => {}
707        }
708        out
709    }
710
711    /// The value a dimensional constraint over `ids` would be SEEDED with — the
712    /// current measurement, so adding a dimension changes nothing until the
713    /// user edits it.
714    pub fn measure(&self, ctype: &str, ids: &[Value]) -> Option<f64> {
715        let p: Vec<Vec3> = ids.iter().filter_map(|id| self.point_world(id)).map(vec).collect();
716        match ctype {
717            "distance" if p.len() >= 2 => Some(p[1].sub(p[0]).length()),
718            "lineDistance" if p.len() >= 3 => {
719                let d = p[2].sub(p[1]).normalized().ok()?;
720                let v = p[0].sub(p[1]);
721                Some(v.sub(d.scale(d.dot(v))).length())
722            }
723            "planeDistance" if p.len() >= 3 => {
724                let n = p[2].sub(p[1]).normalized().ok()?;
725                Some(n.dot(p[0].sub(p[1])))
726            }
727            "angle" if p.len() >= 4 => {
728                let a = p[1].sub(p[0]).normalized().ok()?;
729                let b = p[3].sub(p[2]).normalized().ok()?;
730                Some(a.dot(b).clamp(-1.0, 1.0).acos().to_degrees())
731            }
732            _ => None,
733        }
734    }
735
736    /// The name of the lost reference a constraint depends on, if any.
737    pub fn lost_reference_of(&self, constraint: &Sketch3dConstraint) -> Option<&str> {
738        let key = brep_kernel::sketch_id_key;
739        self.lost_references
740            .iter()
741            .find(|(_, ids)| constraint.points().iter().any(|p| ids.iter().any(|id| key(id) == key(p))))
742            .map(|(name, _)| name.as_str())
743    }
744
745    /// One sentence per lost reference, naming the constraints that need it.
746    pub fn lost_reference_messages(&self) -> Vec<String> {
747        self.lost_references
748            .iter()
749            .map(|(name, _)| {
750                let needed: Vec<String> = self
751                    .doc
752                    .constraints
753                    .iter()
754                    .filter(|c| self.lost_reference_of(c) == Some(name.as_str()))
755                    .map(|c| format!("{} {}", c.ctype().unwrap_or("?"), c.id().map(brep_kernel::sketch_id_key).unwrap_or_default()))
756                    .collect();
757                if needed.is_empty() {
758                    format!("3D sketch: reference '{name}' no longer resolves; it keeps its last position")
759                } else {
760                    format!(
761                        "3D sketch: reference '{name}' no longer resolves; it keeps its last position, needed by constraint {}",
762                        needed.join(", ")
763                    )
764                }
765            })
766            .collect()
767    }
768
769    /// Rows for the entity lists: `(kind, id, label)` per point, geometry and
770    /// constraint, with the mobility / conflict state the list colors by.
771    pub fn entity_rows_json(&self) -> Value {
772        let points: Vec<Value> = self
773            .doc
774            .points
775            .iter()
776            .map(|p| {
777                json!({
778                    "id": p.id,
779                    "fixed": p.fixed,
780                    "construction": p.construction,
781                    "externalReference": p.external_reference,
782                    "movable": self.diagnostics.point_movable(&p.id),
783                    "position": [p.x, p.y, p.z],
784                })
785            })
786            .collect();
787        let geometries: Vec<Value> = self
788            .doc
789            .geometries
790            .iter()
791            .map(|g| {
792                json!({
793                    "id": g.id,
794                    "type": g.geom_type,
795                    "construction": g.construction(),
796                    "movable": self.diagnostics.geometry_movable(&g.id),
797                    "points": g.points,
798                })
799            })
800            .collect();
801        let constraints: Vec<Value> = self
802            .doc
803            .constraints
804            .iter()
805            .map(|c| {
806                json!({
807                    "id": c.id(),
808                    "type": c.ctype(),
809                    "points": c.points(),
810                    "value": c.value(),
811                    "conflicting": c.id().map_or(false, |id| self.diagnostics.constraint_conflicting(id)),
812                    "lostReference": self.lost_reference_of(c),
813                })
814            })
815            .collect();
816        json!({ "points": points, "geometries": geometries, "constraints": constraints })
817    }
818}
819
820// ---------------------------------------------------------------------------
821// Entity refs (shared shape with the planar sketch)
822// ---------------------------------------------------------------------------
823
824pub fn entity_point_ref(id: &Value) -> Value {
825    point_ref(id)
826}
827
828pub fn entity_geometry_ref(id: &Value) -> Value {
829    geometry_ref(id)
830}
831
832pub fn entity_constraint_ref(id: &Value) -> Value {
833    constraint_ref(id)
834}
835
836// ---------------------------------------------------------------------------
837// Geometry helpers
838// ---------------------------------------------------------------------------
839
840fn arr(v: Vec3) -> [f64; 3] {
841    [v.x, v.y, v.z]
842}
843
844fn vec(a: [f64; 3]) -> Vec3 {
845    Vec3::new(a[0], a[1], a[2])
846}
847
848fn mid(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
849    [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5, (a[2] + b[2]) * 0.5]
850}
851
852/// Project a world point to CSS pixels, `None` when behind the eye.
853pub fn project(camera: &ViewCamera, world: [f64; 3]) -> Option<(f64, f64)> {
854    if !camera.projectable(world) {
855        return None;
856    }
857    let (x, y, _) = camera.project(world);
858    Some((x, y))
859}
860
861/// The minor arc from `start` to `end` about `center`, sampled; `None` when the
862/// three points are collinear or the radius is zero.
863pub fn sample_arc(center: Vec3, start: Vec3, end: Vec3) -> Option<Vec<[f64; 3]>> {
864    let rs = start.sub(center);
865    let re = end.sub(center);
866    let radius = rs.length();
867    if radius <= 1e-12 {
868        return None;
869    }
870    let normal = rs.cross(re);
871    if normal.length() <= 1e-12 * radius * radius {
872        return None;
873    }
874    let x_axis = rs.normalized().ok()?;
875    let y_axis = normal.normalized().ok()?.cross(x_axis).normalized().ok()?;
876    let sweep = re.dot(y_axis).atan2(re.dot(x_axis));
877    let sweep = if sweep <= 0.0 { sweep + std::f64::consts::TAU } else { sweep };
878    let r_end = re.length();
879    let mut out = Vec::with_capacity(ARC_SEGMENTS + 1);
880    for i in 0..=ARC_SEGMENTS {
881        let t = i as f64 / ARC_SEGMENTS as f64;
882        let a = sweep * t;
883        // Blend the radius from start to end so an arc whose implied
884        // equal-radius row is not yet satisfied still draws through both ends.
885        let r = radius + (r_end - radius) * t;
886        out.push(arr(center.add(x_axis.scale(r * a.cos())).add(y_axis.scale(r * a.sin()))));
887    }
888    Some(out)
889}
890
891/// A cubic bezier chain (`3n+1` controls), sampled per span.
892pub fn sample_bezier(controls: &[Vec3]) -> Vec<[f64; 3]> {
893    let span_count = controls.len().saturating_sub(1) / 3;
894    let mut out = Vec::with_capacity(span_count * BEZIER_SEGMENTS_PER_SPAN + 1);
895    for span in 0..span_count {
896        let p = &controls[span * 3..span * 3 + 4];
897        let first = if span == 0 { 0 } else { 1 };
898        for i in first..=BEZIER_SEGMENTS_PER_SPAN {
899            let t = i as f64 / BEZIER_SEGMENTS_PER_SPAN as f64;
900            let u = 1.0 - t;
901            let point = p[0]
902                .scale(u * u * u)
903                .add(p[1].scale(3.0 * u * u * t))
904                .add(p[2].scale(3.0 * u * t * t))
905                .add(p[3].scale(t * t * t));
906            out.push(arr(point));
907        }
908    }
909    out
910}
911
912/// The frame of a reference plane `[origin, normalTip]`.
913pub fn plane_frame_of(origin: Vec3, tip: Vec3) -> Option<PlaneFrame> {
914    let normal = tip.sub(origin);
915    if normal.length() <= 1e-12 {
916        return None;
917    }
918    Some(PlaneFrame::from_normal(arr(origin), arr(normal)))
919}
920
921/// A closed square of half-size `half` in `frame`, as a 5-point polyline.
922fn plane_square(frame: &PlaneFrame, half: f64) -> Vec<[f64; 3]> {
923    vec![
924        frame.to_world(-half, -half),
925        frame.to_world(half, -half),
926        frame.to_world(half, half),
927        frame.to_world(-half, half),
928        frame.to_world(-half, -half),
929    ]
930}
931
932fn rgb_of(color: u32) -> [f32; 3] {
933    [
934        ((color >> 16) & 0xff) as f32 / 255.0,
935        ((color >> 8) & 0xff) as f32 / 255.0,
936        (color & 0xff) as f32 / 255.0,
937    ]
938}
939
940fn push_seg(out: &mut SketchTessellation, a: [f64; 3], b: [f64; 3], rgb: [f32; 3]) {
941    out.line_positions.extend_from_slice(&[
942        a[0] as f32, a[1] as f32, a[2] as f32, b[0] as f32, b[1] as f32, b[2] as f32,
943    ]);
944    out.line_colors.extend_from_slice(&[rgb[0], rgb[1], rgb[2], rgb[0], rgb[1], rgb[2]]);
945}
946
947fn push_solid(out: &mut SketchTessellation, pts: &[[f64; 3]], rgb: [f32; 3]) {
948    for pair in pts.windows(2) {
949        push_seg(out, pair[0], pair[1], rgb);
950    }
951}
952
953fn push_dashed(out: &mut SketchTessellation, pts: &[[f64; 3]], rgb: [f32; 3], dl: f64, gl: f64) {
954    let mut on = true;
955    let mut need = dl;
956    for pair in pts.windows(2) {
957        let (a, b) = (vec(pair[0]), vec(pair[1]));
958        let seg = b.sub(a);
959        let len = seg.length();
960        if len <= 0.0 {
961            continue;
962        }
963        let dir = seg.scale(1.0 / len);
964        let mut t = 0.0;
965        while t < len {
966            let step = need.min(len - t);
967            if on {
968                push_seg(out, arr(a.add(dir.scale(t))), arr(a.add(dir.scale(t + step))), rgb);
969            }
970            t += step;
971            need -= step;
972            if need <= 1e-12 {
973                on = !on;
974                need = if on { dl } else { gl };
975            }
976        }
977    }
978}
979