Skip to main content

brep_render/
feature_dimensions.rs

1//! Draggable linear and angular annotations for selected feature parameters.
2//!
3//! Builders place local-space leaders on the feature's geometry and apply the
4//! same intrinsic XYZ transform as the kernel, keeping annotations aligned with
5//! the rebuilt solid. Each annotation identifies the parameter it edits.
6
7use crate::geometry3d::{cross3, dot3, len3 as norm3, sub3};
8
9use serde_json::Value;
10
11use crate::engine_state::rotate_euler_xyz_f64;
12
13/// A dimension annotation's kind. FD-1 was all [`FeatureDimKind::Linear`]; FD-2
14/// adds [`FeatureDimKind::Angular`] (torus `arc`, revolve `angle`).
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum FeatureDimKind {
17    /// A linear distance from `point_a` → `point_b`.
18    Linear,
19    /// An angular sweep of `value` DEGREES about `axis`, measured in the plane
20    /// ⟂ `axis` from the zero reference `ref_dir`, centered at `center`. Ported
21    /// from the previous app's angle-annotation builder.
22    Angular,
23}
24
25/// One editable dimension annotation.
26///
27/// LINEAR: a leader from world `point_a` → `point_b` whose length is the
28/// (resolved) value of param `field_key`; dragging projects the pointer onto the
29/// `a → b` axis.
30///
31/// ANGULAR: a screen-constant-radius ARC swept `value` degrees about `axis`
32/// (unit), starting from `ref_dir` (unit, in the plane ⟂ `axis`), centered at
33/// `center`; dragging maps the pointer to a swept angle. The `point_a`/`point_b`
34/// / `midpoint()` linear surface is unused for an angular annotation (both are
35/// set to `center`); the app anchors an angular chip at the arc's mid-sweep,
36/// which is camera-dependent and computed engine-side.
37#[derive(Clone, Debug)]
38pub struct FeatureDimAnnotation {
39    /// The `inputParams` key this annotation edits (e.g. `sizeX`, `radius`, `arc`).
40    pub field_key: String,
41    /// LINEAR: the dimension's start point in WORLD space (the leader anchor /
42    /// drag base). ANGULAR: `center`.
43    pub point_a: [f64; 3],
44    /// LINEAR: the dimension's end point in WORLD space (the value-1 handle).
45    /// ANGULAR: `center`.
46    pub point_b: [f64; 3],
47    /// The current (resolved) numeric value of `field_key` (a length for LINEAR,
48    /// DEGREES for ANGULAR).
49    pub value: f64,
50    /// The short display prefix (`X`, `R`, `H`, `A`, `Arc`, …).
51    pub label: String,
52    /// The annotation kind.
53    pub kind: FeatureDimKind,
54    /// ANGULAR only: the arc center (the axis-plane vertex) in WORLD space.
55    /// `[0;3]` for a linear annotation.
56    pub center: [f64; 3],
57    /// ANGULAR: the rotation AXIS (unit) the arc sweeps about. LINEAR: `[0;3]`
58    /// for feature dims; the assembly DISTANCE overlays stash the BASE-FACE
59    /// outward unit normal here (the signed drag axis — see
60    /// [`crate::constraint_overlays`]'s perpendicular-foot construction).
61    /// `leaders_buffers` ignores it for linear annotations either way.
62    pub axis: [f64; 3],
63    /// ANGULAR only: the sweep's ZERO reference (unit, in the plane ⟂ `axis`).
64    /// `[0;3]` for a linear annotation.
65    pub ref_dir: [f64; 3],
66}
67
68impl FeatureDimAnnotation {
69    /// `pub(crate)`: the assembly-constraint overlay builder
70    /// ([`crate::constraint_overlays`]) constructs the SAME annotation shape for
71    /// distance constraints so `leaders_buffers` renders constraint arrows with
72    /// byte-identical styling (UI-consistency directive — one arrow look).
73    pub(crate) fn linear(field_key: &str, a: [f64; 3], b: [f64; 3], value: f64, label: &str) -> Self {
74        Self {
75            field_key: field_key.to_string(),
76            point_a: a,
77            point_b: b,
78            value,
79            label: label.to_string(),
80            kind: FeatureDimKind::Linear,
81            center: [0.0; 3],
82            axis: [0.0; 3],
83            ref_dir: [0.0; 3],
84        }
85    }
86
87    /// An angular annotation: `value` DEGREES swept about `axis` from `ref_dir`,
88    /// centered at `center`. `axis` is normalized and `ref_dir` is projected into
89    /// the plane ⟂ `axis` then normalized (mirrors the overlay `#createAngle`
90    /// pre-processing). A degenerate axis/ref falls back to an arbitrary basis so
91    /// the annotation is always renderable.
92    ///
93    /// `pub(crate)`: also constructed by [`crate::constraint_overlays`] for angle
94    /// constraints so the constraint arc reuses this exact gizmo styling.
95    pub(crate) fn angular(
96        field_key: &str,
97        center: [f64; 3],
98        axis: [f64; 3],
99        ref_dir: [f64; 3],
100        value: f64,
101        label: &str,
102    ) -> Self {
103        let axis = normalize_or(axis, [0.0, 1.0, 0.0]);
104        // Project the reference into the plane ⟂ axis, then normalize.
105        let d = dot3(ref_dir, axis);
106        let planar = [
107            ref_dir[0] - axis[0] * d,
108            ref_dir[1] - axis[1] * d,
109            ref_dir[2] - axis[2] * d,
110        ];
111        let ref_dir = if norm3(planar) <= 1e-9 {
112            arbitrary_perpendicular(axis)
113        } else {
114            normalize_or(planar, arbitrary_perpendicular(axis))
115        };
116        Self {
117            field_key: field_key.to_string(),
118            point_a: center,
119            point_b: center,
120            value,
121            label: label.to_string(),
122            kind: FeatureDimKind::Angular,
123            center,
124            axis,
125            ref_dir,
126        }
127    }
128
129    /// The world-space midpoint of the leader — where the app anchors a LINEAR
130    /// label. (Angular chips anchor at the arc mid-sweep, computed engine-side
131    /// with the camera's `world_per_pixel`.)
132    pub fn midpoint(&self) -> [f64; 3] {
133        [
134            (self.point_a[0] + self.point_b[0]) * 0.5,
135            (self.point_a[1] + self.point_b[1]) * 0.5,
136            (self.point_a[2] + self.point_b[2]) * 0.5,
137        ]
138    }
139}
140
141/// Resolved scene geometry an annotation builder needs beyond the pure
142/// `inputParams` — the profile plane (extrude/revolve) and the axis line
143/// (revolve). These are NOT pure params (they resolve scene references), so the
144/// engine resolves them from the run report's sketch profiles / axes, or from
145/// the resident scene when the reference names a solid face / edge (see
146/// `EngineState::feature_dimension_refs`), and hands them in. All fields are
147/// optional: a builder that can't source what it needs returns `[]` gracefully.
148#[derive(Clone, Debug, Default)]
149pub struct ResolvedRefs {
150    /// Extrude/revolve: the profile CENTER (world centroid of the outer loop) —
151    /// the anchor the distance/angle gizmo hangs off, matching the previous app's
152    /// resolved profile-reference-geometry center.
153    pub profile_center: Option<[f64; 3]>,
154    /// Extrude/revolve: the profile plane NORMAL (unit) — the sketch `+z` basis,
155    /// or a face profile's OUTWARD normal (what the kernel's `face_profile` sets
156    /// as `z_axis`) — the authoritative sweep/revolve-orientation direction.
157    pub profile_normal: Option<[f64; 3]>,
158    /// Revolve: a point on the resolved axis LINE (world).
159    pub axis_point: Option<[f64; 3]>,
160    /// Revolve: the resolved axis line DIRECTION (unit, UNORIENTED — the builder
161    /// orients it toward the profile front via the `orient_revolve_axis` port).
162    pub axis_dir: Option<[f64; 3]>,
163    /// Plane (`P`): the resolved plane frame's ORIGIN (world) — the plane AFTER its
164    /// `offset_distance`. The offset dim's un-offset base is `origin − normal·offset`.
165    pub plane_origin: Option<[f64; 3]>,
166    /// Plane (`P`): the resolved plane frame's unit NORMAL (its z-axis) — the axis
167    /// the signed offset dim runs along.
168    pub plane_normal: Option<[f64; 3]>,
169    /// Plane (`P`) and Extrude (`E`): a small world length for a linear dim's
170    /// handle stub when its value is ~0 (a zero-length leader can't be dragged).
171    /// Screen-constant so the handle is a consistent size; ignored once the value
172    /// is non-zero.
173    pub plane_dim_length: Option<f64>,
174    /// Draft (`DRAFT`): the resolved unit PULL direction the feature drafted
175    /// for, from its result's `persistentData.draft.pull`.
176    pub draft_pull: Option<[f64; 3]>,
177    /// Draft (`DRAFT`): the resolved neutral (or parting) plane point, from
178    /// `persistentData.draft.neutral` — where the angle arcs and the pull arrow
179    /// stand.
180    pub draft_neutral: Option<[f64; 3]>,
181}
182
183/// Build the linear dimension annotations for a feature `type` from its
184/// `input_params`. Dispatches on the primitive-solid type; returns `[]` for any
185/// type without an FD-1 builder (extrude / revolve / booleans / etc.).
186///
187/// `input_params` should already have its numeric fields resolved to numbers
188/// (the engine resolves expression strings against the history env before
189/// calling this — see `EngineState::feature_dimension_annotations`), but plain
190/// numeric strings are tolerated here too so the pure geometry stays testable.
191pub fn build_annotations(feature_type: &str, input_params: &Value) -> Vec<FeatureDimAnnotation> {
192    build_annotations_with_refs(feature_type, input_params, &ResolvedRefs::default())
193}
194
195/// Build the dimension annotations for a feature, given any resolved scene
196/// references (`ResolvedRefs`) it needs. The primitive-solid + torus builders
197/// ignore `resolved` (pure params + the baked transform); extrude/revolve read
198/// the resolved profile plane / axis line and return `[]` when it is
199/// unavailable (an unresolved reference — see the builders). The engine resolves
200/// the profile plane from a sketch profile OR a resident solid face.
201pub fn build_annotations_with_refs(
202    feature_type: &str,
203    input_params: &Value,
204    resolved: &ResolvedRefs,
205) -> Vec<FeatureDimAnnotation> {
206    let transform = input_params.get("transform");
207    match feature_type {
208        "P.CU" => build_cube(input_params, transform),
209        "P.CY" => build_cylinder(input_params, transform),
210        "P.CO" => build_cone(input_params, transform),
211        // The sphere feature type is `P.S` (the dispatch keys on `P.S`).
212        "P.S" | "P.SP" => build_sphere(input_params, transform),
213        "P.PY" => build_pyramid(input_params, transform),
214        "P.T" => build_torus(input_params, transform),
215        "E" => build_extrude(input_params, resolved),
216        "R" => build_revolve(input_params, resolved),
217        "P" => build_plane(input_params, resolved),
218        "DRAFT" => build_draft(input_params, resolved),
219        _ => Vec::new(),
220    }
221}
222
223/// Cube (`P.CU`): minimum corner at the local origin, extending `+sizeX/Y/Z`
224/// (matches the kernel's `make_box_brep((0,0,0), …)`). Three linear dims from the
225/// origin corner along each axis.
226fn build_cube(params: &Value, transform: Option<&Value>) -> Vec<FeatureDimAnnotation> {
227    let sx = resolve_number(params, "sizeX");
228    let sy = resolve_number(params, "sizeY");
229    let sz = resolve_number(params, "sizeZ");
230    let p0 = transform_point(transform, [0.0, 0.0, 0.0]);
231    let px = transform_point(transform, [sx, 0.0, 0.0]);
232    let py = transform_point(transform, [0.0, sy, 0.0]);
233    let pz = transform_point(transform, [0.0, 0.0, sz]);
234    vec![
235        FeatureDimAnnotation::linear("sizeX", p0, px, sx, "X"),
236        FeatureDimAnnotation::linear("sizeY", p0, py, sy, "Y"),
237        FeatureDimAnnotation::linear("sizeZ", p0, pz, sz, "Z"),
238    ]
239}
240
241/// Cylinder (`P.CY`): axis is local `+Y`, base at `y=0`, top at `y=height`;
242/// radius along local `+X`. Two dims: radius (base → radial) + height (base → top).
243fn build_cylinder(params: &Value, transform: Option<&Value>) -> Vec<FeatureDimAnnotation> {
244    let radius = resolve_number(params, "radius");
245    let height = resolve_number(params, "height");
246    let base = transform_point(transform, [0.0, 0.0, 0.0]);
247    let top = transform_point(transform, [0.0, height, 0.0]);
248    let radial = transform_point(transform, [radius, 0.0, 0.0]);
249    vec![
250        FeatureDimAnnotation::linear("radius", base, radial, radius, "R"),
251        FeatureDimAnnotation::linear("height", base, top, height, "H"),
252    ]
253}
254
255/// Cone (`P.CO`): base radius at `y=0`, top radius at `y=height` (both along
256/// local `+X`), axis along `+Y`. Three dims: radiusBottom / radiusTop / height.
257fn build_cone(params: &Value, transform: Option<&Value>) -> Vec<FeatureDimAnnotation> {
258    let radius_top = resolve_number(params, "radiusTop");
259    let radius_bottom = resolve_number(params, "radiusBottom");
260    let height = resolve_number(params, "height");
261    let base_center = transform_point(transform, [0.0, 0.0, 0.0]);
262    let top_center = transform_point(transform, [0.0, height, 0.0]);
263    let base_radius = transform_point(transform, [radius_bottom, 0.0, 0.0]);
264    let top_radius = transform_point(transform, [radius_top, height, 0.0]);
265    vec![
266        FeatureDimAnnotation::linear("radiusBottom", base_center, base_radius, radius_bottom, "Rb"),
267        FeatureDimAnnotation::linear("radiusTop", top_center, top_radius, radius_top, "Rt"),
268        FeatureDimAnnotation::linear("height", base_center, top_center, height, "H"),
269    ]
270}
271
272/// Sphere (`P.S`): one radial dim from the center along local `+X`.
273fn build_sphere(params: &Value, transform: Option<&Value>) -> Vec<FeatureDimAnnotation> {
274    let radius = resolve_number(params, "radius");
275    let center = transform_point(transform, [0.0, 0.0, 0.0]);
276    let radial = transform_point(transform, [radius, 0.0, 0.0]);
277    vec![FeatureDimAnnotation::linear("radius", center, radial, radius, "R")]
278}
279
280/// Pyramid (`P.PY`): centered on its axis — base at `y = -h/2`, apex at `y = h/2`,
281/// base edge spanning `±side/2` in local X (at `z = -side/2`). Two dims: the base
282/// side edge + the axial height.
283fn build_pyramid(params: &Value, transform: Option<&Value>) -> Vec<FeatureDimAnnotation> {
284    let side = resolve_number(params, "baseSideLength");
285    let height = resolve_number(params, "height");
286    let half_side = side * 0.5;
287    let base_y = -height * 0.5;
288    let apex_y = height * 0.5;
289    let base_start = transform_point(transform, [-half_side, base_y, -half_side]);
290    let base_end = transform_point(transform, [half_side, base_y, -half_side]);
291    let base_center = transform_point(transform, [0.0, base_y, 0.0]);
292    let apex = transform_point(transform, [0.0, apex_y, 0.0]);
293    vec![
294        FeatureDimAnnotation::linear("baseSideLength", base_start, base_end, side, "Side"),
295        FeatureDimAnnotation::linear("height", base_center, apex, height, "H"),
296    ]
297}
298
299/// Torus (`P.T`): centered on its axis (local `+Y`) at the origin; the tube
300/// circle lies in the local X/Y plane centered at `(majorRadius, 0, 0)`, revolved
301/// `arc` DEGREES about `+Y`. Two LINEAR dims — `majorRadius` (center → the tube
302/// centerline along `+X`, `R`) and `tubeRadius` (the centerline → the outer wall,
303/// `r`) — plus the `arc` sweep as an ANGULAR dim about the local `+Y` axis from
304/// the `+X` reference. Ported verbatim from the previous torus-annotation builder.
305fn build_torus(params: &Value, transform: Option<&Value>) -> Vec<FeatureDimAnnotation> {
306    let major = resolve_number(params, "majorRadius");
307    let tube = resolve_number(params, "tubeRadius");
308    let arc = clamp_deg(resolve_number(params, "arc"));
309
310    let center = transform_point(transform, [0.0, 0.0, 0.0]);
311    let major_point = transform_point(transform, [major, 0.0, 0.0]);
312    let tube_point = transform_point(transform, [major + tube, 0.0, 0.0]);
313    // The axis / reference are the transformed local +Y / +X (subtract the
314    // transformed origin then normalize, so translation cancels; a non-uniform
315    // scale skews them — normalization handles magnitude).
316    let axis = normalize_or(sub3(transform_point(transform, [0.0, 1.0, 0.0]), center), [0.0, 1.0, 0.0]);
317    let start_dir = sub3(major_point, center);
318
319    vec![
320        FeatureDimAnnotation::linear("majorRadius", center, major_point, major, "R"),
321        FeatureDimAnnotation::linear("tubeRadius", major_point, tube_point, tube, "r"),
322        FeatureDimAnnotation::angular("arc", center, axis, start_dir, arc, "Arc"),
323    ]
324}
325
326/// Extrude (`E`): a LINEAR distance dim from the profile CENTER along the profile
327/// plane NORMAL by `distance` (`D`), plus the two-sided `distanceBack` leg along
328/// `-normal` (`Db`). Needs the resolved profile center + normal (a sketch
329/// profile's, or a resident solid face's — the engine sources both). Ported from
330/// the previous extrude-annotation builder.
331fn build_extrude(params: &Value, resolved: &ResolvedRefs) -> Vec<FeatureDimAnnotation> {
332    let (Some(center), Some(normal)) = (resolved.profile_center, resolved.profile_normal) else {
333        return Vec::new();
334    };
335    let normal = normalize_or(normal, [0.0, 0.0, 1.0]);
336    let distance = resolve_number(params, "distance");
337    let back = resolve_number(params, "distanceBack");
338    // A leg at ~0 (a one-sided extrude's other side) would collapse to a
339    // zero-length leader, which the drag ignores: its arrow could not be pulled
340    // out. Give it the Plane dim's screen-constant stub along its own direction
341    // instead; the value (and its label) stays 0 and the drag maps 1:1 there.
342    let leg = |value: f64| if value.abs() > 1e-6 { value } else { resolved.plane_dim_length.unwrap_or(0.0) };
343    let (forward_len, back_len) = (leg(distance), leg(back));
344    let forward = [
345        center[0] + normal[0] * forward_len,
346        center[1] + normal[1] * forward_len,
347        center[2] + normal[2] * forward_len,
348    ];
349    let backward = [
350        center[0] - normal[0] * back_len,
351        center[1] - normal[1] * back_len,
352        center[2] - normal[2] * back_len,
353    ];
354    vec![
355        FeatureDimAnnotation::linear("distance", center, forward, distance, "D"),
356        FeatureDimAnnotation::linear("distanceBack", center, backward, back, "Db"),
357    ]
358}
359
360/// Plane (`P`): one SIGNED LINEAR offset dim along the plane normal, driving
361/// `offset_distance`. The plane sits on either side of its base orientation/
362/// reference plane, so the dim runs from the un-offset base
363/// (`origin − normal·offset`) to the current plane (`origin`) and is dragged
364/// through zero to flip sign (the drag preserves sign; the kernel accepts a
365/// negative `offset_distance`). At offset ≈ 0 the leader collapses, so a small
366/// `+normal` stub (`plane_dim_length`, screen-constant) keeps it draggable — the
367/// value mapping stays 1:1 there. No resolved plane frame → `[]`.
368fn build_plane(params: &Value, resolved: &ResolvedRefs) -> Vec<FeatureDimAnnotation> {
369    let (Some(origin), Some(normal)) = (resolved.plane_origin, resolved.plane_normal) else {
370        return Vec::new();
371    };
372    let offset = resolve_number(params, "offset_distance");
373    // The un-offset base plane point — the dim's zero anchor.
374    let base = [
375        origin[0] - normal[0] * offset,
376        origin[1] - normal[1] * offset,
377        origin[2] - normal[2] * offset,
378    ];
379    // Handle at the current offset; at ~0 use a small +normal stub so the leader
380    // has a direction (the drag no-ops on a zero-length axis).
381    let extent = if offset.abs() > 1e-6 {
382        offset
383    } else {
384        resolved.plane_dim_length.unwrap_or(1.0)
385    };
386    let handle = [
387        base[0] + normal[0] * extent,
388        base[1] + normal[1] * extent,
389        base[2] + normal[2] * extent,
390    ];
391    vec![FeatureDimAnnotation::linear(
392        "offset_distance",
393        base,
394        handle,
395        offset,
396        "Offset",
397    )]
398}
399
400/// Draft (`DRAFT`): the ANGLE as an arc swept from the pull about a line square
401/// to it, at the neutral plane point: the arc's zero line runs along the pull
402/// and its end leans by the draft angle, which is how a drafted wall leans. A
403/// parting line drafted with its own angle on each side gets a second arc,
404/// `angle2`, swept from the reversed pull. Needs the resolved pull and neutral
405/// point (the feature's last successful run); `[]` otherwise.
406fn build_draft(params: &Value, resolved: &ResolvedRefs) -> Vec<FeatureDimAnnotation> {
407    let (Some(pull), Some(neutral)) = (resolved.draft_pull, resolved.draft_neutral) else {
408        return Vec::new();
409    };
410    let pull = normalize_or(pull, [0.0, 0.0, 1.0]);
411    let hinge = arbitrary_perpendicular(pull);
412    let mut out = vec![FeatureDimAnnotation::angular("angle", neutral, hinge, pull, resolve_number(params, "angle"), "A")];
413    let parted = params.get("type").and_then(Value::as_str) == Some("Parting line");
414    let same = params.get("sameBothSides").and_then(Value::as_bool).unwrap_or(true);
415    if parted && !same {
416        let against = [-pull[0], -pull[1], -pull[2]];
417        out.push(FeatureDimAnnotation::angular("angle2", neutral, hinge, against, resolve_number(params, "angle2"), "A2"));
418    }
419    out
420}
421
422/// The Draft's two GLYPHS, appended to the dimension overlay's triangle
423/// buffers: the PULL as an arrow from the neutral point along the pull (blue,
424/// not a handle: it has no value to drag), and the NEUTRAL PLANE as a square
425/// outline about the point, square to the pull. Screen-constant sizes.
426pub fn append_draft_glyph(
427    positions: &mut Vec<f32>,
428    colors: &mut Vec<f32>,
429    neutral: [f64; 3],
430    pull: [f64; 3],
431    world_per_pixel: f64,
432) {
433    let mut tb = TriBuf { positions: std::mem::take(positions), colors: std::mem::take(colors) };
434    let d = normalize_or(pull, [0.0, 0.0, 1.0]);
435    let at = |k: f64| [neutral[0] + d[0] * k, neutral[1] + d[1] * k, neutral[2] + d[2] * k];
436    let length = DRAFT_PULL_LEN_PX * world_per_pixel;
437    let cone = CONE_LEN_PX * world_per_pixel;
438    push_tube(&mut tb, neutral, at(length - cone), SHAFT_RAD_PX * world_per_pixel, PULL_RGB);
439    push_cone(&mut tb, at(length - cone), at(length), CONE_RAD_PX * world_per_pixel, PULL_RGB);
440    let (u, v) = axis_basis(d);
441    let half = DRAFT_PLANE_HALF_PX * world_per_pixel;
442    let corner = |a: f64, b: f64| {
443        [
444            neutral[0] + (u[0] * a + v[0] * b) * half,
445            neutral[1] + (u[1] * a + v[1] * b) * half,
446            neutral[2] + (u[2] * a + v[2] * b) * half,
447        ]
448    };
449    let corners = [corner(-1.0, -1.0), corner(1.0, -1.0), corner(1.0, 1.0), corner(-1.0, 1.0)];
450    for i in 0..4 {
451        push_tube(&mut tb, corners[i], corners[(i + 1) % 4], ANGLE_RAY_RAD_PX * world_per_pixel, PULL_RGB);
452    }
453    *positions = tb.positions;
454    *colors = tb.colors;
455}
456
457/// The Draft glyphs' colour (the reference blue of the feature icons) and
458/// screen sizes.
459const PULL_RGB: [f32; 3] = [0.239, 0.525, 0.769];
460const DRAFT_PULL_LEN_PX: f64 = 90.0;
461const DRAFT_PLANE_HALF_PX: f64 = 60.0;
462
463/// Revolve (`R`): one ANGULAR dim = `angle` DEGREES swept about the resolved axis
464/// line, oriented toward the profile front (the `orient_revolve_axis` port — so
465/// the arc rotates the SAME way the solid does), centered at the axis point
466/// nearest the profile, zeroed on the radial from that vertex to the profile.
467/// Needs the resolved axis line + profile; returns `[]` otherwise. Ported from
468/// the previous revolve-annotation builder.
469fn build_revolve(params: &Value, resolved: &ResolvedRefs) -> Vec<FeatureDimAnnotation> {
470    let (Some(axis_point), Some(axis_dir)) = (resolved.axis_point, resolved.axis_dir) else {
471        return Vec::new();
472    };
473    let Some(profile_center) = resolved.profile_center else {
474        return Vec::new();
475    };
476    let axis = orient_revolve_axis(axis_dir, axis_point, profile_center, resolved.profile_normal);
477    let vertex = closest_point_on_line(profile_center, axis_point, axis);
478    // The radial from the vertex to the profile (projected ⟂ axis) is the zero
479    // reference; the `angular` ctor re-projects + falls back if it degenerates.
480    let start_dir = sub3(profile_center, vertex);
481    let angle = clamp_deg(resolve_number(params, "angle"));
482    vec![FeatureDimAnnotation::angular("angle", vertex, axis, start_dir, angle, "A")]
483}
484
485/// The signed revolve axis native Revolve uses: the profile's outward normal
486/// selects between the two directions of an unoriented axis edge. Port of
487/// `resolveOrientedRevolveAxisDirection`.
488pub(crate) fn orient_revolve_axis(
489    axis_dir: [f64; 3],
490    axis_point: [f64; 3],
491    profile_center: [f64; 3],
492    profile_normal: Option<[f64; 3]>,
493) -> [f64; 3] {
494    let axis = normalize_or(axis_dir, [0.0, 1.0, 0.0]);
495    let Some(normal) = profile_normal else {
496        return axis;
497    };
498    if norm3(normal) <= 1e-12 {
499        return axis;
500    }
501    let normal = normalize_or(normal, [0.0, 0.0, 1.0]);
502    // radial = (profileCenter - axisPoint) projected ⟂ axis.
503    let mut radial = sub3(profile_center, axis_point);
504    let d = dot3(radial, axis);
505    radial = [radial[0] - axis[0] * d, radial[1] - axis[1] * d, radial[2] - axis[2] * d];
506    if norm3(radial) <= 1e-12 {
507        return axis;
508    }
509    let c = cross3(axis, radial);
510    if dot3(c, normal) < 0.0 {
511        [-axis[0], -axis[1], -axis[2]]
512    } else {
513        axis
514    }
515}
516
517/// The point on line `(line_point, line_dir)` closest to `point`.
518pub(crate) fn closest_point_on_line(
519    point: [f64; 3],
520    line_point: [f64; 3],
521    line_dir: [f64; 3],
522) -> [f64; 3] {
523    let dir = normalize_or(line_dir, [0.0, 1.0, 0.0]);
524    let t = dot3(sub3(point, line_point), dir);
525    [
526        line_point[0] + dir[0] * t,
527        line_point[1] + dir[1] * t,
528        line_point[2] + dir[2] * t,
529    ]
530}
531
532/// Clamp a degree value to `[-360, 360]`.
533fn clamp_deg(v: f64) -> f64 {
534    v.clamp(-360.0, 360.0)
535}
536
537/// Apply a feature's `inputParams.transform` (TRS, `rotationEuler` in DEGREES,
538/// `M = T·R·S`) to a LOCAL point → WORLD. Mirrors composing that degree-based TRS
539/// matrix and applying it to a point: `world = position + R·(scale ⊙ local)`, with `R` the exact
540/// intrinsic XYZ Euler order matrix the kernel bake uses (`rotate_euler_xyz_f64`).
541pub(crate) fn transform_point(transform: Option<&Value>, local: [f64; 3]) -> [f64; 3] {
542    let position = read_vec3(transform, "position", [0.0, 0.0, 0.0]);
543    let rotation_deg = read_vec3(transform, "rotationEuler", [0.0, 0.0, 0.0]);
544    let scale = read_vec3(transform, "scale", [1.0, 1.0, 1.0]);
545    let scaled = [local[0] * scale[0], local[1] * scale[1], local[2] * scale[2]];
546    let euler = [
547        rotation_deg[0].to_radians(),
548        rotation_deg[1].to_radians(),
549        rotation_deg[2].to_radians(),
550    ];
551    let rotated = rotate_euler_xyz_f64(scaled, euler);
552    [
553        rotated[0] + position[0],
554        rotated[1] + position[1],
555        rotated[2] + position[2],
556    ]
557}
558
559/// Read a `[x, y, z]` from a `transform` sub-field (numbers only; a missing /
560/// short array keeps the per-index default).
561fn read_vec3(transform: Option<&Value>, key: &str, default: [f64; 3]) -> [f64; 3] {
562    crate::json_support::vec3_or(transform.and_then(|t| t.get(key)), default)
563}
564
565/// Read `params[key]` as a finite number: a JSON number, else a plain numeric
566/// string (e.g. `"12.5"`). Non-numeric / expression strings resolve to `0.0`
567/// (the engine pre-resolves expressions before building, so this is only the
568/// pure-geometry fallback). Mirrors the numeric input-param resolution fallback.
569fn resolve_number(params: &Value, key: &str) -> f64 {
570    match params.get(key) {
571        Some(Value::Number(n)) => n.as_f64().filter(|v| v.is_finite()).unwrap_or(0.0),
572        Some(Value::String(s)) => s.trim().parse::<f64>().ok().filter(|v| v.is_finite()).unwrap_or(0.0),
573        _ => 0.0,
574    }
575}
576
577// --- restyled leader geometry (matches the reference dimension-arrows image) --
578//
579// Each annotation draws a thick SILVER rod (a 3D tube) from the shared origin
580// `point_a` out to `point_b`, an ORANGE cone arrowhead at `point_b`, and a
581// single ORANGE origin sphere at the shared start point (deduped across the
582// annotations that share it — a cube's three axis dims share one corner). The
583// geometry is radially symmetric so it needs no camera orientation; it is fed to
584// the `feature-dim-leaders` overlay group as flat triangle buffers. Colors are
585// display sRGB written ~directly by the overlay shader (with a per-face shade for
586// depth), so use hex/255 — no linear conversion.
587
588/// Silver-grey rod shaft color (~0xccced1) — also the angle ARC tube.
589const SHAFT_RGB: [f32; 3] = [0.80, 0.81, 0.82];
590/// Orange cone + origin/handle-sphere color (#F5A623).
591const ORANGE_RGB: [f32; 3] = [0.961, 0.651, 0.137];
592/// Red — the angle gizmo's ZERO-reference (drawn DASHED) radial line.
593const RED_RGB: [f32; 3] = [0.902, 0.157, 0.157];
594/// Green — the angle gizmo's rotation-AXIS line.
595const GREEN_RGB: [f32; 3] = [0.204, 0.808, 0.267];
596
597/// Silver-rod shaft radius, CSS pixels (thick, reads as a 3D rod).
598const SHAFT_RAD_PX: f64 = 2.2;
599/// Arrowhead cone length, CSS pixels.
600const CONE_LEN_PX: f64 = 16.0;
601/// Arrowhead cone base radius, CSS pixels (fuller 3D cone).
602const CONE_RAD_PX: f64 = 6.0;
603/// Origin sphere radius, CSS pixels (medium, screen-constant). Shared with
604/// `EngineState::dimension_origin_pick` so the click hit-radius matches the drawn
605/// sphere exactly.
606pub(crate) const ORIGIN_SPHERE_RAD_PX: f64 = 7.0;
607
608/// The angle gizmo's ARC radius, CSS pixels (screen-constant — matching the previous
609/// `FEATURE_ANGLE_RADIUS_PX`). Shared with the engine so the drawn arc, the chip
610/// anchor (mid-sweep) and the drag hit-search all use the SAME radius.
611pub const ANGLE_ARC_RAD_PX: f64 = 120.0;
612/// The angle gizmo's ref/axis line radius, CSS pixels (thinner than the arc).
613const ANGLE_RAY_RAD_PX: f64 = 1.6;
614/// Degrees of sweep per arc tube segment (tessellation of the arc).
615const ARC_DEG_PER_SEG: f64 = 4.0;
616/// The RED zero-reference line's dash / gap length, CSS pixels.
617const DASH_LEN_PX: f64 = 6.0;
618const DASH_GAP_PX: f64 = 5.0;
619
620const TUBE_SEGMENTS: usize = 8;
621const CONE_SEGMENTS: usize = 16;
622const SPHERE_RINGS: usize = 6;
623const SPHERE_SECTORS: usize = 10;
624
625/// Build the world-space leader geometry for a set of annotations as flat
626/// triangle `(positions, colors)` buffers (9 position + 9 color floats per
627/// triangle), ready to feed the `feature-dim-leaders` overlay group as `tris`.
628/// Normals are omitted — the overlay parser computes a flat face normal per
629/// triangle, and the shader's per-face shade gives the rods/cones/spheres their
630/// 3D read. `world_per_pixel` keeps the rod/cone/sphere screen-constant.
631pub fn leaders_buffers(
632    annotations: &[FeatureDimAnnotation],
633    world_per_pixel: f64,
634) -> (Vec<f32>, Vec<f32>) {
635    let mut tb = TriBuf::default();
636    let shaft_rad = SHAFT_RAD_PX * world_per_pixel;
637    let cone_len = CONE_LEN_PX * world_per_pixel;
638    let cone_rad = CONE_RAD_PX * world_per_pixel;
639    let sphere_rad = ORIGIN_SPHERE_RAD_PX * world_per_pixel;
640
641    // Draw the shared origin sphere once per distinct start point.
642    let mut origins: Vec<[f64; 3]> = Vec::new();
643    let mut add_origin = |tb: &mut TriBuf, a: [f64; 3]| {
644        if !origins.iter().any(|o| norm3(sub3(*o, a)) < 1e-6) {
645            push_sphere(tb, a, sphere_rad, ORANGE_RGB);
646            origins.push(a);
647        }
648    };
649
650    for ann in annotations {
651        match ann.kind {
652            FeatureDimKind::Angular => {
653                // The arc VERTEX gets the same orange origin sphere as a linear
654                // dim's `point_a`, so it is a visible mode-toggle target (the arc's
655                // sweep-END orange sphere is the angle DRAG handle, not a toggle).
656                // `add_origin` dedups against a linear origin at the same world
657                // point (a torus's `majorRadius` origin == this center), so no
658                // doubled geometry there.
659                add_origin(&mut tb, ann.center);
660                push_angle_gizmo(&mut tb, ann, world_per_pixel);
661            }
662            FeatureDimKind::Linear => {
663                let a = ann.point_a;
664                let b = ann.point_b;
665                let axis = sub3(b, a);
666                let len = norm3(axis);
667                add_origin(&mut tb, a);
668                if len < 1e-9 {
669                    continue;
670                }
671                let dir = [axis[0] / len, axis[1] / len, axis[2] / len];
672                // The cone occupies the far end; the rod runs from origin to it.
673                let cl = cone_len.min(len * 0.9);
674                let shaft_end = [b[0] - dir[0] * cl, b[1] - dir[1] * cl, b[2] - dir[2] * cl];
675                push_tube(&mut tb, a, shaft_end, shaft_rad, SHAFT_RGB);
676                push_cone(&mut tb, shaft_end, b, cone_rad, ORANGE_RGB);
677            }
678        }
679    }
680    (tb.positions, tb.colors)
681}
682
683/// Append a PLAIN leader line `a → b` (thin silver rod, NO arrowhead cone / origin
684/// sphere — nothing that reads as grabbable) onto existing `(positions, colors)`
685/// triangle buffers. The NON-dimensional assembly-constraint overlays (coincident /
686/// parallel / …) draw their anchor-to-anchor leaders through this so the line
687/// styling stays in this ONE home (same silver + screen-constant radius as the
688/// dimension rods, slightly thinner because it carries no handle).
689pub fn append_plain_leader(
690    positions: &mut Vec<f32>,
691    colors: &mut Vec<f32>,
692    a: [f64; 3],
693    b: [f64; 3],
694    world_per_pixel: f64,
695) {
696    let mut tb = TriBuf {
697        positions: std::mem::take(positions),
698        colors: std::mem::take(colors),
699    };
700    push_tube(&mut tb, a, b, ANGLE_RAY_RAD_PX * world_per_pixel, SHAFT_RGB);
701    *positions = tb.positions;
702    *colors = tb.colors;
703}
704
705/// The free-motion glyph at a selected assembly component (what its mates
706/// leave it): a double-headed arrow through `center` per free slide, and per
707/// free rotation a rod along the axis line (through its point nearest
708/// `center`) with a curled arrow turning about it. Screen-constant sizes,
709/// world-space triangles in the overlay `tris` shape.
710pub fn freedom_glyph_buffers(
711    center: [f64; 3],
712    slides: &[[f64; 3]],
713    axes: &[([f64; 3], [f64; 3])],
714    world_per_pixel: f64,
715) -> (Vec<f32>, Vec<f32>) {
716    let mut tb = TriBuf::default();
717    let rod = SHAFT_RAD_PX * world_per_pixel;
718    let cone_len = CONE_LEN_PX * world_per_pixel;
719    let cone_rad = CONE_RAD_PX * world_per_pixel;
720    let half = GLYPH_SLIDE_HALF_PX * world_per_pixel;
721    for slide in slides {
722        let d = normalize_or(*slide, [1.0, 0.0, 0.0]);
723        let tip = |k: f64| [center[0] + d[0] * k, center[1] + d[1] * k, center[2] + d[2] * k];
724        push_tube(&mut tb, tip(-(half - cone_len)), tip(half - cone_len), rod, SLIDE_RGB);
725        push_cone(&mut tb, tip(half - cone_len), tip(half), cone_rad, SLIDE_RGB);
726        push_cone(&mut tb, tip(-(half - cone_len)), tip(-half), cone_rad, SLIDE_RGB);
727    }
728    for (point, direction) in axes {
729        let d = normalize_or(*direction, [0.0, 0.0, 1.0]);
730        // The axis line where it passes the component.
731        let foot = closest_point_on_line(center, *point, d);
732        let along = |k: f64| [foot[0] + d[0] * k, foot[1] + d[1] * k, foot[2] + d[2] * k];
733        let reach = GLYPH_AXIS_HALF_PX * world_per_pixel;
734        push_tube(&mut tb, along(-reach), along(reach), ANGLE_RAY_RAD_PX * world_per_pixel, TURN_RGB);
735        // A 270° curl about the axis, ending in an arrowhead.
736        let (u, v) = axis_basis(d);
737        let radius = GLYPH_CURL_RAD_PX * world_per_pixel;
738        let at = |angle: f64| {
739            let (c, s) = (angle.cos() * radius, angle.sin() * radius);
740            [foot[0] + u[0] * c + v[0] * s, foot[1] + u[1] * c + v[1] * s, foot[2] + u[2] * c + v[2] * s]
741        };
742        let sweep = 1.5 * std::f64::consts::PI;
743        let steps = 18;
744        for i in 0..steps {
745            let a0 = sweep * i as f64 / steps as f64;
746            let a1 = sweep * (i + 1) as f64 / steps as f64;
747            push_tube(&mut tb, at(a0), at(a1), rod, TURN_RGB);
748        }
749        let end = at(sweep);
750        let tangent = normalize_or(sub3(at(sweep), at(sweep - 0.05)), u);
751        let head = [end[0] + tangent[0] * cone_len, end[1] + tangent[1] * cone_len, end[2] + tangent[2] * cone_len];
752        push_cone(&mut tb, end, head, cone_rad, TURN_RGB);
753    }
754    (tb.positions, tb.colors)
755}
756
757/// Free-motion glyph colors and sizes (screen px).
758const SLIDE_RGB: [f32; 3] = [0.255, 0.624, 0.949];
759const TURN_RGB: [f32; 3] = [0.804, 0.380, 0.886];
760const GLYPH_SLIDE_HALF_PX: f64 = 48.0;
761const GLYPH_AXIS_HALF_PX: f64 = 60.0;
762const GLYPH_CURL_RAD_PX: f64 = 20.0;
763
764/// A flat triangle-soup accumulator (positions + per-vertex rgb colors).
765#[derive(Default)]
766struct TriBuf {
767    positions: Vec<f32>,
768    colors: Vec<f32>,
769}
770
771impl TriBuf {
772    fn tri(&mut self, a: [f64; 3], b: [f64; 3], c: [f64; 3], rgb: [f32; 3]) {
773        for p in [a, b, c] {
774            self.positions
775                .extend_from_slice(&[p[0] as f32, p[1] as f32, p[2] as f32]);
776            self.colors.extend_from_slice(&rgb);
777        }
778    }
779}
780
781/// Push a solid 3D rod (open-ended tube) from `a` to `b` with world `radius`.
782fn push_tube(tb: &mut TriBuf, a: [f64; 3], b: [f64; 3], radius: f64, rgb: [f32; 3]) {
783    let axis = sub3(b, a);
784    let len = norm3(axis);
785    if len < 1e-9 || radius <= 0.0 {
786        return;
787    }
788    let dir = [axis[0] / len, axis[1] / len, axis[2] / len];
789    let (u, v) = axis_basis(dir);
790    let ring = |center: [f64; 3], k: usize| -> [f64; 3] {
791        let ang = (k as f64 / TUBE_SEGMENTS as f64) * std::f64::consts::TAU;
792        let (c, s) = (ang.cos() * radius, ang.sin() * radius);
793        [
794            center[0] + u[0] * c + v[0] * s,
795            center[1] + u[1] * c + v[1] * s,
796            center[2] + u[2] * c + v[2] * s,
797        ]
798    };
799    for k in 0..TUBE_SEGMENTS {
800        let a0 = ring(a, k);
801        let a1 = ring(a, k + 1);
802        let b0 = ring(b, k);
803        let b1 = ring(b, k + 1);
804        tb.tri(a0, b0, b1, rgb);
805        tb.tri(a0, b1, a1, rgb);
806    }
807}
808
809/// Push a filled arrowhead cone: apex at `tip`, base circle of world `radius`
810/// centered at `base` (side facets + a base cap).
811fn push_cone(tb: &mut TriBuf, base: [f64; 3], tip: [f64; 3], radius: f64, rgb: [f32; 3]) {
812    let axis = sub3(tip, base);
813    let len = norm3(axis);
814    if len < 1e-9 || radius <= 0.0 {
815        return;
816    }
817    let dir = [axis[0] / len, axis[1] / len, axis[2] / len];
818    let (u, v) = axis_basis(dir);
819    let ring = |k: usize| -> [f64; 3] {
820        let ang = (k as f64 / CONE_SEGMENTS as f64) * std::f64::consts::TAU;
821        let (c, s) = (ang.cos() * radius, ang.sin() * radius);
822        [
823            base[0] + u[0] * c + v[0] * s,
824            base[1] + u[1] * c + v[1] * s,
825            base[2] + u[2] * c + v[2] * s,
826        ]
827    };
828    let mut prev = ring(0);
829    for k in 1..=CONE_SEGMENTS {
830        let cur = ring(k);
831        tb.tri(tip, prev, cur, rgb); // side facet
832        tb.tri(base, cur, prev, rgb); // base cap
833        prev = cur;
834    }
835}
836
837/// Push a filled UV sphere of world `radius` at `center` (flat-shaded facets).
838fn push_sphere(tb: &mut TriBuf, center: [f64; 3], radius: f64, rgb: [f32; 3]) {
839    if radius <= 0.0 {
840        return;
841    }
842    let point = |ring: usize, sector: usize| -> [f64; 3] {
843        let lat = std::f64::consts::PI * (ring as f64 / SPHERE_RINGS as f64)
844            - std::f64::consts::FRAC_PI_2;
845        let lon = std::f64::consts::TAU * (sector as f64 / SPHERE_SECTORS as f64);
846        [
847            center[0] + lat.cos() * lon.cos() * radius,
848            center[1] + lat.cos() * lon.sin() * radius,
849            center[2] + lat.sin() * radius,
850        ]
851    };
852    for r in 0..SPHERE_RINGS {
853        for sct in 0..SPHERE_SECTORS {
854            let p00 = point(r, sct);
855            let p01 = point(r, sct + 1);
856            let p10 = point(r + 1, sct);
857            let p11 = point(r + 1, sct + 1);
858            tb.tri(p00, p10, p11, rgb);
859            tb.tri(p00, p11, p01, rgb);
860        }
861    }
862}
863
864/// Push the angle gizmo (image-9 target) for an ANGULAR annotation: a light-grey
865/// ARC of screen-constant radius swept from `ref_dir` by `value` degrees about
866/// `axis` at `center`, an ORANGE handle SPHERE at the sweep end with an ORANGE
867/// CONE just past it along the arc tangent, a RED DASHED zero-reference line along
868/// `ref_dir`, and a GREEN line along `axis`. Sizing is screen-constant via
869/// `world_per_pixel` so the gizmo stays a fixed pixel size across zoom.
870fn push_angle_gizmo(tb: &mut TriBuf, ann: &FeatureDimAnnotation, world_per_pixel: f64) {
871    let center = ann.center;
872    let axis = ann.axis;
873    let start = ann.ref_dir;
874    let radius = ANGLE_ARC_RAD_PX * world_per_pixel;
875    let ray_rad = ANGLE_RAY_RAD_PX * world_per_pixel;
876    let shaft_rad = SHAFT_RAD_PX * world_per_pixel;
877    let cone_len = CONE_LEN_PX * world_per_pixel;
878    let cone_rad = CONE_RAD_PX * world_per_pixel;
879    let sphere_rad = ORIGIN_SPHERE_RAD_PX * world_per_pixel;
880    if radius <= 1e-9 {
881        return;
882    }
883    // A full 360° arc would close on itself; clamp the DRAWN sweep just under it
884    // (matches the overlay's ±359.9 draw clamp) while the chip still shows the
885    // real value.
886    let value = ann.value.clamp(-359.9, 359.9);
887    let value_rad = value.to_radians();
888
889    // The arc: sample from 0 → value and connect consecutive points with grey
890    // tube segments. The point at parameter `t` (radians) is
891    // `center + rotate(start, axis, t) * radius`.
892    let arc_point = |t: f64| -> [f64; 3] {
893        let dir = rotate_about_axis(start, axis, t);
894        [
895            center[0] + dir[0] * radius,
896            center[1] + dir[1] * radius,
897            center[2] + dir[2] * radius,
898        ]
899    };
900    let seg_count = ((value.abs() / ARC_DEG_PER_SEG).ceil() as usize).max(2);
901    let mut prev = arc_point(0.0);
902    for k in 1..=seg_count {
903        let t = value_rad * (k as f64 / seg_count as f64);
904        let cur = arc_point(t);
905        push_tube(tb, prev, cur, shaft_rad, SHAFT_RGB);
906        prev = cur;
907    }
908
909    // The sweep END: the orange handle sphere sits on the arc, the cone points
910    // just past it along the arc tangent (the direction of increasing angle).
911    let dir_end = rotate_about_axis(start, axis, value_rad);
912    let end_pt = [
913        center[0] + dir_end[0] * radius,
914        center[1] + dir_end[1] * radius,
915        center[2] + dir_end[2] * radius,
916    ];
917    push_sphere(tb, end_pt, sphere_rad, ORANGE_RGB);
918    // Tangent = d/dt rotate = axis × dir_end, signed by the sweep direction.
919    let sweep_sign = if value < 0.0 { -1.0 } else { 1.0 };
920    let tangent = normalize_or(cross3(axis, dir_end), dir_end);
921    let tangent = [tangent[0] * sweep_sign, tangent[1] * sweep_sign, tangent[2] * sweep_sign];
922    let cone_tip = [
923        end_pt[0] + tangent[0] * cone_len,
924        end_pt[1] + tangent[1] * cone_len,
925        end_pt[2] + tangent[2] * cone_len,
926    ];
927    push_cone(tb, end_pt, cone_tip, cone_rad, ORANGE_RGB);
928
929    // RED DASHED zero-reference line from the center out along `ref_dir` to the
930    // arc-start radius (short tube dashes with gaps).
931    let ref_end = [
932        center[0] + start[0] * radius,
933        center[1] + start[1] * radius,
934        center[2] + start[2] * radius,
935    ];
936    push_dashed(tb, center, ref_end, ray_rad, RED_RGB, world_per_pixel);
937
938    // GREEN rotation-axis line through the center (a solid tube, both sides).
939    let axis_len = radius * 0.7;
940    let axis_a = [
941        center[0] - axis[0] * axis_len,
942        center[1] - axis[1] * axis_len,
943        center[2] - axis[2] * axis_len,
944    ];
945    let axis_b = [
946        center[0] + axis[0] * axis_len,
947        center[1] + axis[1] * axis_len,
948        center[2] + axis[2] * axis_len,
949    ];
950    push_tube(tb, axis_a, axis_b, ray_rad, GREEN_RGB);
951}
952
953/// Push a DASHED line `a → b` as a series of short solid tube segments (dash then
954/// gap, in screen-constant CSS px). Used for the angle gizmo's red zero-reference.
955fn push_dashed(
956    tb: &mut TriBuf,
957    a: [f64; 3],
958    b: [f64; 3],
959    radius: f64,
960    rgb: [f32; 3],
961    world_per_pixel: f64,
962) {
963    let axis = sub3(b, a);
964    let len = norm3(axis);
965    if len < 1e-9 {
966        return;
967    }
968    let dir = [axis[0] / len, axis[1] / len, axis[2] / len];
969    let dash = (DASH_LEN_PX * world_per_pixel).max(1e-6);
970    let gap = (DASH_GAP_PX * world_per_pixel).max(1e-6);
971    let mut s = 0.0;
972    while s < len {
973        let e = (s + dash).min(len);
974        let p0 = [a[0] + dir[0] * s, a[1] + dir[1] * s, a[2] + dir[2] * s];
975        let p1 = [a[0] + dir[0] * e, a[1] + dir[1] * e, a[2] + dir[2] * e];
976        push_tube(tb, p0, p1, radius, rgb);
977        s = e + gap;
978    }
979}
980
981/// The world-space chip anchor for an ANGULAR annotation: the arc mid-sweep point
982/// at the screen-constant radius (`center + rotate(ref_dir, axis, value/2) *
983/// radius`) — i.e. `labelAnchor = vertex + bisector * radius`. Camera-dependent
984/// (via `world_per_pixel`), so the engine computes it per frame.
985pub fn angular_chip_anchor(ann: &FeatureDimAnnotation, world_per_pixel: f64) -> [f64; 3] {
986    let radius = ANGLE_ARC_RAD_PX * world_per_pixel;
987    let value = ann.value.clamp(-359.9, 359.9);
988    let bisector = rotate_about_axis(ann.ref_dir, ann.axis, (value * 0.5).to_radians());
989    [
990        ann.center[0] + bisector[0] * radius,
991        ann.center[1] + bisector[1] * radius,
992        ann.center[2] + bisector[2] * radius,
993    ]
994}
995
996/// Screen-px hit radius for grabbing a dimension arrowHEAD — the cone base plus a
997/// little slack, so a click near the drawn arrowhead reliably grabs it. Shared by
998/// `EngineState::dimension_arrow_pick`.
999// Grab tolerance around a dimension arrowhead. Generous on purpose: egui only
1000// reports a DRAG once the pointer has already moved a few px past the press, so a
1001// tight radius makes the arrow feel un-grabbable. This gives a comfortable target.
1002pub(crate) const ARROW_HANDLE_HIT_RAD_PX: f64 = CONE_RAD_PX + 12.0;
1003
1004/// The world-space arrowHEAD handle point of an annotation — the drag grab target
1005/// (`EngineState::dimension_arrow_pick`). LINEAR: the orange cone tip at
1006/// `point_b`. ANGULAR: the orange sweep-END handle sphere on the arc (`center +
1007/// rotate(ref_dir, axis, value°) * radius`, value clamped to the drawn ±359.9° so
1008/// the grab point matches the drawn handle). Camera-dependent for angular (via
1009/// `world_per_pixel`), so it is computed per frame.
1010pub(crate) fn arrow_handle_point(
1011    ann: &FeatureDimAnnotation,
1012    world_per_pixel: f64,
1013) -> [f64; 3] {
1014    match ann.kind {
1015        FeatureDimKind::Linear => ann.point_b,
1016        FeatureDimKind::Angular => {
1017            let radius = ANGLE_ARC_RAD_PX * world_per_pixel;
1018            let value = ann.value.clamp(-359.9, 359.9);
1019            let dir = rotate_about_axis(ann.ref_dir, ann.axis, value.to_radians());
1020            [
1021                ann.center[0] + dir[0] * radius,
1022                ann.center[1] + dir[1] * radius,
1023                ann.center[2] + dir[2] * radius,
1024            ]
1025        }
1026    }
1027}
1028
1029/// Normalize `v`, or return `fallback` if `v` is ~zero-length.
1030fn normalize_or(v: [f64; 3], fallback: [f64; 3]) -> [f64; 3] {
1031    let n = norm3(v);
1032    if n < 1e-12 {
1033        fallback
1034    } else {
1035        [v[0] / n, v[1] / n, v[2] / n]
1036    }
1037}
1038
1039/// A stable unit vector ⟂ `direction` (a port of the previous app's arbitrary-perpendicular helper).
1040fn arbitrary_perpendicular(direction: [f64; 3]) -> [f64; 3] {
1041    if norm3(direction) <= 1e-12 {
1042        return [0.0, 0.0, 1.0];
1043    }
1044    let seed = if dot3(direction, [0.0, 0.0, 1.0]).abs() < 0.9 {
1045        [0.0, 0.0, 1.0]
1046    } else {
1047        [0.0, 1.0, 0.0]
1048    };
1049    let mut perp = cross3(direction, seed);
1050    if norm3(perp) <= 1e-12 {
1051        perp = cross3(direction, [1.0, 0.0, 0.0]);
1052    }
1053    if norm3(perp) <= 1e-12 {
1054        [1.0, 0.0, 0.0]
1055    } else {
1056        normalize_or(perp, [1.0, 0.0, 0.0])
1057    }
1058}
1059
1060/// Rotate `v` by `angle` radians about unit `axis` (Rodrigues). Shared with the
1061/// engine's angular drag/chip anchoring.
1062pub fn rotate_about_axis(v: [f64; 3], axis: [f64; 3], angle: f64) -> [f64; 3] {
1063    crate::geometry3d::rotate3(v, normalize_or(axis, [0.0, 1.0, 0.0]), angle)
1064}
1065
1066/// A radially-symmetric perpendicular basis `(u, v)` for a unit `dir`.
1067fn axis_basis(dir: [f64; 3]) -> ([f64; 3], [f64; 3]) {
1068    let seed = if dir[0].abs() < 0.9 {
1069        [1.0, 0.0, 0.0]
1070    } else {
1071        [0.0, 1.0, 0.0]
1072    };
1073    let mut u = cross3(dir, seed);
1074    let un = norm3(u);
1075    if un < 1e-9 {
1076        u = [0.0, 1.0, 0.0];
1077    } else {
1078        u = [u[0] / un, u[1] / un, u[2] / un];
1079    }
1080    let v = cross3(dir, u);
1081    let vn = norm3(v).max(1e-9);
1082    (u, [v[0] / vn, v[1] / vn, v[2] / vn])
1083}
1084