brep_render/constraint_overlays.rs
1//! Assembly-constraint VIEWPORT overlays — the CONSTRAINT twin
2//! of [`crate::feature_dimensions`].
3//!
4//! Pure builders: the kernel's `assembly_overlay_json` rows (per-constraint world
5//! anchors / directions / status / measured value) + the `assembly_state_json`
6//! constraint list (for `inputParams` — expression detection + element refs) fold
7//! into [`ConstraintOverlay`] records, which bake into the SAME leader/arrow/arc
8//! triangle buffers the feature-dimension gizmo draws (via
9//! [`crate::feature_dimensions::leaders_buffers`] — nothing re-rolled, per the
10//! UI-consistency directive):
11//!
12//! * **distance** → a LINEAR dimension annotation — the silver rod + orange
13//! cone arrow + orange origin sphere, GRABBABLE (drag edits
14//! `inputParams.distance`, commit auto-solves). Plane-based pairings draw the
15//! TRUE dimension perpendicular to the BASE face (the perpendicular-foot
16//! construction on `build_distance_annotation`, matching the kernel's
17//! signed `d = (P_other − P_base)·n̂_base` convention); plane-less pairings
18//! keep the plain anchor-to-anchor leader.
19//! * **angle** → an ANGULAR annotation (the screen-constant arc + orange sweep-end
20//! handle + red dashed zero reference + green axis), GRABBABLE (drag edits
21//! `inputParams.angle`).
22//! * **center** → two plain leaders drawn BY ROLE from the row's `groups`
23//! (the kernel mapper's inferred `[width pair, tab]` element-index groups):
24//! the width span between its two faces, and a leader from that span's
25//! midpoint (which lies on the mid-plane) to the tab's anchor centroid; the
26//! label sits at the width midpoint. Pick order never shapes the drawing.
27//! * everything else (coincident / parallel / perpendicular / concentric /
28//! tangent / touch_align / fixed) → a plain anchor-to-anchor leader line +
29//! label anchor only — never a handle.
30//!
31//! Dragging is DISABLED for a distance/angle whose param is a non-numeric
32//! EXPRESSION string (matches how feature dimensions treat expression-driven
33//! params); the engine consults [`ConstraintOverlay::draggable`].
34//!
35//! The interactive state machine (hit regions, drag preview, the
36//! `assembly_update_constraint_json` commit) lives in
37//! `engine_state/assembly_overlay.rs`; this module stays camera-free and pure so
38//! the geometry is unit-testable from canned JSON payloads.
39
40use serde_json::Value;
41
42use crate::feature_dimensions::{
43 append_plain_leader, leaders_buffers, FeatureDimAnnotation,
44};
45
46/// Which overlay family a constraint renders as.
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum ConstraintOverlayKind {
49 /// A grabbable linear dimension arrow pair (`distance`).
50 Distance,
51 /// A grabbable angle arc (`angle`).
52 Angle,
53 /// A non-interactive leader + label (every other type).
54 Leader,
55}
56
57/// One constraint's overlay record: identity + status for the label, the
58/// resolved world geometry, and (for the dimensional kinds) the annotation the
59/// shared leader renderer draws + the drag machinery grabs.
60#[derive(Clone, Debug)]
61pub struct ConstraintOverlay {
62 /// The constraint id (`DIST3`, `ANGL2`, …) — the mutation-ABI key.
63 pub id: String,
64 /// The constraint `type` string (`distance`, `coincident`, …).
65 pub constraint_type: String,
66 /// The type's icon glyph (`brep_kernel::ConstraintTypeDef::icon`) — what
67 /// the viewport chip shows in place of the id. Empty for an unknown type,
68 /// in which case the chip falls back to the id.
69 pub icon: String,
70 /// The solve status (`satisfied` / `adjusted` / `error` / …) — drives the
71 /// label color via [`status_color`].
72 pub status: String,
73 /// The human status/solve message (label tooltip).
74 pub message: String,
75 /// The overlay family.
76 pub kind: ConstraintOverlayKind,
77 /// The resolved WORLD anchor points (one per selection; empty when the
78 /// kernel could not resolve the selections — label-less, geometry-less row).
79 pub anchors: Vec<[f64; 3]>,
80 /// The element ROLE groups a multi-element type inferred (`groups` on the
81 /// overlay row): index groups into `anchors`, role order — center's
82 /// `[width pair, tab]`. Empty for the pairing types, whose two anchors ARE
83 /// the drawing.
84 pub groups: Vec<Vec<usize>>,
85 /// Distance/Angle: the dimension annotation (reusing the feature-dim shape so
86 /// `leaders_buffers` renders it verbatim). `field_key` is the `inputParams`
87 /// key the drag edits (`distance` / `angle`). `None` for `Leader` rows and
88 /// for dimensional rows whose anchors did not resolve.
89 pub annotation: Option<FeatureDimAnnotation>,
90 /// The measured value the kernel evaluated (`value` in the overlay row), for
91 /// the label suffix. `None` for non-dimensional rows.
92 pub value: Option<f64>,
93 /// The value's unit (`"mm"` / `"deg"`), empty when `value` is `None`.
94 pub unit: String,
95 /// Whether the dimensional handle may be DRAGGED: true only for
96 /// Distance/Angle whose current param is numeric (or absent — a first-solve
97 /// initialized target). A non-numeric expression string disables the drag.
98 pub draggable: bool,
99 /// The constraint's `inputParams` (from the state list) — the drag commit
100 /// mutates a clone of this (so `elements` / flags ride along unchanged).
101 pub input_params: Value,
102 /// The referenced element names (`inputParams.elements`) — label hover
103 /// highlights these through the existing emphasis machinery.
104 pub elements: Vec<String>,
105}
106
107impl ConstraintOverlay {
108 /// The `inputParams` key a drag on this overlay edits (`distance` / `angle`).
109 pub fn field_key(&self) -> Option<&'static str> {
110 match self.kind {
111 ConstraintOverlayKind::Distance => Some("distance"),
112 ConstraintOverlayKind::Angle => Some("angle"),
113 ConstraintOverlayKind::Leader => None,
114 }
115 }
116
117 /// The world-space label anchor: a dimensional annotation's chip anchor (the
118 /// leader midpoint, or the angle arc's mid-sweep at the screen-constant
119 /// radius — camera-dependent via `world_per_pixel`); a role-grouped row's
120 /// first-group centroid (center: the width span's midpoint, on the
121 /// mid-plane); a leader row's anchor midpoint (or its single anchor).
122 /// `None` when nothing resolved.
123 pub fn label_anchor(&self, world_per_pixel: f64) -> Option<[f64; 3]> {
124 if let Some(annotation) = &self.annotation {
125 return Some(match self.kind {
126 ConstraintOverlayKind::Angle => {
127 crate::feature_dimensions::angular_chip_anchor(annotation, world_per_pixel)
128 }
129 _ => annotation.midpoint(),
130 });
131 }
132 if let Some((span, _)) = self.role_leaders() {
133 return Some(co_mid(span.0, span.1));
134 }
135 match self.anchors.len() {
136 0 => None,
137 1 => Some(self.anchors[0]),
138 _ => {
139 let a = self.anchors[0];
140 let b = self.anchors[1];
141 Some([(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5, (a[2] + b[2]) * 0.5])
142 }
143 }
144 }
145
146 /// The role-drawn leaders of a grouped row (center): the WIDTH span
147 /// between the first group's two anchors, and the leader from that span's
148 /// midpoint to the second group's anchor centroid. `None` unless the row
149 /// carries two groups whose indexes all resolve to anchors (a pairing row,
150 /// or a stale `groups` against a shorter anchor list, draws the plain
151 /// leader instead).
152 fn role_leaders(&self) -> Option<(([f64; 3], [f64; 3]), ([f64; 3], [f64; 3]))> {
153 let [width, tab] = self.groups.as_slice() else {
154 return None;
155 };
156 let [w0, w1] = width.as_slice() else {
157 return None;
158 };
159 let (a, b) = (*self.anchors.get(*w0)?, *self.anchors.get(*w1)?);
160 if tab.is_empty() {
161 return None;
162 }
163 let mut centroid = [0.0f64; 3];
164 for &index in tab {
165 let p = self.anchors.get(index)?;
166 for k in 0..3 {
167 centroid[k] += p[k] / tab.len() as f64;
168 }
169 }
170 Some(((a, b), (co_mid(a, b), centroid)))
171 }
172
173 /// The label chip text: the type's icon, then `{value}{unit}` for
174 /// dimensional rows (`⟺ 5.25 mm`, `∠ 90°`); the bare icon otherwise. The
175 /// id no longer rides in the chip — the app's chip hover names it — so a
176 /// crowded assembly reads by picture, not by `DIST3`/`COIN9` codes. A row
177 /// whose type has no icon keeps the id in the icon's place.
178 pub fn label_text(&self) -> String {
179 let lead = if self.icon.is_empty() { self.id.as_str() } else { self.icon.as_str() };
180 match self.value {
181 Some(value) => {
182 let n = crate::formatting::compact_decimal(value, 2);
183 if self.unit == "deg" {
184 format!("{lead} {n}\u{00b0}")
185 } else if self.unit.is_empty() {
186 format!("{lead} {n}")
187 } else {
188 format!("{lead} {n} {}", self.unit)
189 }
190 }
191 None => lead.to_string(),
192 }
193 }
194}
195
196// ---------------------------------------------------------------------------
197// Status → color
198// ---------------------------------------------------------------------------
199
200/// The requirements-doc §5 status → color vocabulary as display-sRGB `[r,g,b]`
201/// (0..1, hex/255 like the leader palette — the overlay shader writes ~directly).
202///
203/// Overlay-shader color (0..1 floats) for a constraint status — a thin view
204/// over the ONE canonical map in [`crate::assembly_status`] (the panel's row
205/// labels and the tree rollup consume the same table; unified at Wave-3
206/// integration so the vocabulary can never drift).
207pub fn status_color(status: &str) -> [f32; 3] {
208 let [r, g, b] = crate::assembly_status::status_color_rgb(status);
209 [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0]
210}
211
212// ---------------------------------------------------------------------------
213// Builder
214// ---------------------------------------------------------------------------
215
216/// Build the overlay records from the kernel payloads: `overlay_rows` is the
217/// parsed `assembly_overlay_json` array; `state_constraints` is the parsed
218/// `assembly_state_json`'s `constraints` array (may be `Null` — the builder then
219/// has no `inputParams`, so dimensional rows fall back to draggable-with-empty
220/// params). Rows without resolved anchors yield status-only records (no
221/// geometry, no label anchor); a `fixed` constraint's single anchor yields a
222/// label anchor but no leader.
223pub fn build_constraint_overlays(
224 overlay_rows: &Value,
225 state_constraints: &Value,
226) -> Vec<ConstraintOverlay> {
227 let Some(rows) = overlay_rows.as_array() else {
228 return Vec::new();
229 };
230 rows.iter()
231 .filter_map(|row| build_row(row, state_constraints))
232 .collect()
233}
234
235fn build_row(row: &Value, state_constraints: &Value) -> Option<ConstraintOverlay> {
236 let id = row.get("id")?.as_str()?.to_string();
237 let constraint_type = row
238 .get("type")
239 .and_then(Value::as_str)
240 .unwrap_or("")
241 .to_string();
242 let icon = brep_kernel::constraint_type(&constraint_type)
243 .map(|def| def.icon.to_string())
244 .unwrap_or_default();
245 let status = row
246 .get("status")
247 .and_then(Value::as_str)
248 .unwrap_or("")
249 .to_string();
250 let message = row
251 .get("message")
252 .and_then(Value::as_str)
253 .unwrap_or("")
254 .to_string();
255 let anchors = read_points(row.get("anchors"));
256 let directions = read_dirs(row.get("directions"));
257 let geoms = read_strings(row.get("geoms"));
258 let groups = read_groups(row.get("groups"));
259 let value = row.get("value").and_then(Value::as_f64);
260 let unit = row
261 .get("unit")
262 .and_then(Value::as_str)
263 .unwrap_or("")
264 .to_string();
265
266 // The matching state entry's inputParams (expression check + elements).
267 let input_params = state_constraints
268 .as_array()
269 .and_then(|list| {
270 list.iter().find(|entry| {
271 entry
272 .get("inputParams")
273 .and_then(|p| p.get("id"))
274 .and_then(Value::as_str)
275 == Some(id.as_str())
276 })
277 })
278 .and_then(|entry| entry.get("inputParams"))
279 .cloned()
280 .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
281 let elements = crate::json_support::string_values(input_params.get("elements"))
282 .map(str::to_string)
283 .collect();
284
285 let kind = match constraint_type.as_str() {
286 "distance" => ConstraintOverlayKind::Distance,
287 "angle" => ConstraintOverlayKind::Angle,
288 _ => ConstraintOverlayKind::Leader,
289 };
290
291 // Dragging: only the dimensional kinds, and only while the param is NOT a
292 // non-numeric expression string (absent / number / plain numeric string are
293 // all draggable — matching the feature-dimension expression rule).
294 // A limit mate holds a range, not the single value the handle edits: its
295 // handle is not draggable.
296 let limited = input_params.get("limit").and_then(Value::as_bool).unwrap_or(false);
297 let draggable = match kind {
298 ConstraintOverlayKind::Leader => false,
299 ConstraintOverlayKind::Distance => !limited && param_allows_drag(&input_params, "distance"),
300 ConstraintOverlayKind::Angle => !limited && param_allows_drag(&input_params, "angle"),
301 };
302
303 let annotation = match kind {
304 ConstraintOverlayKind::Distance => {
305 build_distance_annotation(&anchors, &directions, &geoms, value)
306 }
307 ConstraintOverlayKind::Angle => build_angle_annotation(
308 &anchors,
309 &directions,
310 &geoms,
311 value,
312 row.get("angleAxis")
313 .cloned()
314 .and_then(|v| serde_json::from_value(v).ok()),
315 ),
316 ConstraintOverlayKind::Leader => None,
317 };
318
319 Some(ConstraintOverlay {
320 id,
321 constraint_type,
322 icon,
323 status,
324 message,
325 kind,
326 anchors,
327 groups,
328 annotation,
329 value: match kind {
330 ConstraintOverlayKind::Leader => None,
331 _ => value,
332 },
333 unit,
334 draggable,
335 input_params,
336 elements,
337 })
338}
339
340/// Whether `params[key]` permits a value drag: absent (first-solve initialized),
341/// a JSON number, or a PLAIN numeric string — but NOT a non-numeric expression
342/// string (`"a + b"`), which stays authoritative and disables the handle.
343fn param_allows_drag(params: &Value, key: &str) -> bool {
344 match params.get(key) {
345 None | Some(Value::Null) => true,
346 Some(Value::Number(_)) => true,
347 Some(Value::String(text)) => text.trim().parse::<f64>().is_ok(),
348 _ => false,
349 }
350}
351
352/// The distance constraint's LINEAR annotation.
353///
354/// PLANE-BASED pairings (at least one element is tagged `"plane"` in the row's
355/// `geoms` — the BASE face, element 0 preferred, matching the kernel mapper's
356/// base choice) draw the TRUE dimension: the other element's anchor `P` is
357/// projected onto the base plane along its outward normal `n̂` — the
358/// perpendicular foot `F = P − s·n̂` with `s = (P − Q)·n̂` the SIGNED offset —
359/// and the arrow runs `F → P`. That segment is normal to the base face by
360/// construction and its length `|s|` IS the constrained distance, so the arrow
361/// shows the kernel's signed `d = (P_other − P_base)·n̂_base` convention
362/// verbatim (a negative `s` points behind the face). The base normal rides in
363/// the annotation's (linear-unused) `axis` field so the drag can measure
364/// signed offsets along it — including through the face into negatives, and
365/// even when `s = 0` collapses the segment to a point.
366///
367/// Plane-less pairings (lines/points — no side to be on) keep the plain
368/// `anchors[0] → anchors[1]` leader with the unsigned measured value and a
369/// zero `axis`. `None` unless both anchors resolved.
370fn build_distance_annotation(
371 anchors: &[[f64; 3]],
372 directions: &[Option<[f64; 3]>],
373 geoms: &[String],
374 value: Option<f64>,
375) -> Option<FeatureDimAnnotation> {
376 if anchors.len() < 2 {
377 return None;
378 }
379 // The base plane: the first element tagged "plane" with a usable normal.
380 let base = (0..2).find(|&i| {
381 geoms.get(i).map(String::as_str) == Some("plane")
382 && directions
383 .get(i)
384 .copied()
385 .flatten()
386 .is_some_and(|n| co_norm(n) > 1e-9)
387 });
388 if let Some(base) = base {
389 let n = directions[base].expect("base index checked above");
390 let len = co_norm(n);
391 let n = [n[0] / len, n[1] / len, n[2] / len];
392 let q = anchors[base];
393 let p = anchors[1 - base];
394 let s = co_dot(co_sub(p, q), n);
395 let foot = [p[0] - n[0] * s, p[1] - n[1] * s, p[2] - n[2] * s];
396 // The kernel's measured `value` equals `s` for both plane arms (same
397 // formula over the same anchors); prefer it for label consistency.
398 let mut annotation =
399 FeatureDimAnnotation::linear("distance", foot, p, value.unwrap_or(s), "D");
400 annotation.axis = n;
401 return Some(annotation);
402 }
403 let a = anchors[0];
404 let b = anchors[1];
405 let value = value.unwrap_or_else(|| co_norm(co_sub(b, a)));
406 Some(FeatureDimAnnotation::linear("distance", a, b, value, "D"))
407}
408
409/// The angle arc uses the kernel's persistent world reference axis. Rebuilding
410/// an axis from `d0 × d1` would reverse it at negative/reflex targets, and lose
411/// it at 0/180 degrees. Legacy rows without an axis fall back to the cross.
412///
413/// The arc VERTEX is the angle's hinge — see [`angle_vertex`].
414fn build_angle_annotation(
415 anchors: &[[f64; 3]],
416 directions: &[Option<[f64; 3]>],
417 geoms: &[String],
418 value: Option<f64>,
419 reference_axis: Option<[f64; 3]>,
420) -> Option<FeatureDimAnnotation> {
421 if anchors.len() < 2 || directions.len() < 2 {
422 return None;
423 }
424 let d0 = directions[0]?;
425 let d1 = directions[1]?;
426 let axis = reference_axis.unwrap_or_else(|| co_cross(d0, d1));
427 let center = angle_vertex(anchors, d0, d1, geoms);
428 // Plane directions are normals. Turn the reference into the first
429 // face's section through the hinge so the arc arms lie in the measured
430 // planes, rather than sticking out perpendicular to them. Rotating both
431 // normals by the same quarter turn preserves the signed sweep and axis.
432 // Choose the half-line towards the first face; using only that fixed arm
433 // avoids reversing the reference as the second component turns.
434 let ref_dir = if geoms.get(0).map(String::as_str) == Some("plane")
435 && geoms.get(1).map(String::as_str) == Some("plane")
436 {
437 let tangent = co_cross(axis, d0);
438 if co_dot(tangent, co_sub(anchors[0], center)) < 0.0 {
439 co_scale(tangent, -1.0)
440 } else {
441 tangent
442 }
443 } else {
444 d0
445 };
446 let value = value.unwrap_or(0.0).clamp(-360.0, 360.0);
447 Some(FeatureDimAnnotation::angular(
448 "angle", center, axis, ref_dir, value, "A",
449 ))
450}
451
452/// `|n̂₀ × n̂₁|` below which two planes (or a line and a plane) count as
453/// parallel and have no hinge. The solver leaves a satisfied 0°/180° target
454/// with a residual around 1e-10, so the cutoff sits well above that: a target
455/// of exactly 180° must land on the fallback, not on a hinge 1e10 mm away.
456const PARALLEL_SIN: f64 = 1e-6;
457
458/// The arc vertex — the point the angle gizmo rotates about.
459///
460/// For two PLANAR faces the measured directions are the face NORMALS, and the
461/// angle between two planes is hinged on the intersection line of their
462/// INFINITE planes. The vertex is the point of that hinge nearest the midpoint
463/// of the two face anchors. That foot is invariant under any rotation about
464/// the hinge (a rotation about an axis preserves every point's component
465/// along it), so editing the angle of a hinge-pinned pair rotates the arc
466/// without moving it. That holds for every planar face because the kernel's
467/// face anchor is a FIXED point of its body (the boundary box centre in the
468/// face's own in-plane basis, `assembly_resolve::planar_face`), not a
469/// world-axis box that would slide over a triangle or an L as the body turns.
470///
471/// A plane paired with a direction carrier (edge, axis face, circle) is
472/// hinged where the carrier line pierces the plane. Two carriers meet at the
473/// closest-approach midpoint of their lines (the vertex of two edges). Rows
474/// without geometry tags (legacy sessions) take that carrier rule too.
475///
476/// Parallel elements have no hinge: the vertex falls back to the anchor
477/// midpoint, which lies on the mid-plane of two parallel faces. Approaching
478/// parallel, the true hinge recedes to infinity and the vertex follows it
479/// until [`PARALLEL_SIN`] switches to the fallback.
480fn angle_vertex(anchors: &[[f64; 3]], d0: [f64; 3], d1: [f64; 3], geoms: &[String]) -> [f64; 3] {
481 let is_plane = |i: usize| geoms.get(i).map(String::as_str) == Some("plane");
482 let (a0, a1) = (anchors[0], anchors[1]);
483 match (is_plane(0), is_plane(1)) {
484 (true, true) => plane_hinge_foot(a0, d0, a1, d1).unwrap_or_else(|| co_mid(a0, a1)),
485 (true, false) => {
486 line_plane_pierce(a1, d1, a0, d0).unwrap_or_else(|| co_mid(a0, a1))
487 }
488 (false, true) => {
489 line_plane_pierce(a0, d0, a1, d1).unwrap_or_else(|| co_mid(a0, a1))
490 }
491 (false, false) => carrier_closest_midpoint(a0, d0, a1, d1),
492 }
493}
494
495/// The point on the intersection line of the planes `(p0, n0)` and `(p1, n1)`
496/// nearest the midpoint `M` of `p0` and `p1` — the constrained least-squares
497/// solution `P = M + α·n̂₀ + β·n̂₁` with `[1 c; c 1]·[α β]ᵀ = [n̂₀·(p0−M), n̂₁·(p1−M)]ᵀ`,
498/// `c = n̂₀·n̂₁`. `None` when the planes are parallel ([`PARALLEL_SIN`]).
499fn plane_hinge_foot(
500 p0: [f64; 3],
501 n0: [f64; 3],
502 p1: [f64; 3],
503 n1: [f64; 3],
504) -> Option<[f64; 3]> {
505 let (l0, l1) = (co_norm(n0), co_norm(n1));
506 if l0 < 1e-9 || l1 < 1e-9 {
507 return None;
508 }
509 let n0 = co_scale(n0, 1.0 / l0);
510 let n1 = co_scale(n1, 1.0 / l1);
511 let c = co_dot(n0, n1);
512 let det = 1.0 - c * c; // = |n̂₀ × n̂₁|²
513 if det < PARALLEL_SIN * PARALLEL_SIN {
514 return None;
515 }
516 let m = co_mid(p0, p1);
517 let r0 = co_dot(n0, co_sub(p0, m));
518 let r1 = co_dot(n1, co_sub(p1, m));
519 let alpha = (r0 - c * r1) / det;
520 let beta = (r1 - c * r0) / det;
521 Some(co_add(m, co_add(co_scale(n0, alpha), co_scale(n1, beta))))
522}
523
524/// Where the carrier line `l + t·d` pierces the plane `(p, n)`; `None` when
525/// the line runs parallel to the plane ([`PARALLEL_SIN`] on the unit vectors).
526fn line_plane_pierce(l: [f64; 3], d: [f64; 3], p: [f64; 3], n: [f64; 3]) -> Option<[f64; 3]> {
527 let (ld, ln) = (co_norm(d), co_norm(n));
528 if ld < 1e-9 || ln < 1e-9 {
529 return None;
530 }
531 let d = co_scale(d, 1.0 / ld);
532 let n = co_scale(n, 1.0 / ln);
533 let denom = co_dot(d, n);
534 if denom.abs() < PARALLEL_SIN {
535 return None;
536 }
537 let t = co_dot(n, co_sub(p, l)) / denom;
538 Some(co_add(l, co_scale(d, t)))
539}
540
541/// The midpoint of the closest-approach segment between carrier lines
542/// `a + t·da` and `b + s·db`; the anchor midpoint when (near) parallel.
543fn carrier_closest_midpoint(a: [f64; 3], da: [f64; 3], b: [f64; 3], db: [f64; 3]) -> [f64; 3] {
544 let mid = |p: [f64; 3], q: [f64; 3]| {
545 [(p[0] + q[0]) * 0.5, (p[1] + q[1]) * 0.5, (p[2] + q[2]) * 0.5]
546 };
547 let da_n = co_norm(da);
548 let db_n = co_norm(db);
549 if da_n < 1e-9 || db_n < 1e-9 {
550 return mid(a, b);
551 }
552 let u = [da[0] / da_n, da[1] / da_n, da[2] / da_n];
553 let v = [db[0] / db_n, db[1] / db_n, db[2] / db_n];
554 let w0 = co_sub(a, b);
555 let b_uv = co_dot(u, v);
556 let denom = 1.0 - b_uv * b_uv;
557 if denom.abs() < 1e-9 {
558 return mid(a, b); // parallel carriers — no unique vertex
559 }
560 let d = co_dot(u, w0);
561 let e = co_dot(v, w0);
562 let t = (b_uv * e - d) / denom;
563 let s = (e - b_uv * d) / denom;
564 let p = [a[0] + u[0] * t, a[1] + u[1] * t, a[2] + u[2] * t];
565 let q = [b[0] + v[0] * s, b[1] + v[1] * s, b[2] + v[2] * s];
566 mid(p, q)
567}
568
569// ---------------------------------------------------------------------------
570// Buffers
571// ---------------------------------------------------------------------------
572
573/// Bake the whole overlay set into flat world-space triangle `(positions,
574/// colors)` buffers (the `tris` shape the overlay group consumes): the
575/// dimensional annotations through [`leaders_buffers`] (identical arrow/arc
576/// styling), the non-dimensional rows as plain silver leaders
577/// ([`append_plain_leader`]). Rows without geometry contribute nothing.
578pub fn constraint_overlay_buffers(
579 overlays: &[ConstraintOverlay],
580 world_per_pixel: f64,
581) -> (Vec<f32>, Vec<f32>) {
582 let annotations: Vec<FeatureDimAnnotation> = overlays
583 .iter()
584 .filter_map(|overlay| overlay.annotation.clone())
585 .collect();
586 let (mut positions, mut colors) = leaders_buffers(&annotations, world_per_pixel);
587 for overlay in overlays {
588 if overlay.kind != ConstraintOverlayKind::Leader {
589 continue;
590 }
591 if let Some((span, tab)) = overlay.role_leaders() {
592 // Role-drawn (center): the width span, then mid-plane → tab.
593 append_plain_leader(&mut positions, &mut colors, span.0, span.1, world_per_pixel);
594 append_plain_leader(&mut positions, &mut colors, tab.0, tab.1, world_per_pixel);
595 } else if overlay.anchors.len() >= 2 {
596 append_plain_leader(
597 &mut positions,
598 &mut colors,
599 overlay.anchors[0],
600 overlay.anchors[1],
601 world_per_pixel,
602 );
603 }
604 }
605 (positions, colors)
606}
607
608// ---------------------------------------------------------------------------
609// JSON + vec helpers (self-contained; `co_` prefixed like the fd_ family)
610// ---------------------------------------------------------------------------
611
612fn read_points(value: Option<&Value>) -> Vec<[f64; 3]> {
613 value
614 .and_then(Value::as_array)
615 .map(|list| list.iter().filter_map(read_point3).collect())
616 .unwrap_or_default()
617}
618
619/// Directions align index-wise with anchors; a JSON `null` (a point-like
620/// selection has no direction) stays `None`.
621fn read_dirs(value: Option<&Value>) -> Vec<Option<[f64; 3]>> {
622 value
623 .and_then(Value::as_array)
624 .map(|list| list.iter().map(read_point3).collect())
625 .unwrap_or_default()
626}
627
628/// The row's per-element `geoms` tags (aligned index-wise with anchors);
629/// empty when absent — a distance row then has no identifiable base plane and
630/// falls back to the plain anchor-to-anchor leader.
631fn read_strings(value: Option<&Value>) -> Vec<String> {
632 value
633 .and_then(Value::as_array)
634 .map(|list| {
635 list.iter()
636 .map(|v| v.as_str().unwrap_or("").to_string())
637 .collect()
638 })
639 .unwrap_or_default()
640}
641
642/// The row's role `groups` (index groups into `anchors`); empty when absent.
643fn read_groups(value: Option<&Value>) -> Vec<Vec<usize>> {
644 value
645 .and_then(Value::as_array)
646 .map(|groups| {
647 groups
648 .iter()
649 .map(|group| {
650 group
651 .as_array()
652 .map(|list| {
653 list.iter()
654 .filter_map(Value::as_u64)
655 .map(|index| index as usize)
656 .collect()
657 })
658 .unwrap_or_default()
659 })
660 .collect()
661 })
662 .unwrap_or_default()
663}
664
665fn read_point3(value: &Value) -> Option<[f64; 3]> {
666 let list = value.as_array()?;
667 Some([
668 list.first()?.as_f64()?,
669 list.get(1)?.as_f64()?,
670 list.get(2)?.as_f64()?,
671 ])
672}
673
674fn co_mid(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
675 [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5, (a[2] + b[2]) * 0.5]
676}
677
678fn co_add(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
679 [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
680}
681
682fn co_scale(v: [f64; 3], k: f64) -> [f64; 3] {
683 [v[0] * k, v[1] * k, v[2] * k]
684}
685
686fn co_sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
687 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
688}
689
690fn co_dot(a: [f64; 3], b: [f64; 3]) -> f64 {
691 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
692}
693
694fn co_norm(v: [f64; 3]) -> f64 {
695 co_dot(v, v).sqrt()
696}
697
698fn co_cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
699 [
700 a[1] * b[2] - a[2] * b[1],
701 a[2] * b[0] - a[0] * b[2],
702 a[0] * b[1] - a[1] * b[0],
703 ]
704}
705