brep_render/engine_state/sketch_mode.rs
1use super::*;
2
3/// One in-flight sketch drag (S2): the grabbed points and the anchor uv. A single
4/// entry for a point grab; all of a geometry's (deduped) points for a geometry
5/// grab (a rigid translate). Each point tracks the cursor by an ABSOLUTE
6/// `orig + (uv - anchor)` (never incremental — the solver moves points between
7/// frames, so incremental deltas would drift).
8#[derive(Clone)]
9pub struct SketchDrag {
10 /// Per grabbed point: `(id, orig_x, orig_y, orig_fixed)` captured once at grab.
11 pub(super) points: Vec<(serde_json::Value, f64, f64, bool)>,
12 /// The plane `(u, v)` where the grab started — the anchor for the delta.
13 pub(super) anchor: (f64, f64),
14}
15
16/// The active engine-native sketch edit — the live session plus the state to
17/// restore when sketch mode exits.
18pub struct SketchEdit {
19 /// The live solved sketch session (the doc being edited + its plane).
20 pub session: crate::sketch::SketchSession,
21 /// The id of the `"S"` feature this edit belongs to.
22 pub feature_id: String,
23 /// The rolled-to step to restore on exit (the model state before entering).
24 prev_rollback: usize,
25 /// The camera to restore on exit (the vantage before the plane orient).
26 prev_camera: crate::view::ViewCamera,
27 /// Whether this sketch was created THIS edit (so a cancel deletes it).
28 is_new: bool,
29 /// For a sketch created by this session: the undo step its creation took
30 /// (`History::undo_top` right after the push). Finish writes into that
31 /// step and Cancel retracts it, while nothing else has taken a step since,
32 /// so a new sketch is one undo step and a cancelled one is none.
33 creation_step: Option<u64>,
34 /// The in-flight drag (S2): the grabbed points + anchor, or `None` when no drag
35 /// is live. Grabs a point OR a whole geometry (rigid translate). See [`SketchDrag`].
36 pub(super) drag: Option<SketchDrag>,
37 /// The in-progress draw-tool click buffer (S3a): the point ids placed so far for
38 /// the geometry being drawn (a line-chain's running start, a rect/circle/arc's
39 /// first clicks). Cleared when a geometry lands, the tool changes, or on cancel.
40 pub(super) pending: Vec<serde_json::Value>,
41 /// The last hovered plane `(u, v)` (S3a) — the anchor for the rubber-band preview
42 /// so it follows the cursor while a tool has pending clicks.
43 pub(super) hover_uv: Option<(f64, f64)>,
44 /// Per-session UNDO stack (S6a): snapshots of the visible edit state taken at the
45 /// START of each discrete mutating op. Separate from the model-level undo (which
46 /// owns the FEATURE document). Cleared implicitly on enter/exit (a fresh
47 /// `SketchEdit` starts empty; exit drops the whole struct).
48 pub(super) undo_stack: Vec<SketchSnapshot>,
49 /// Per-session REDO stack (S6a): states popped by `sketch_undo`, restored by
50 /// `sketch_redo`. Cleared whenever a new mutation records an undo snapshot.
51 pub(super) redo_stack: Vec<SketchSnapshot>,
52 /// First-move guard for a dimension-label DRAG (S6a): set when the drag's single
53 /// undo snapshot has been taken, reset at the gesture end
54 /// ([`sketch_dimension_drag_end`](EngineState::sketch_dimension_drag_end)) so the
55 /// whole drag is ONE undo step, not one per motion frame.
56 pub(super) dim_drag_snapshotted: bool,
57 /// The external-reference edge links (S6b-2): one [`crate::sketch::ExternalRef`]
58 /// per linked scene edge (by name), mapping it to the materialized sketch points +
59 /// construction geometry. Loaded from `persistentData.externalRefs` on enter,
60 /// written back on commit, and captured in the undo snapshot so undo restores it
61 /// alongside the doc.
62 pub(super) external_refs: Vec<crate::sketch::ExternalRef>,
63 /// Names the feature's `projectedEdges` list carried at enter that had
64 /// nothing to materialize: the edge did not resolve in the backdrop scene
65 /// (a downstream edge, a typo). They are not links, so they are not in
66 /// `external_refs`, but Finish keeps them listed for the kernel to report
67 /// as unresolved — the editor never silently drops a dialog entry.
68 pub(super) listed_unlinked: Vec<String>,
69 /// The in-progress freehand stroke (S6b-3): raw plane `(u, v)` samples captured
70 /// during a handdraw drag, recognized into geometry on drag-end. Empty when no
71 /// stroke is live. Transient interaction state — NOT part of the undo snapshot.
72 pub(super) handdraw_stroke: Vec<(f64, f64)>,
73}
74
75/// One reversible sketch-edit state (S6a): a clone of everything the visible edit
76/// carries — the solved [`SketchDoc`](crate::sketch::SketchDoc), the dimension label
77/// offsets, and the selection — enough to fully restore the session on undo/redo.
78/// Transient interaction state (in-flight drag, draw pending buffer) is deliberately
79/// NOT captured; undo/redo clears it instead.
80#[derive(Clone)]
81pub(super) struct SketchSnapshot {
82 pub(super) doc: crate::sketch::SketchDoc,
83 pub(super) dim_offsets: serde_json::Map<String, serde_json::Value>,
84 pub(super) selection: Vec<serde_json::Value>,
85 /// The external-reference mapping (S6b-2) — captured so undoing a pickEdges link
86 /// also drops its `ExternalRef` entry, keeping the mapping consistent with the doc.
87 pub(super) external_refs: Vec<crate::sketch::ExternalRef>,
88}
89
90impl SketchEdit {
91 /// A snapshot of the CURRENT visible edit state (doc + dim offsets + selection +
92 /// external refs).
93 pub(super) fn snapshot(&self) -> SketchSnapshot {
94 SketchSnapshot {
95 doc: self.session.doc.clone(),
96 dim_offsets: self.session.dim_offsets.clone(),
97 selection: self.session.selection.clone(),
98 external_refs: self.external_refs.clone(),
99 }
100 }
101
102 /// Push the current state onto the undo stack and clear redo — the discrete-op
103 /// undo primitive. Callers invoke this at the START of a mutation (before the doc
104 /// changes) so one Ctrl+Z reverts that op.
105 pub(super) fn record_undo(&mut self) {
106 let snap = self.snapshot();
107 self.undo_stack.push(snap);
108 self.redo_stack.clear();
109 }
110}
111
112/// Convert a kernel [`brep_kernel::Frame`] into the sketch module's
113/// [`crate::sketch::PlaneFrame`]. Kept HERE (not in `sketch/mod.rs`, which is
114/// deliberately kernel-free) so a sketch's kernel-resolved plane frame — the exact
115/// frame the committed sheet is materialized against — can seed the live session.
116fn plane_frame_from_kernel(frame: &brep_kernel::Frame) -> crate::sketch::PlaneFrame {
117 crate::sketch::PlaneFrame {
118 origin: [frame.origin.x, frame.origin.y, frame.origin.z],
119 x_axis: [frame.x_axis.x, frame.x_axis.y, frame.x_axis.z],
120 y_axis: [frame.y_axis.x, frame.y_axis.y, frame.y_axis.z],
121 z_axis: [frame.z_axis.x, frame.z_axis.y, frame.z_axis.z],
122 }
123}
124
125impl EngineState {
126 /// True while a sketch is being edited (the shell hides the normal side panel
127 /// and shows the sketch-mode bar).
128 pub fn sketch_mode(&self) -> bool {
129 self.sketch_edit.is_some()
130 }
131
132 /// The live sketch session while in sketch mode (for the DOF readout / overlay
133 /// / the headless verifier), else `None`.
134 pub fn sketch_edit_session(&self) -> Option<&crate::sketch::SketchSession> {
135 self.sketch_edit.as_ref().map(|edit| &edit.session)
136 }
137
138 /// The id of the feature being edited while in sketch mode, else `None`.
139 pub fn sketch_edit_feature_id(&self) -> Option<&str> {
140 self.sketch_edit.as_ref().map(|edit| edit.feature_id.as_str())
141 }
142
143 /// Whether the sketch camera is locked flat to the plane (only panning). On by
144 /// default every sketch entry; the sketch-mode bar's checkbox reflects this.
145 pub fn sketch_camera_locked(&self) -> bool {
146 self.sketch_camera_locked
147 }
148
149 /// Toggle the sketch camera lock. Turning it ON re-faces the camera to the
150 /// current sketch plane (so "off → spin around → on" snaps back flat); turning
151 /// it OFF just frees orbiting. No-op outside sketch mode.
152 pub fn toggle_sketch_camera_lock(&mut self) {
153 if !self.sketch_mode() {
154 return;
155 }
156 self.sketch_camera_locked = !self.sketch_camera_locked;
157 if self.sketch_camera_locked {
158 // `PlaneFrame` is `Copy`, so this ends the `&self` borrow before the
159 // `&mut self` re-orient.
160 if let Some(plane) = self.sketch_edit_session().map(|s| s.plane) {
161 self.face_camera_to_plane(&plane);
162 self.dirty = true;
163 }
164 }
165 }
166
167 /// Orient the camera flat-on to a sketch plane: look along the NEGATIVE normal
168 /// with the plane's +y as up, so the plane faces the viewer. Shared by sketch
169 /// entry and the lock toggle.
170 fn face_camera_to_plane(&mut self, plane: &crate::sketch::PlaneFrame) {
171 let dir = [
172 -(plane.z_axis[0] as f32),
173 -(plane.z_axis[1] as f32),
174 -(plane.z_axis[2] as f32),
175 ];
176 let up = [
177 plane.y_axis[0] as f32,
178 plane.y_axis[1] as f32,
179 plane.y_axis[2] as f32,
180 ];
181 self.apply_look_direction(dir, up);
182 }
183
184 /// Enter sketch mode for the `"S"` feature with id `feature_id`: snapshot the
185 /// camera + rolled-to step, roll to the step BEFORE the sketch (its backdrop),
186 /// read the persisted plane `basis` + `sketch` doc off the history JSON, solve
187 /// a live session, orient the camera onto the plane, and push the read-only
188 /// overlay. Returns the session's diagnostics JSON. Errors when the feature is
189 /// absent or is not a sketch.
190 pub fn enter_sketch_mode(&mut self, feature_id: &str) -> Result<String, String> {
191 let index = self
192 .history
193 .index_of(feature_id)
194 .ok_or_else(|| format!("no feature with id '{feature_id}'"))?;
195 if self.history.feature_type(index).as_deref() != Some("S") {
196 return Err(format!("feature '{feature_id}' is not a sketch (type \"S\")"));
197 }
198
199 // The frame the kernel resolved for THIS sketch on the last full run is
200 // published under the sketch's own id in `construction_frames` (see
201 // `feature_pipeline::features::sketch::execute` → `result.frames`). It is, by
202 // construction, the EXACT frame the committed sheet was materialized against
203 // (the sheet's world curves come from the same `SketchProfile` frame). Capture
204 // it NOW, before the roll below drops the sketch from `construction_frames` —
205 // seeding the live session with it keeps the editing overlay on the same plane
206 // the committed sheet lands on. This fixes the off-location sheet for
207 // face/datum-attached sketches whose live-resolved frame differs from the
208 // persisted `basis` (which the kernel only uses as a missing-reference fallback).
209 let resolved_frame = self
210 .construction_frames
211 .iter()
212 .find(|(name, _)| name == feature_id)
213 .map(|(_, frame)| plane_frame_from_kernel(frame));
214
215 // Snapshot the pre-entry view + roll, then roll to the step just before the
216 // sketch so the model up to (not including) it is the sketching backdrop.
217 let prev_camera = self.camera.clone();
218 let prev_rollback = self.history.rollback();
219 self.history.set_rollback(index.saturating_sub(1));
220 self.rerun_history();
221
222 // Read the persisted plane + doc straight off the history JSON (headless).
223 // The plane is the kernel-resolved frame when available (live-first, matching
224 // the SKETCH feature's `resolve_frame`), else the persisted `basis`, else XY.
225 let persistent = self.history.feature_persistent_data(index);
226 let plane = resolved_frame
227 .or_else(|| {
228 persistent
229 .as_ref()
230 .and_then(|p| p.get("basis"))
231 .map(crate::sketch::PlaneFrame::from_basis_json)
232 })
233 .unwrap_or_else(crate::sketch::PlaneFrame::xy);
234 let doc_value = persistent
235 .as_ref()
236 .and_then(|p| p.get("sketch"))
237 .cloned()
238 .unwrap_or_else(|| {
239 serde_json::json!({ "points": [], "geometries": [], "constraints": [] })
240 });
241 let mut doc: crate::sketch::SketchDoc = serde_json::from_value(doc_value)
242 .map_err(|error| format!("sketch doc parse: {error}"))?;
243 // Every sketch carries the part origin projected onto its plane, as a
244 // fixed reference to constrain to (added on first entry, re-projected
245 // when the plane moved).
246 crate::sketch::external_ref::ensure_origin_point(&mut doc, &plane);
247 let mut session = crate::sketch::SketchSession::new(doc, plane)?;
248 // Seed the overlay palette from the live display settings so the sketch colors
249 // are managed there like the rest of the display (kept in sync by
250 // `apply_settings_json` whenever the user edits a sketch color).
251 session.colors = self.settings.sketch_colors();
252 // Load the persisted per-dimension label offsets (S5) — plane-space
253 // `{du, dv}` keyed by constraint id, written back on commit below.
254 if let Some(offsets) = persistent
255 .as_ref()
256 .and_then(|p| p.get("dimOffsets"))
257 .and_then(serde_json::Value::as_object)
258 {
259 session.dim_offsets = offsets.clone();
260 }
261 // Load the persisted external-reference edge links (S6b-2) — the mapping from
262 // linked scene edges to their materialized points/geometry, round-tripped on
263 // commit below. A malformed array degrades to no refs.
264 let mut external_refs: Vec<crate::sketch::ExternalRef> = persistent
265 .as_ref()
266 .and_then(|p| p.get("externalRefs"))
267 .and_then(|v| serde_json::from_value(v.clone()).ok())
268 .unwrap_or_default();
269 // Heal docs poisoned by the pre-fix delete: drop any linked-edge entry whose
270 // materialized points/geometry are gone, so its edge can be RE-LINKED (a stale
271 // entry's dead dedup path would otherwise block the re-link forever). Reproject
272 // (below) then only touches live refs.
273 crate::sketch::external_ref::prune_dead_refs(&session.doc, &mut external_refs);
274 // The feature's `projectedEdges` list is the one record of the linked
275 // edges: every listed edge the backdrop resolves is materialized below
276 // (a dialog entry shows up in the editor), and a link the list no
277 // longer names was removed from the dialog — but only once a unified
278 // Finish stamped the marker; before that the entries were never
279 // listed, so they are adopted, not released.
280 let listed = brep_kernel::reference_names(
281 self.history
282 .feature_params(index)
283 .as_ref()
284 .and_then(|p| p.get("projectedEdges")),
285 );
286 let links_listed = persistent
287 .as_ref()
288 .and_then(|p| p.get(crate::sketch::external_ref::LINKS_LISTED_KEY))
289 .and_then(serde_json::Value::as_bool)
290 == Some(true);
291
292 // Drop any MODEL selection carried in from picking the sketch plane, so no
293 // faces/edges stay highlighted inside the sketch — the only highlight the
294 // user should see there is the sketch's own geometry (or an entity they
295 // pick to link in). Covers the new-sketch path too (`new_sketch` enters
296 // through here).
297 self.clear_selection();
298
299 // Every sketch entry starts with the camera LOCKED flat to the plane (the
300 // default): face it now, and `face_camera_to_plane` re-does this when the
301 // user toggles the lock back on.
302 self.sketch_camera_locked = true;
303 self.face_camera_to_plane(&plane);
304
305 // Push the overlay + capture diagnostics BEFORE moving the session into the
306 // edit (both are borrows of the local `session`).
307 self.set_sketch_overlay(&session);
308 let diagnostics =
309 serde_json::to_string(&session.diagnostics).unwrap_or_else(|_| "{}".to_string());
310
311 self.sketch_edit = Some(SketchEdit {
312 session,
313 feature_id: feature_id.to_string(),
314 prev_rollback,
315 prev_camera,
316 is_new: false,
317 creation_step: None,
318 drag: None,
319 pending: Vec::new(),
320 hover_uv: None,
321 // A fresh session starts with empty undo/redo history (S6a).
322 undo_stack: Vec::new(),
323 redo_stack: Vec::new(),
324 dim_drag_snapshotted: false,
325 external_refs,
326 listed_unlinked: Vec::new(),
327 handdraw_stroke: Vec::new(),
328 });
329 // Sync the links with the list against the CURRENT backdrop model: every
330 // loaded ref re-projects so a linked edge tracks upstream geometry edits,
331 // a listed edge without a ref is linked, and (once unified) a ref the
332 // list dropped is released. Best-effort on a missing edge — the
333 // persisted coords stand as the fallback; the regenerate fold, which
334 // has the kernel's word on what resolves, is what releases those. This
335 // may move the ref points + re-solve, so re-read diagnostics afterward.
336 let reprojected = self.sketch_sync_external_refs(&listed, links_listed);
337 let diagnostics = if reprojected {
338 self.sketch_edit
339 .as_ref()
340 .map(|edit| {
341 serde_json::to_string(&edit.session.diagnostics)
342 .unwrap_or_else(|_| "{}".to_string())
343 })
344 .unwrap_or(diagnostics)
345 } else {
346 diagnostics
347 };
348 // Clear the now-active sketch's committed overlay: the mid-enter rerun above
349 // (rolled to the step before the sketch, `sketch_edit` not yet set) may have
350 // fed it; now `sketch_edit` is armed, so it is excluded and cleared — the live
351 // editing overlay is its only display while editing (no double display).
352 self.refresh_committed_sketches();
353 self.dirty = true;
354 Ok(diagnostics)
355 }
356
357 /// Exit sketch mode. `commit` writes the edited doc back to the feature's
358 /// `persistentData.sketch`; a non-commit exit of a brand-new sketch DELETES the
359 /// feature (a fresh sketch nobody kept). Restores the snapshotted camera +
360 /// rolled-to step, clears the overlay, re-runs the history, and returns the
361 /// build report. A no-op (returns `"{}"`) when not in sketch mode.
362 pub fn exit_sketch_mode(&mut self, commit: bool) -> String {
363 let Some(edit) = self.sketch_edit.take() else {
364 return "{}".to_string();
365 };
366 if commit {
367 if let Some(index) = self.history.index_of(&edit.feature_id) {
368 let mut sketch_value = serde_json::to_value(&edit.session.doc).unwrap_or_else(|_| {
369 serde_json::json!({ "points": [], "geometries": [], "constraints": [] })
370 });
371 // Stamp each closed loop's STABLE id onto its geometries. The
372 // kernel derives the same ids when it reads the sketch, so this
373 // changes no name — it persists the id against the one edit
374 // deriving cannot survive: deleting the edge the id came from.
375 // Per-loop face names (extrude/sweep/revolve/loft caps) embed it.
376 brep_kernel::assign_sketch_loop_ids(&mut sketch_value);
377 // The dimension label offsets persist alongside the doc (S5) so a
378 // re-enter restores each dimension's dragged label position, and
379 // the external-reference edge links (S6b-2) so a re-enter reloads
380 // (and re-projects) each linked scene edge.
381 let refs_value = serde_json::to_value(&edit.external_refs)
382 .unwrap_or_else(|_| serde_json::Value::Array(Vec::new()));
383 // One write, so Finish is ONE undo step (and none when the
384 // session changed nothing). A sketch this session created
385 // writes into its creation's step, so the whole new sketch is
386 // one step.
387 // The linked edges are the feature's `projectedEdges` list:
388 // listed order kept, dropped links gone, unmaterialized entries
389 // kept, new links appended.
390 let current = self.history.feature_params(index);
391 let listed = brep_kernel::reference_names(
392 current.as_ref().and_then(|p| p.get("projectedEdges")),
393 );
394 let names = crate::sketch::external_ref::listed_edge_names(
395 &listed,
396 &edit.external_refs,
397 &edit.listed_unlinked,
398 );
399 let mut fields = vec![
400 ("sketch", sketch_value),
401 ("dimOffsets", serde_json::Value::Object(edit.session.dim_offsets.clone())),
402 ("externalRefs", refs_value),
403 ];
404 // From the first Finish that has a link on, the list names every
405 // link (see `enter_sketch_mode`'s adopt-or-release rule). A
406 // sketch that never linked anything is left unstamped, so a
407 // Finish that changed nothing still writes nothing.
408 if !names.is_empty() || !edit.external_refs.is_empty() {
409 fields.push((
410 crate::sketch::external_ref::LINKS_LISTED_KEY,
411 serde_json::Value::Bool(true),
412 ));
413 }
414 match edit.creation_step {
415 Some(step) => {
416 self.history.set_feature_persistent_fields_in_step(index, fields, step);
417 }
418 None => {
419 self.history.set_feature_persistent_fields(index, fields);
420 }
421 }
422 // Write the links into the list. Folded without a checkpoint so
423 // Finish stays ONE undo step — the snapshot above already holds
424 // the pre-Finish list — and skipped when the names already match,
425 // so an unchanged Finish does not tick the revision.
426 if names != listed {
427 self.history.fold_param_no_undo(
428 &edit.feature_id,
429 "projectedEdges",
430 serde_json::Value::Array(names.into_iter().map(serde_json::Value::String).collect()),
431 );
432 }
433 }
434 } else if edit.is_new {
435 // Retract the creation's step, so the cancel leaves nothing to
436 // undo; only if something else took a step since, delete the
437 // feature as a step of its own.
438 if edit.creation_step.is_some_and(|step| self.history.retract(step)) {
439 self.reinstall_rewound_parts_library();
440 } else if let Some(index) = self.history.index_of(&edit.feature_id) {
441 self.history.remove_feature(index);
442 }
443 }
444 self.history.set_rollback(edit.prev_rollback);
445 self.clear_sketch_overlay();
446 self.camera = edit.prev_camera;
447 self.dirty = true;
448 self.rerun_history()
449 }
450
451 /// Create a NEW engine-native sketch on a base plane (`"XY" | "XZ" | "YZ"`) and
452 /// enter sketch mode on it. The feature persists an analytic `basis` (computed
453 /// via [`crate::sketch::PlaneFrame`]) and an empty `sketch` doc; a cancel exit
454 /// deletes it. Returns the new session's diagnostics JSON. Errors on an unknown
455 /// plane name.
456 pub fn new_sketch(&mut self, plane: &str) -> Result<String, String> {
457 let frame = match plane {
458 "XY" => crate::sketch::PlaneFrame::xy(),
459 "XZ" => crate::sketch::PlaneFrame::xz(),
460 "YZ" => crate::sketch::PlaneFrame::yz(),
461 other => {
462 return Err(format!("unknown base plane '{other}' (expected XY|XZ|YZ)"));
463 }
464 };
465 let id = self
466 .history
467 .next_feature_id(&crate::features::feature_short_name("S"));
468 let feature = serde_json::json!({
469 "type": "S",
470 "inputParams": { "id": id, "sketchPlane": plane },
471 "persistentData": {
472 "basis": {
473 "origin": frame.origin,
474 "x": frame.x_axis,
475 "y": frame.y_axis,
476 "z": frame.z_axis,
477 },
478 "sketch": { "points": [], "geometries": [], "constraints": [] }
479 }
480 });
481 self.history.push_feature(feature);
482 let creation_step = self.history.undo_top();
483 let diagnostics = self.enter_sketch_mode(&id)?;
484 if let Some(edit) = self.sketch_edit.as_mut() {
485 edit.is_new = true;
486 edit.creation_step = creation_step;
487 }
488 Ok(diagnostics)
489 }
490}