Skip to main content

brep_render/engine_state/
cage_edit.rs

1//! The CONTROL CAGE editor of a NURBS Solid (`NS`): the engine side.
2//!
3//! The kernel's [`ControlCage`] is the one model: the points the editor lists,
4//! draws and drags are read through `nurbs_solid::resolve_cage`, which is also
5//! what the kernel builds the body from, so a handle is never somewhere the
6//! surface is not controlled from. Every edit writes the whole cage back to
7//! `persistentData.cage` (materialising the primitive's cage on the first
8//! edit) and re-runs the history.
9//!
10//! SELECTION lives in the transform gizmo's arm ([`CageArm`]): the gizmo is
11//! armed exactly while at least one point is selected, at the selection's
12//! centroid. A drag re-derives every selected point from a snapshot taken at
13//! the grab — translate adds the pose's motion, rotate turns the snapshot
14//! about the grab centroid — so a long drag never accumulates error, and the
15//! frames of one drag coalesce into one undo step.
16//!
17//! LOOPS are inserted by knot insertion ([`ControlCage::insert_ring_between`],
18//! [`ControlCage::insert_column_between`]) beside the selected point, which
19//! refines the cage without moving the body; the new loop is selected
20//! afterwards so it can be dragged at once.
21
22use super::transform_gizmo::{rotate_euler_xyz_f64, TransformPose};
23use super::*;
24use brep_kernel::feature_pipeline::nurbs_solid;
25use brep_kernel::{CagePoint, ControlCage, Vec3};
26use serde_json::Value;
27
28/// The overlay group the cage draws into.
29const OVERLAY_GROUP: &str = "cage-edit";
30/// Cage line colour (0..1 rgb) and the dots: plain and selected.
31const CAGE_LINE: [f32; 3] = [0.30, 0.48, 0.80];
32const DOT_PLAIN: [f32; 3] = [0.70, 0.84, 1.0];
33const DOT_SELECTED: [f32; 3] = [0.435, 0.886, 0.435];
34const DOT_SIZE_PX: f32 = 9.0;
35/// A viewport click within this many CSS pixels of a dot picks it.
36pub const CAGE_PICK_RADIUS_PX: f64 = 10.0;
37
38/// The gizmo's cage subject: which points, and the grab snapshot of a drag.
39#[derive(Clone, Debug, Default)]
40pub struct CageArm {
41    /// Selected linear point indices, ascending, no repeats.
42    pub(super) selected: Vec<usize>,
43    /// The selected points at grab and the grab centroid, while a drag is in
44    /// flight. Every drag frame re-derives the points from these.
45    pub(super) grab: Option<(Vec<[f64; 3]>, [f64; 3])>,
46    /// The pose last written during the drag — what the widget tracks.
47    pub(super) live: Option<TransformPose>,
48}
49
50/// How a pick or a list action changes the selection.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum CageSelect {
53    /// The given points become the selection.
54    Replace,
55    /// Each given point joins the selection, or leaves it when already in.
56    Toggle,
57    /// The given points join the selection.
58    Add,
59}
60
61/// The cage as the editor's panel describes it.
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct CageSummary {
64    pub segments: usize,
65    pub rings: usize,
66    pub points: usize,
67    /// Whether the document carries an edited cage (the primitive params are
68    /// then only what it started from; Reset drops it).
69    pub persisted: bool,
70}
71
72fn array3(v: Vec3) -> [f64; 3] {
73    [v.x, v.y, v.z]
74}
75
76fn vec3(a: [f64; 3]) -> Vec3 {
77    Vec3::new(a[0], a[1], a[2])
78}
79
80fn centroid(points: &[[f64; 3]]) -> [f64; 3] {
81    if points.is_empty() {
82        return [0.0; 3];
83    }
84    let mut sum = [0.0; 3];
85    for p in points {
86        for k in 0..3 {
87            sum[k] += p[k];
88        }
89    }
90    let n = points.len() as f64;
91    [sum[0] / n, sum[1] / n, sum[2] / n]
92}
93
94impl EngineState {
95    // --- reads -----------------------------------------------------------------
96
97    /// Whether `feature_id` names a NURBS Solid.
98    pub fn is_cage_feature(&self, feature_id: &str) -> bool {
99        self.history
100            .index_of(feature_id)
101            .and_then(|index| self.history.feature_type(index))
102            .is_some_and(|ty| ty.eq_ignore_ascii_case("NS"))
103    }
104
105    /// The cage the kernel builds `feature_id` from (persisted or primitive),
106    /// or the reason it cannot be read.
107    pub fn cage_of(&self, feature_id: &str) -> Result<ControlCage, String> {
108        let index = self
109            .history
110            .index_of(feature_id)
111            .filter(|_| self.is_cage_feature(feature_id))
112            .ok_or_else(|| format!("'{feature_id}' is not a NURBS solid"))?;
113        let params = self.history.feature_params(index).unwrap_or(Value::Null);
114        let persistent = self.history.feature_persistent_data(index).unwrap_or(Value::Null);
115        let env = brep_kernel::Env::build(&self.history.expressions(), &self.history.configurator())
116            .map_err(|error| format!("expressions: {error}"))?;
117        nurbs_solid::resolve_cage(&env, &params, &persistent)
118    }
119
120    /// Every control point of the cage in linear order (empty for a
121    /// non-cage, or a cage the document cannot build).
122    pub fn cage_points(&self, feature_id: &str) -> Vec<[f64; 3]> {
123        self.cage_of(feature_id)
124            .map(|cage| cage.points().into_iter().map(array3).collect())
125            .unwrap_or_default()
126    }
127
128    /// The cage's shape for the panel, `None` for a non-cage.
129    pub fn cage_summary(&self, feature_id: &str) -> Option<CageSummary> {
130        let cage = self.cage_of(feature_id).ok()?;
131        let index = self.history.index_of(feature_id)?;
132        let persistent = self.history.feature_persistent_data(index).unwrap_or(Value::Null);
133        Some(CageSummary {
134            segments: cage.segments(),
135            rings: cage.ring_count(),
136            points: cage.point_count(),
137            persisted: nurbs_solid::has_persisted_cage(&persistent),
138        })
139    }
140
141    /// The NURBS solid whose cage editor is open, if any (the history panel
142    /// feeds it with the overlay).
143    pub fn cage_edit_feature(&self) -> Option<&str> {
144        self.cage_edit_feature.as_deref()
145    }
146
147    /// The selected point indices of the armed cage (empty unless the gizmo
148    /// is armed on a cage).
149    pub fn cage_selected(&self) -> Vec<usize> {
150        self.transform_gizmo
151            .cage
152            .as_ref()
153            .map(|cage| cage.selected.clone())
154            .unwrap_or_default()
155    }
156
157    /// Whether the gizmo is armed on the cage of `feature_id`.
158    pub fn cage_armed_for(&self, feature_id: &str) -> bool {
159        self.transform_gizmo.cage.is_some()
160            && self.transform_gizmo.feature_id.as_deref() == Some(feature_id)
161    }
162
163    // --- selection and the gizmo ---------------------------------------------------
164
165    /// Change the selection of `feature_id`'s cage and arm the gizmo at the
166    /// selection's centroid (disarmed when nothing is left selected).
167    /// Indices outside the cage are ignored.
168    pub fn cage_select(&mut self, feature_id: &str, indices: &[usize], mode: CageSelect) {
169        let count = self.cage_points(feature_id).len();
170        if count == 0 {
171            return;
172        }
173        let mut selected = if self.cage_armed_for(feature_id) {
174            self.cage_selected()
175        } else {
176            Vec::new()
177        };
178        match mode {
179            CageSelect::Replace => {
180                selected = indices.iter().copied().filter(|i| *i < count).collect();
181            }
182            CageSelect::Add => {
183                selected.extend(indices.iter().copied().filter(|i| *i < count));
184            }
185            CageSelect::Toggle => {
186                for &index in indices.iter().filter(|i| **i < count) {
187                    if let Some(at) = selected.iter().position(|s| *s == index) {
188                        selected.remove(at);
189                    } else {
190                        selected.push(index);
191                    }
192                }
193            }
194        }
195        selected.sort_unstable();
196        selected.dedup();
197        if selected.is_empty() {
198            if self.cage_armed_for(feature_id) {
199                self.disarm_transform();
200            }
201            return;
202        }
203        self.component_move_reset();
204        self.transform_gizmo.feature_id = Some(feature_id.to_string());
205        self.transform_gizmo.mode = GizmoMode::Transform;
206        self.transform_gizmo.drag = None;
207        self.transform_gizmo.anchor = None;
208        self.transform_gizmo.port = None;
209        self.transform_gizmo.deform = None;
210        self.transform_gizmo.cage = Some(CageArm {
211            selected,
212            grab: None,
213            live: None,
214        });
215        self.clear_feature_dimension_overlay();
216        self.sync_transform_gizmo();
217    }
218
219    /// Select every point of the cage.
220    pub fn cage_select_all(&mut self, feature_id: &str) {
221        let all: Vec<usize> = (0..self.cage_points(feature_id).len()).collect();
222        self.cage_select(feature_id, &all, CageSelect::Replace);
223    }
224
225    /// Clear the selection (and so disarm the gizmo).
226    pub fn cage_clear_selection(&mut self, feature_id: &str) {
227        self.cage_select(feature_id, &[], CageSelect::Replace);
228    }
229
230    /// Grow the selection to the whole ring of every selected ring point (a
231    /// selected pole stays as it is).
232    pub fn cage_select_rings_of_selection(&mut self, feature_id: &str) {
233        let Ok(cage) = self.cage_of(feature_id) else {
234            return;
235        };
236        let mut grown = Vec::new();
237        for index in self.cage_selected() {
238            if let Some(CagePoint::Ring { ring, .. }) = cage.locate(index) {
239                grown.extend((0..cage.segments()).map(|c| cage.index_of(ring, c)));
240            }
241        }
242        self.cage_select(feature_id, &grown, CageSelect::Add);
243    }
244
245    /// Grow the selection to the whole column (pole to pole, poles excluded)
246    /// of every selected ring point.
247    pub fn cage_select_columns_of_selection(&mut self, feature_id: &str) {
248        let Ok(cage) = self.cage_of(feature_id) else {
249            return;
250        };
251        let mut grown = Vec::new();
252        for index in self.cage_selected() {
253            if let Some(CagePoint::Ring { column, .. }) = cage.locate(index) {
254                grown.extend((0..cage.ring_count()).map(|r| cage.index_of(r, column)));
255            }
256        }
257        self.cage_select(feature_id, &grown, CageSelect::Add);
258    }
259
260    /// A viewport click while a cage editor is open: when one of the cage's
261    /// dots sits within [`CAGE_PICK_RADIUS_PX`] of CSS-pixel `(x, y)`, select
262    /// it — REPLACING the selection, or TOGGLING it in with `toggle` (a
263    /// modifier held) — and report its index. Dots are picked by projection,
264    /// so a point behind the body is as pickable as one in front, which is
265    /// what a cage wants. `None` leaves the click to the ordinary selection.
266    pub fn cage_point_pick_at(&mut self, x: f64, y: f64, toggle: bool) -> Option<usize> {
267        let feature_id = self.cage_edit_feature.clone()?;
268        let points = self.cage_points(&feature_id);
269        let mut best: Option<(usize, f64)> = None;
270        for (index, point) in points.iter().enumerate() {
271            if !self.camera.projectable(*point) {
272                continue;
273            }
274            let (sx, sy, _) = self.camera.project(*point);
275            let d = ((sx - x).powi(2) + (sy - y).powi(2)).sqrt();
276            if d <= CAGE_PICK_RADIUS_PX && best.is_none_or(|(_, bd)| d < bd) {
277                best = Some((index, d));
278            }
279        }
280        let (index, _) = best?;
281        let mode = if toggle { CageSelect::Toggle } else { CageSelect::Replace };
282        self.cage_select(&feature_id, &[index], mode);
283        Some(index)
284    }
285
286    /// Every cage dot projected to VIEWPORT-LOCAL px, `(index, (x, y))`, for
287    /// the host's hit blob. Empty unless a cage editor is open.
288    pub fn cage_point_screen_points(&self) -> Vec<(usize, (f64, f64))> {
289        let Some(feature_id) = self.cage_edit_feature.as_deref() else {
290            return Vec::new();
291        };
292        self.cage_points(feature_id)
293            .into_iter()
294            .enumerate()
295            .filter(|(_, point)| self.camera.projectable(*point))
296            .map(|(index, point)| {
297                let (sx, sy, _) = self.camera.project(point);
298                (index, (sx, sy))
299            })
300            .collect()
301    }
302
303    /// The armed cage's pose: the live drag pose while a drag is in flight,
304    /// else the selection's centroid with the world frame. `None` when the
305    /// selection is gone (the gizmo disarms).
306    pub(super) fn cage_pose(&self) -> Option<TransformPose> {
307        let arm = self.transform_gizmo.cage.as_ref()?;
308        if self.transform_gizmo.drag.is_some() {
309            if let Some(live) = arm.live {
310                return Some(live);
311            }
312        }
313        let feature_id = self.transform_gizmo.feature_id.as_deref()?;
314        let points = self.cage_points(feature_id);
315        let selected: Vec<[f64; 3]> = arm
316            .selected
317            .iter()
318            .filter_map(|i| points.get(*i).copied())
319            .collect();
320        if selected.is_empty() {
321            return None;
322        }
323        Some(TransformPose {
324            position: centroid(&selected),
325            rotation_deg: [0.0; 3],
326            scale: [1.0; 3],
327        })
328    }
329
330    /// Whether the armed cage's gizmo should draw its rotation rings: a lone
331    /// point has nothing to turn about.
332    pub(super) fn cage_shows_rings(&self) -> Option<bool> {
333        self.transform_gizmo
334            .cage
335            .as_ref()
336            .map(|arm| arm.selected.len() >= 2)
337    }
338
339    /// Snapshot the selection at the grab (called when a gizmo drag starts).
340    pub(super) fn cage_grab_begin(&mut self) {
341        let Some(feature_id) = self.transform_gizmo.feature_id.clone() else {
342            return;
343        };
344        if self.transform_gizmo.cage.is_none() {
345            return;
346        }
347        let points = self.cage_points(&feature_id);
348        if let Some(arm) = self.transform_gizmo.cage.as_mut() {
349            let snapshot: Vec<[f64; 3]> = arm
350                .selected
351                .iter()
352                .filter_map(|i| points.get(*i).copied())
353                .collect();
354            let center = centroid(&snapshot);
355            arm.grab = Some((snapshot, center));
356            arm.live = None;
357        }
358    }
359
360    /// Forget the grab snapshot (called when the drag ends).
361    pub(super) fn cage_grab_end(&mut self) {
362        if let Some(arm) = self.transform_gizmo.cage.as_mut() {
363            arm.grab = None;
364            arm.live = None;
365        }
366    }
367
368    /// The gizmo's write-back for a cage: `pose` is the grab pose moved by the
369    /// drag so far (position = grab centroid + translation; rotation = the
370    /// drag's turn, from identity). Every selected point is re-derived from
371    /// the grab snapshot: turned about the grab centroid, then moved.
372    pub(super) fn write_cage_pose(&mut self, pose: &TransformPose) {
373        let Some(feature_id) = self.transform_gizmo.feature_id.clone() else {
374            return;
375        };
376        let Some(arm) = self.transform_gizmo.cage.as_ref() else {
377            return;
378        };
379        let Some((snapshot, center)) = arm.grab.clone() else {
380            return;
381        };
382        let selected = arm.selected.clone();
383        let dragging = self.transform_dragging();
384        let euler = [
385            pose.rotation_deg[0].to_radians(),
386            pose.rotation_deg[1].to_radians(),
387            pose.rotation_deg[2].to_radians(),
388        ];
389        let shift = [
390            pose.position[0] - center[0],
391            pose.position[1] - center[1],
392            pose.position[2] - center[2],
393        ];
394        let Ok(mut cage) = self.cage_of(&feature_id) else {
395            return;
396        };
397        for (index, start) in selected.iter().zip(snapshot.iter()) {
398            let offset = [start[0] - center[0], start[1] - center[1], start[2] - center[2]];
399            let turned = rotate_euler_xyz_f64(offset, euler);
400            let moved: [f64; 3] = std::array::from_fn(|axis| {
401                let after = center[axis] + turned[axis] + shift[axis];
402                if dragging {
403                    crate::formatting::snap_drag_moved(start[axis], after)
404                } else {
405                    after
406                }
407            });
408            let moved = Vec3::new(moved[0], moved[1], moved[2]);
409            let _ = cage.set_point(*index, moved);
410        }
411        if let Some(arm) = self.transform_gizmo.cage.as_mut() {
412            arm.live = Some(*pose);
413        }
414        let key = format!("cage-drag:{feature_id}");
415        self.write_cage(&feature_id, &cage, Some(&key));
416    }
417
418    // --- edits -------------------------------------------------------------------------
419
420    /// Persist `cage` as the feature's edited cage (checkpointed; `coalesce`
421    /// folds a run of same-key writes into one undo step) and re-run.
422    fn write_cage(&mut self, feature_id: &str, cage: &ControlCage, coalesce: Option<&str>) {
423        let Some(index) = self.history.index_of(feature_id) else {
424            return;
425        };
426        self.history.set_feature_persistent_field_coalesced(
427            index,
428            nurbs_solid::PERSISTENT_KEY,
429            cage.to_json(),
430            coalesce,
431        );
432        self.rerun_history();
433    }
434
435    /// Move one point to `position` (a typed edit; coalesced per point).
436    pub fn cage_set_point_position(
437        &mut self,
438        feature_id: &str,
439        index: usize,
440        position: [f64; 3],
441    ) -> Result<(), String> {
442        let mut cage = self.cage_of(feature_id)?;
443        cage.set_point(index, vec3(position))?;
444        let key = format!("cage-point:{feature_id}:{index}");
445        self.write_cage(feature_id, &cage, Some(&key));
446        self.sync_transform_gizmo();
447        Ok(())
448    }
449
450    /// Insert a ring beside the selected point: `above` puts it between that
451    /// point's ring and the next towards the top pole, else towards the
452    /// bottom. With several points selected the first decides. The body is
453    /// unchanged; the new ring is selected. Returns its ring index.
454    pub fn cage_insert_ring(&mut self, feature_id: &str, above: bool) -> Result<usize, String> {
455        let mut cage = self.cage_of(feature_id)?;
456        let anchor = self
457            .cage_selected()
458            .first()
459            .copied()
460            .ok_or("select a point of the cage first: the ring goes beside it")?;
461        // Rows count the poles: the bottom pole is row 0, ring r is row r + 1.
462        let row = match cage.locate(anchor) {
463            Some(CagePoint::Pole(0)) => 0,
464            Some(CagePoint::Pole(_)) => cage.ring_count(),
465            Some(CagePoint::Ring { ring, .. }) => {
466                if above {
467                    ring + 1
468                } else {
469                    ring
470                }
471            }
472            None => return Err(format!("no cage point {anchor}")),
473        };
474        let new_ring = cage.insert_ring_between(row)?;
475        self.write_cage(feature_id, &cage, None);
476        let loop_points: Vec<usize> = (0..cage.segments()).map(|c| cage.index_of(new_ring, c)).collect();
477        self.cage_select(feature_id, &loop_points, CageSelect::Replace);
478        Ok(new_ring)
479    }
480
481    /// Insert a column (pole to pole) beside the selected point: `next` puts
482    /// it between that point's column and the next around the ring, else the
483    /// previous. A selected pole offers no column, so a ring point must be
484    /// selected. The body is unchanged; the new column is selected. Returns
485    /// its column index.
486    pub fn cage_insert_column(&mut self, feature_id: &str, next: bool) -> Result<usize, String> {
487        let mut cage = self.cage_of(feature_id)?;
488        let selected = self.cage_selected();
489        let column = selected
490            .iter()
491            .find_map(|index| match cage.locate(*index) {
492                Some(CagePoint::Ring { column, .. }) => Some(column),
493                _ => None,
494            })
495            .ok_or("select a ring point of the cage first: the column goes beside it")?;
496        let n = cage.segments();
497        let after = if next { column } else { (column + n - 1) % n };
498        let new_column = cage.insert_column_between(after)?;
499        self.write_cage(feature_id, &cage, None);
500        let loop_points: Vec<usize> = (0..cage.ring_count()).map(|r| cage.index_of(r, new_column)).collect();
501        self.cage_select(feature_id, &loop_points, CageSelect::Replace);
502        Ok(new_column)
503    }
504
505    /// Drop the edited cage: the body returns to the primitive the params
506    /// describe. Clears the selection.
507    pub fn cage_reset(&mut self, feature_id: &str) -> Result<(), String> {
508        let index = self
509            .history
510            .index_of(feature_id)
511            .filter(|_| self.is_cage_feature(feature_id))
512            .ok_or_else(|| format!("'{feature_id}' is not a NURBS solid"))?;
513        if self.cage_armed_for(feature_id) {
514            self.disarm_transform();
515        }
516        self.history
517            .set_feature_persistent_field(index, nurbs_solid::PERSISTENT_KEY, Value::Null);
518        self.rerun_history();
519        Ok(())
520    }
521
522    // --- the overlay ------------------------------------------------------------------
523
524    /// Feed the cage overlay for `feature_id` — its rings, its columns and a
525    /// dot per point, the selected ones highlighted — or clear it with
526    /// `None`. Cheap to call every frame: an unchanged feed is skipped.
527    pub fn refresh_cage_edit_overlay(&mut self, feature_id: Option<&str>) {
528        if self.cage_edit_feature.as_deref() != feature_id {
529            self.cage_edit_feature = feature_id.map(str::to_string);
530        }
531        let selected = feature_id
532            .filter(|id| self.cage_armed_for(id))
533            .map(|_| self.cage_selected())
534            .unwrap_or_default();
535        let key = feature_id.map(|id| (id.to_string(), selected.clone(), self.applied_generation));
536        if self.cage_overlay_key == key {
537            return;
538        }
539        self.cage_overlay_key = key;
540        let Some(feature_id) = feature_id else {
541            let _ = self
542                .widgets
543                .set_overlay_json(&serde_json::json!({ "groups": [{ "name": OVERLAY_GROUP }] }).to_string());
544            self.dirty = true;
545            return;
546        };
547        let Ok(cage) = self.cage_of(feature_id) else {
548            let _ = self
549                .widgets
550                .set_overlay_json(&serde_json::json!({ "groups": [{ "name": OVERLAY_GROUP }] }).to_string());
551            self.dirty = true;
552            return;
553        };
554        let mut line_positions: Vec<f64> = Vec::new();
555        let mut line_colors: Vec<f32> = Vec::new();
556        let mut push_line = |a: Vec3, b: Vec3| {
557            line_positions.extend_from_slice(&array3(a));
558            line_positions.extend_from_slice(&array3(b));
559            line_colors.extend_from_slice(&CAGE_LINE);
560            line_colors.extend_from_slice(&CAGE_LINE);
561        };
562        let n = cage.segments();
563        for ring in &cage.rings {
564            for c in 0..n {
565                push_line(ring[c], ring[(c + 1) % n]);
566            }
567        }
568        for c in 0..n {
569            let mut previous = cage.poles[0];
570            for ring in &cage.rings {
571                push_line(previous, ring[c]);
572                previous = ring[c];
573            }
574            push_line(previous, cage.poles[1]);
575        }
576        let mut dot_positions: Vec<f64> = Vec::new();
577        let mut dot_colors: Vec<f32> = Vec::new();
578        for (index, point) in cage.points().iter().enumerate() {
579            dot_positions.extend_from_slice(&array3(*point));
580            let color = if selected.binary_search(&index).is_ok() {
581                DOT_SELECTED
582            } else {
583                DOT_PLAIN
584            };
585            dot_colors.extend_from_slice(&color);
586        }
587        let group = serde_json::json!({
588            "name": OVERLAY_GROUP,
589            "renderOrder": 6,
590            "lines": { "positions": line_positions, "colors": line_colors },
591            "points": { "positions": dot_positions, "colors": dot_colors, "size": DOT_SIZE_PX },
592        });
593        let _ = self
594            .widgets
595            .set_overlay_json(&serde_json::json!({ "groups": [group] }).to_string());
596        self.dirty = true;
597    }
598}
599