Skip to main content

brep_render/engine_state/
deform_edit.rs

1//! The PICK HANDLES of a Deform Face (`DFF`): the engine side.
2//!
3//! The kernel reports every pick it resolved in the feature's
4//! `persistentData.deform.resolved` (the anchor on the face, the outward
5//! normal, the offset, and the point the pick was moved to). While the
6//! feature's form is open each target is drawn as a dot, with a line back to
7//! its anchor. A click on a dot arms the transform gizmo there; a drag moves
8//! the pick ALONG ITS NORMAL: the new offset is the offset at the grab plus the
9//! drag's motion projected on the normal (motion across the normal is
10//! ignored, so any gizmo axis can be used). The offset is written back where
11//! the pick takes it from — the pick's own `offset` in
12//! `persistentData.deform.picks` when it has one, else the form's `offset` —
13//! and the frames of one drag coalesce into one undo step.
14
15use super::transform_gizmo::TransformPose;
16use super::*;
17use serde_json::Value;
18
19/// The overlay group the handles draw into.
20const OVERLAY_GROUP: &str = "deform-edit";
21const LINE_COLOR: [f32; 3] = [0.24, 0.53, 0.77];
22const DOT_PLAIN: [f32; 3] = [0.66, 0.83, 0.97];
23const DOT_SELECTED: [f32; 3] = [0.435, 0.886, 0.435];
24const DOT_SIZE_PX: f32 = 10.0;
25/// A viewport click within this many CSS pixels of a dot picks it.
26pub const DEFORM_PICK_RADIUS_PX: f64 = 10.0;
27
28/// The gizmo's Deform Face subject: which pick, and the grab snapshot.
29#[derive(Clone, Debug, Default)]
30pub struct DeformArm {
31    pub(super) pick: usize,
32    /// At the grab: the pick's offset, its target and its unit normal.
33    pub(super) grab: Option<(f64, [f64; 3], [f64; 3])>,
34    /// The pose last written during the drag.
35    pub(super) live: Option<TransformPose>,
36}
37
38/// One resolved pick, as the kernel reported it.
39#[derive(Clone, Debug, PartialEq)]
40pub struct DeformPickRow {
41    pub anchor: [f64; 3],
42    pub normal: [f64; 3],
43    pub offset: f64,
44    pub target: [f64; 3],
45}
46
47fn read3(value: &Value) -> Option<[f64; 3]> {
48    let array = value.as_array()?;
49    let c: Vec<f64> = array.iter().filter_map(Value::as_f64).collect();
50    (c.len() == 3).then(|| [c[0], c[1], c[2]])
51}
52
53impl EngineState {
54    /// Whether `feature_id` is a Deform Face.
55    pub fn is_deform_feature(&self, feature_id: &str) -> bool {
56        self.history
57            .index_of(feature_id)
58            .and_then(|index| self.history.feature_type(index))
59            .is_some_and(|ty| ty.eq_ignore_ascii_case("DFF"))
60    }
61
62    /// The picks the last run of `feature_id` resolved (empty before its
63    /// first successful run, or for another feature type).
64    pub fn deform_picks(&self, feature_id: &str) -> Vec<DeformPickRow> {
65        if !self.is_deform_feature(feature_id) {
66            return Vec::new();
67        }
68        let Some(index) = self.history.index_of(feature_id) else {
69            return Vec::new();
70        };
71        let persistent = self.history.feature_persistent_data(index).unwrap_or(Value::Null);
72        let Some(rows) = persistent.pointer("/deform/resolved").and_then(Value::as_array) else {
73            return Vec::new();
74        };
75        rows.iter()
76            .filter_map(|row| {
77                Some(DeformPickRow {
78                    anchor: read3(row.get("anchor")?)?,
79                    normal: read3(row.get("normal")?)?,
80                    offset: row.get("offset")?.as_f64()?,
81                    target: read3(row.get("target")?)?,
82                })
83            })
84            .collect()
85    }
86
87    /// The Deform Face whose handles are shown (the history panel feeds it).
88    pub fn deform_edit_feature(&self) -> Option<&str> {
89        self.deform_edit_feature.as_deref()
90    }
91
92    /// The pick the gizmo is armed on, for `feature_id`.
93    pub fn deform_armed_pick(&self, feature_id: &str) -> Option<usize> {
94        if self.transform_gizmo.feature_id.as_deref() != Some(feature_id) {
95            return None;
96        }
97        self.transform_gizmo.deform.as_ref().map(|arm| arm.pick)
98    }
99
100    /// Arm the gizmo on pick `pick` of `feature_id` (at its target). `false`
101    /// when there is no such pick.
102    pub fn deform_select_pick(&mut self, feature_id: &str, pick: usize) -> bool {
103        if pick >= self.deform_picks(feature_id).len() {
104            return false;
105        }
106        self.component_move_reset();
107        self.transform_gizmo.feature_id = Some(feature_id.to_string());
108        self.transform_gizmo.mode = GizmoMode::Transform;
109        self.transform_gizmo.drag = None;
110        self.transform_gizmo.anchor = None;
111        self.transform_gizmo.port = None;
112        self.transform_gizmo.cage = None;
113        self.transform_gizmo.deform = Some(DeformArm { pick, grab: None, live: None });
114        self.clear_feature_dimension_overlay();
115        self.sync_transform_gizmo();
116        true
117    }
118
119    /// When the handles are shown and one of the dots sits within
120    /// [`DEFORM_PICK_RADIUS_PX`] of CSS-pixel `(x, y)`, arm the gizmo on it and
121    /// report its index. `None` leaves the click to the ordinary selection.
122    pub fn deform_pick_at(&mut self, x: f64, y: f64) -> Option<usize> {
123        let feature_id = self.deform_edit_feature.clone()?;
124        let mut best: Option<(usize, f64)> = None;
125        for (index, row) in self.deform_picks(&feature_id).iter().enumerate() {
126            if !self.camera.projectable(row.target) {
127                continue;
128            }
129            let (sx, sy, _) = self.camera.project(row.target);
130            let d = ((sx - x).powi(2) + (sy - y).powi(2)).sqrt();
131            if d <= DEFORM_PICK_RADIUS_PX && best.is_none_or(|(_, bd)| d < bd) {
132                best = Some((index, d));
133            }
134        }
135        let (index, _) = best?;
136        self.deform_select_pick(&feature_id, index).then_some(index)
137    }
138
139    /// Every handle dot projected to VIEWPORT-LOCAL px, `(index, (x, y))`,
140    /// for the host's hit blob. Empty unless handles are shown.
141    pub fn deform_pick_screen_points(&self) -> Vec<(usize, (f64, f64))> {
142        let Some(feature_id) = self.deform_edit_feature.as_deref() else {
143            return Vec::new();
144        };
145        self.deform_picks(feature_id)
146            .into_iter()
147            .enumerate()
148            .filter(|(_, row)| self.camera.projectable(row.target))
149            .map(|(index, row)| {
150                let (sx, sy, _) = self.camera.project(row.target);
151                (index, (sx, sy))
152            })
153            .collect()
154    }
155
156    /// The armed pick's pose: the live drag pose while a drag is in flight,
157    /// else its target with the world frame.
158    pub(super) fn deform_pose(&self) -> Option<TransformPose> {
159        let arm = self.transform_gizmo.deform.as_ref()?;
160        if self.transform_gizmo.drag.is_some() {
161            if let Some(live) = arm.live {
162                return Some(live);
163            }
164        }
165        let feature_id = self.transform_gizmo.feature_id.as_deref()?;
166        let row = self.deform_picks(feature_id).get(arm.pick)?.clone();
167        Some(TransformPose { position: row.target, rotation_deg: [0.0; 3], scale: [1.0; 3] })
168    }
169
170    /// Snapshot the armed pick at the grab.
171    pub(super) fn deform_grab_begin(&mut self) {
172        let Some(feature_id) = self.transform_gizmo.feature_id.clone() else {
173            return;
174        };
175        let Some(pick) = self.transform_gizmo.deform.as_ref().map(|arm| arm.pick) else {
176            return;
177        };
178        let row = self.deform_picks(&feature_id).get(pick).cloned();
179        // A drag is its own undo step: a form edit of the same feature just
180        // before it (same coalesce key for the form's offset) is not folded in.
181        self.history.break_coalescing();
182        if let (Some(arm), Some(row)) = (self.transform_gizmo.deform.as_mut(), row) {
183            arm.grab = Some((row.offset, row.target, row.normal));
184            arm.live = None;
185        }
186    }
187
188    pub(super) fn deform_grab_end(&mut self) {
189        if let Some(arm) = self.transform_gizmo.deform.as_mut() {
190            arm.grab = None;
191            arm.live = None;
192        }
193    }
194
195    /// The gizmo's write-back: the offset at the grab plus the motion along
196    /// the pick's normal.
197    pub(super) fn write_deform_pose(&mut self, pose: &TransformPose) {
198        let Some(feature_id) = self.transform_gizmo.feature_id.clone() else {
199            return;
200        };
201        let Some(arm) = self.transform_gizmo.deform.clone() else {
202            return;
203        };
204        let Some((offset, target, normal)) = arm.grab else {
205            return;
206        };
207        let along: f64 = (0..3).map(|axis| (pose.position[axis] - target[axis]) * normal[axis]).sum();
208        let moved = offset + along;
209        let moved = if self.transform_dragging() { crate::formatting::snap_drag_moved(offset, moved) } else { moved };
210        if let Some(live) = self.transform_gizmo.deform.as_mut() {
211            // The handle follows the normal, whatever axis is dragged.
212            live.live = Some(TransformPose {
213                position: std::array::from_fn(|axis| target[axis] + normal[axis] * (moved - offset)),
214                rotation_deg: [0.0; 3],
215                scale: [1.0; 3],
216            });
217        }
218        // Nothing to write when the stored offset already is `moved`. Compared
219        // against the INPUT the last write left — not the grab's offset (a
220        // drag that went out and came back must write the grab's value back
221        // over the one it wrote on the way out), and not the evaluated
222        // `resolved` row (an asynchronous run may not have caught up). An
223        // offset still held as an expression has not been written by this
224        // drag, so it is compared against the grab: an expression is only
225        // replaced by a number when the drag actually changes it.
226        let stored = self.deform_stored_offset(&feature_id, arm.pick).unwrap_or(offset);
227        if stored == moved {
228            return;
229        }
230        let _ = self.deform_set_offset(&feature_id, arm.pick, moved, Some(&format!("deform-drag:{feature_id}")));
231    }
232
233    /// Pick `pick`'s offset as STORED (the input, not the evaluated result),
234    /// read by the rule [`Self::deform_set_offset`] writes by: its own
235    /// `offset` when it carries one, else the form's. `None` when that value
236    /// is not a plain number (an expression).
237    fn deform_stored_offset(&self, feature_id: &str, pick: usize) -> Option<f64> {
238        let index = self.history.index_of(feature_id)?;
239        let persistent = self.history.feature_persistent_data(index).unwrap_or(Value::Null);
240        match persistent.pointer(&format!("/deform/picks/{pick}/offset")) {
241            Some(Value::Null) | None => {}
242            Some(Value::String(text)) if text.trim().is_empty() => {}
243            Some(own) => return own.as_f64(),
244        }
245        self.history.feature_params(index)?.get("offset")?.as_f64()
246    }
247
248    /// Set pick `pick`'s offset: its own `offset` when the feature lists its
249    /// picks and that one carries one, else the form's `offset` (which every
250    /// pick without its own follows). `coalesce` folds a drag into one undo
251    /// step. Re-runs the history.
252    pub fn deform_set_offset(
253        &mut self,
254        feature_id: &str,
255        pick: usize,
256        offset: f64,
257        coalesce: Option<&str>,
258    ) -> Result<(), String> {
259        if !offset.is_finite() {
260            return Err("deform offset must be finite".into());
261        }
262        let index = self.history.index_of(feature_id).ok_or_else(|| format!("no feature '{feature_id}'"))?;
263        if !self.is_deform_feature(feature_id) {
264            return Err(format!("'{feature_id}' is not a Deform Face"));
265        }
266        let persistent = self.history.feature_persistent_data(index).unwrap_or(Value::Null);
267        // The kernel's rule: a pick's offset that is missing, null or blank
268        // takes the form's.
269        let own = persistent.pointer(&format!("/deform/picks/{pick}/offset")).is_some_and(|value| match value {
270            Value::Null => false,
271            Value::String(text) => !text.trim().is_empty(),
272            _ => true,
273        });
274        if own {
275            let mut deform = persistent.get("deform").cloned().unwrap_or(Value::Null);
276            deform["picks"][pick]["offset"] = serde_json::json!(offset);
277            self.history.set_feature_persistent_field_coalesced(index, "deform", deform, coalesce);
278        } else {
279            let mut params = self.history.feature_params(index).unwrap_or_else(|| serde_json::json!({}));
280            params["offset"] = serde_json::json!(offset);
281            self.history.set_feature_params(index, params);
282        }
283        self.rerun_history();
284        Ok(())
285    }
286
287    /// Feed the handle overlay for `feature_id` — a dot per pick target and a
288    /// line back to its anchor, the armed one highlighted — or clear it with
289    /// `None`. Cheap to call every frame: an unchanged feed is skipped.
290    pub fn refresh_deform_edit_overlay(&mut self, feature_id: Option<&str>) {
291        let feature_id = feature_id.filter(|id| self.is_deform_feature(id));
292        if self.deform_edit_feature.as_deref() != feature_id {
293            self.deform_edit_feature = feature_id.map(str::to_string);
294        }
295        let armed = feature_id.and_then(|id| self.deform_armed_pick(id));
296        let key = feature_id.map(|id| (id.to_string(), armed, self.applied_generation));
297        if self.deform_overlay_key == key {
298            return;
299        }
300        self.deform_overlay_key = key;
301        let empty = serde_json::json!({ "groups": [{ "name": OVERLAY_GROUP }] }).to_string();
302        let Some(feature_id) = feature_id else {
303            let _ = self.widgets.set_overlay_json(&empty);
304            self.dirty = true;
305            return;
306        };
307        let rows = self.deform_picks(feature_id);
308        let mut line_positions: Vec<f64> = Vec::new();
309        let mut line_colors: Vec<f32> = Vec::new();
310        let mut dot_positions: Vec<f64> = Vec::new();
311        let mut dot_colors: Vec<f32> = Vec::new();
312        for (index, row) in rows.iter().enumerate() {
313            line_positions.extend_from_slice(&row.anchor);
314            line_positions.extend_from_slice(&row.target);
315            line_colors.extend_from_slice(&LINE_COLOR);
316            line_colors.extend_from_slice(&LINE_COLOR);
317            dot_positions.extend_from_slice(&row.target);
318            dot_colors.extend_from_slice(if armed == Some(index) { &DOT_SELECTED } else { &DOT_PLAIN });
319        }
320        let group = serde_json::json!({
321            "name": OVERLAY_GROUP,
322            "renderOrder": 6,
323            "lines": { "positions": line_positions, "colors": line_colors },
324            "points": { "positions": dot_positions, "colors": dot_colors, "size": DOT_SIZE_PX },
325        });
326        let _ = self.widgets.set_overlay_json(&serde_json::json!({ "groups": [group] }).to_string());
327        self.dirty = true;
328    }
329}
330