Skip to main content

brep_render/engine_state/
simulation_play.rs

1//! Motion-study playback: bake, play, scrub.
2//!
3//! A study's frames are solved ONCE, in order, through the kernel's frame
4//! solve (`assembly_frame_solve_impl`: the mates at the motors' values and the
5//! suppress clips' switches, warm-started from the previous frame), and kept
6//! as poses — [`BakedFrame`]s — until the document changes. Playback,
7//! scrubbing and (later) every output read the same frames, so they cannot
8//! disagree. The solve is sequential (scrubbing backwards would otherwise mean
9//! re-solving from 0), so it is time-sliced under a per-tick budget inside the
10//! app's frame ([`EngineState::simulation_tick`]) rather than run at once, and
11//! the pane shows its progress; the playhead never runs ahead of the bake.
12//!
13//! Displays are posed by matrix over the geometry the renderer already holds
14//! (`SolidDisplay::pose`, as an exploded view's are), re-posing only the
15//! occurrences whose pose changed since the shown frame, and
16//! [`EngineState::simulation_stop`] puts every display back exactly. Nothing
17//! is written to the document. A frame the mates cannot hold keeps the
18//! previous frame's poses and is marked failed; it never stops the bake.
19//!
20//! Interference is checked on every baked frame (`Study::interference`): the
21//! occurrences' display meshes, posed by the frame, are screened pair by pair
22//! for an edge of one piercing a face of the other (`interference::
23//! displays_pierce`: face-to-face contact is not a clash, nor are coincident
24//! surfaces). A clashing frame is marked, its parts are tinted while shown,
25//! and playback keeps going — there is no stop at contact.
26//!
27//! The timeline's clips are read from the same study sample: suppress clips
28//! go into the bake (a mate off for the frame), and at show time a frame's
29//! sample hides the occurrences of its visibility clips, folds an explode
30//! clip's step translations (from the exploded view's record) into the
31//! occurrences' poses, drives the camera between two PMI views' cameras for
32//! a camera clip — the camera as it stood before the first such frame is
33//! kept and given back with the displays — sets the displays' opacity for a
34//! transparency clip, and cuts the posed displays on a PMI view's section
35//! planes (swept along their normals) for a section clip. No PMI view is
36//! ever activated by playback: one posing path, one set of originals, one
37//! exact restore.
38
39use super::interference::{displays_pierce, overlaps, posed_bbox};
40use super::pmi_section::{clip_display_all, side_of_all, Side};
41use super::{component_move::now_ms, EngineState};
42use crate::camera::Aabb;
43use crate::scene::SolidDisplay;
44use brep_kernel::{PmiCamera, PmiProjection};
45use brep_simulation::model::Study;
46use brep_simulation::sample::SectionSample;
47use brep_simulation::FrameSample;
48use serde_json::{json, Map, Value};
49use std::collections::{BTreeMap, HashMap};
50
51/// Solving per app tick: a 121-frame study of a small mechanism bakes in a
52/// few ticks while the UI keeps drawing.
53const BAKE_BUDGET_MS: f64 = 12.0;
54
55/// One baked frame: every movable occurrence's world pose (row-major 4×4, the
56/// kernel's spelling), and whether the mates held it.
57#[derive(Debug, Clone, PartialEq)]
58pub struct BakedFrame {
59    pub poses: BTreeMap<String, [f64; 16]>,
60    /// The mates could not hold this frame; the previous frame's poses stand in.
61    pub failed: bool,
62    /// The occurrence pairs that interfere at this frame (each `a < b`), by
63    /// the participant ids of the interference check; empty when the study
64    /// does not check or nothing clashes.
65    pub clashes: Vec<(String, String)>,
66}
67
68/// The row-major identity pose.
69pub(super) const IDENTITY: [f64; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
70
71/// The tint of a clashing part's displays while its frame is shown.
72const CLASH_TINT: [f32; 3] = [0.92, 0.25, 0.2];
73
74/// The study being played or scrubbed, its bake so far and what the displays
75/// show of it.
76#[derive(Debug)]
77pub struct SimulationPlayback {
78    pub study: String,
79    /// The study as baked, and the document revision it was baked against;
80    /// either moving starts the bake over.
81    baked_study: Study,
82    revision: u64,
83    /// The mates' document values, what a speed motor starts from.
84    base: HashMap<String, f64>,
85    pub frames: Vec<BakedFrame>,
86    total: usize,
87    /// The previous frame's reply poses: the next frame's warm start.
88    reference: Map<String, Value>,
89    /// The playhead, seconds.
90    pub time: f64,
91    pub playing: bool,
92    pub looping: bool,
93    /// The frame the displays show.
94    shown: Option<usize>,
95    /// The frame asked for (by a seek or the playhead); shown once it is baked.
96    wanted: Option<usize>,
97    /// Displays as they were before their first pose, by solid name.
98    originals: HashMap<String, SolidDisplay>,
99    /// Occurrence → the world pose its displays show.
100    applied: HashMap<String, [f64; 16]>,
101    /// The last frame the mates could not hold, and why.
102    pub error: Option<String>,
103    /// The interference check's participants: occurrence → its member solids
104    /// (`interference_participants`, taken at prepare).
105    participants: Vec<(String, Vec<String>)>,
106    /// The solids tinted for the shown frame's clashes.
107    tinted: Vec<String>,
108    /// The solids a visibility clip hides at the shown frame.
109    hidden: Vec<String>,
110    /// The solids a transparency clip made see-through at the shown frame.
111    translucent: Vec<String>,
112    /// The solids a section clip cut or hid at the shown frame; put back
113    /// (and re-posed) before the next frame is posed.
114    sectioned: Vec<String>,
115    /// The camera as it stood before a camera clip first drove it; given
116    /// back with the displays.
117    camera_before: Option<PmiCamera>,
118    /// The shown frame's clip sample (what automation reads).
119    shown_sample: Option<FrameSample>,
120}
121
122impl SimulationPlayback {
123    /// The study as baked.
124    pub(crate) fn baked_study(&self) -> &Study {
125        &self.baked_study
126    }
127
128    /// The document revision the bake was made against.
129    pub(crate) fn revision(&self) -> u64 {
130        self.revision
131    }
132
133    /// The mates' document values (a speed motor's start).
134    pub(crate) fn base(&self) -> &HashMap<String, f64> {
135        &self.base
136    }
137
138    /// The display as the document poses it, when playback has recorded it.
139    pub(crate) fn original(&self, name: &str) -> Option<&SolidDisplay> {
140        self.originals.get(name)
141    }
142}
143
144impl EngineState {
145    /// The playback, if a study has been played or scrubbed.
146    pub(crate) fn simulation_playback(&self) -> Option<&SimulationPlayback> {
147        self.simulation_play.as_ref()
148    }
149
150    /// Bake `study` (the active one when `None`) to the end, now: the whole
151    /// bake in one call, as an export or a published motion needs it. Pauses
152    /// playback; the playhead is kept. Returns the study id.
153    pub fn simulation_bake_all(&mut self, study: Option<&str>) -> Result<String, String> {
154        let id = self.simulation_prepare(study)?;
155        if let Some(play) = self.simulation_play.as_mut() {
156            play.playing = false;
157        }
158        if !self.ensure_assembly_session() {
159            return Err(super::ASSEMBLY_SESSION_PENDING.into());
160        }
161        let mut guard = 0usize;
162        while self.simulation_play.as_ref().is_some_and(|play| play.frames.len() < play.total) {
163            guard += 1;
164            if guard > 1_000_000 {
165                return Err("the bake did not finish".into());
166            }
167            self.simulation_bake_next();
168        }
169        Ok(id)
170    }
171
172    /// A publish wrote `motion` into `study`'s block entry: the bake is of the
173    /// same study still, so it is kept — its record takes the motion and the
174    /// revision the write made, which `simulation_prepare` compares.
175    pub(super) fn simulation_keep_bake_through_publish(&mut self, study: &str, motion: Value) {
176        let revision = self.history.revision();
177        if let Some(play) = self.simulation_play.as_mut().filter(|play| play.study == study) {
178            play.baked_study.motion = Some(motion);
179            play.revision = revision;
180        }
181    }
182
183    /// Play `study` (the active one when `None`) from where its playhead
184    /// stands — from 0 when it stands at the end — baking it first if need
185    /// be; `looping` sets whether it repeats. Returns the study id.
186    pub fn simulation_play(&mut self, study: Option<&str>, looping: Option<bool>) -> Result<String, String> {
187        let id = self.simulation_prepare(study)?;
188        let play = self.simulation_play.as_mut().expect("prepared");
189        if let Some(looping) = looping {
190            play.looping = looping;
191        }
192        if play.time >= play.baked_study.duration - 1e-9 {
193            play.time = 0.0;
194        }
195        play.playing = true;
196        play.wanted = Some(play.baked_study.frame_at(play.time));
197        Ok(id)
198    }
199
200    /// Hold the playhead where it is; the frame stays shown.
201    pub fn simulation_pause(&mut self) {
202        if let Some(play) = self.simulation_play.as_mut() {
203            play.playing = false;
204        }
205    }
206
207    /// Every display back at its document pose, the playhead at 0. The bake
208    /// is kept, so Play starts again at once.
209    pub fn simulation_stop(&mut self) {
210        self.simulation_restore_displays();
211        if let Some(play) = self.simulation_play.as_mut() {
212            play.playing = false;
213            play.time = 0.0;
214            play.wanted = None;
215        }
216    }
217
218    /// Put the playhead at `time` (seconds, clamped to the study) and show
219    /// that frame, pausing; a frame not baked yet is shown when it is.
220    pub fn simulation_seek(&mut self, study: Option<&str>, time: f64) -> Result<(), String> {
221        if !time.is_finite() {
222            return Err("seek: the time is not a number".into());
223        }
224        self.simulation_prepare(study)?;
225        let play = self.simulation_play.as_mut().expect("prepared");
226        play.playing = false;
227        play.time = time.clamp(0.0, play.baked_study.duration);
228        play.wanted = Some(play.baked_study.frame_at(play.time));
229        self.simulation_show_wanted();
230        Ok(())
231    }
232
233    /// Whether playback repeats at the study's end.
234    pub fn simulation_set_looping(&mut self, study: Option<&str>, looping: bool) -> Result<(), String> {
235        self.simulation_prepare(study)?;
236        self.simulation_play.as_mut().expect("prepared").looping = looping;
237        Ok(())
238    }
239
240    /// Whether a study is being played or scrubbed (its displays may be posed).
241    pub fn simulation_playing_or_shown(&self) -> bool {
242        self.simulation_play.as_ref().is_some_and(|play| play.playing || play.shown.is_some())
243    }
244
245    /// Make `study` (the active one when `None`) the playback, keeping an
246    /// up-to-date bake of the same study and starting over otherwise.
247    fn simulation_prepare(&mut self, study: Option<&str>) -> Result<String, String> {
248        let block = self.simulation()?.ok_or("no study yet: New study starts one")?;
249        let study = match study {
250            Some(id) => block.study(id).ok_or_else(|| format!("no study '{id}'"))?,
251            None => block.active_study().ok_or("no study yet: New study starts one")?,
252        }
253        .clone();
254        let revision = self.history.revision();
255        let current = self
256            .simulation_play
257            .as_ref()
258            .is_some_and(|play| play.study == study.id && play.revision == revision && play.baked_study == study);
259        if current {
260            return Ok(study.id);
261        }
262        // Another study's (or a stale bake's) poses go, and an exploded view
263        // is put away, so every display sits at its document pose: what the
264        // frames' matrices are relative to.
265        self.simulation_restore_displays();
266        if self.pmi_active_view.is_some() {
267            self.pmi_deactivate_view();
268        }
269        let previous = self.simulation_play.take();
270        let (time, looping) = previous
271            .filter(|play| play.study == study.id)
272            .map_or((0.0, false), |play| (play.time.min(study.duration), play.looping));
273        let base = self.simulation_motor_mates().into_iter().map(|mate| (mate.id, mate.value)).collect();
274        let participants = if study.interference.enabled { self.interference_participants() } else { Vec::new() };
275        let total = study.frame_count();
276        let id = study.id.clone();
277        self.simulation_play = Some(SimulationPlayback {
278            study: id.clone(),
279            baked_study: study,
280            revision,
281            base,
282            frames: Vec::with_capacity(total),
283            total,
284            reference: Map::new(),
285            time,
286            playing: false,
287            looping,
288            shown: None,
289            wanted: None,
290            originals: HashMap::new(),
291            applied: HashMap::new(),
292            error: None,
293            participants,
294            tinted: Vec::new(),
295            hidden: Vec::new(),
296            translucent: Vec::new(),
297            sectioned: Vec::new(),
298            camera_before: None,
299            shown_sample: None,
300        });
301        Ok(id)
302    }
303
304    /// Advance by `dt` seconds: bake frames under the budget, move the
305    /// playhead and show its frame. `true` while another frame is needed
306    /// (playing, or still baking). The app calls it once per frame.
307    pub fn simulation_tick(&mut self, dt: f64) -> bool {
308        let Some(play) = self.simulation_play.as_ref() else { return false };
309        // The document moved under the bake: start over, keeping the playhead.
310        if play.revision != self.history.revision() {
311            let (study, time, playing, looping) = (play.study.clone(), play.time, play.playing, play.looping);
312            self.simulation_restore_displays();
313            self.simulation_play = None;
314            if self.simulation_prepare(Some(&study)).is_err() {
315                return false;
316            }
317            let play = self.simulation_play.as_mut().expect("prepared");
318            play.time = time.min(play.baked_study.duration);
319            play.playing = playing;
320            play.looping = looping;
321            play.wanted = Some(play.baked_study.frame_at(play.time));
322        }
323        let start = now_ms();
324        let mut ready = true;
325        if self.simulation_play.as_ref().is_some_and(|play| play.frames.len() < play.total) {
326            // The frame solve runs against the MAIN-side kernel session, which
327            // the history runner's thread owns after a run: bring it over (a
328            // no-op once it is current), as a live drag does before its solve.
329            // Until its copy lands, this frame bakes nothing.
330            ready = self.ensure_assembly_session();
331        }
332        while ready && self.simulation_play.as_ref().is_some_and(|play| play.frames.len() < play.total) && now_ms() - start < BAKE_BUDGET_MS {
333            self.simulation_bake_next();
334        }
335        let play = self.simulation_play.as_mut().expect("checked above");
336        if play.playing {
337            let duration = play.baked_study.duration;
338            play.time += dt.max(0.0);
339            if play.time >= duration - 1e-9 {
340                if play.looping {
341                    play.time = (play.time % duration).max(0.0);
342                } else {
343                    play.time = duration;
344                    play.playing = false;
345                }
346            }
347            // The playhead waits for the bake rather than running ahead of it.
348            let baked = play.frames.len();
349            if play.baked_study.frame_at(play.time) >= baked {
350                play.time = play.baked_study.frame_time(baked.saturating_sub(1));
351                if baked == 0 {
352                    play.time = 0.0;
353                }
354            }
355            play.wanted = Some(play.baked_study.frame_at(play.time));
356        }
357        self.simulation_show_wanted();
358        let play = self.simulation_play.as_ref().expect("checked above");
359        play.playing || play.frames.len() < play.total
360    }
361
362    /// Solve the next unbaked frame against the session (one step of the
363    /// tick's bake loop; the tests step it by hand).
364    pub(super) fn simulation_bake_next(&mut self) {
365        let Some(play) = self.simulation_play.as_mut() else { return };
366        let index = play.frames.len();
367        if index >= play.total {
368            return;
369        }
370        let time = play.baked_study.frame_time(index);
371        let base = &play.base;
372        let sample = play.baked_study.sample(time, &|id| base.get(id).copied());
373        let mut overrides = Map::new();
374        for (id, mate) in &sample.mates {
375            let mut change = Map::new();
376            if let Some(value) = mate.value {
377                change.insert("value".into(), json!(value));
378            }
379            if let Some(enabled) = mate.enabled {
380                change.insert("enabled".into(), json!(enabled));
381            }
382            overrides.insert(id.clone(), Value::Object(change));
383        }
384        let request = json!({ "overrides": overrides, "reference": play.reference });
385        let (poses, failed): (BTreeMap<String, [f64; 16]>, bool) = match brep_kernel::assembly_frame_solve_impl(&request.to_string()) {
386            Ok(reply) => {
387                let reply: Value = serde_json::from_str(&reply).unwrap_or(Value::Null);
388                let poses_json = reply.get("poses").and_then(Value::as_object).cloned().unwrap_or_default();
389                let poses = poses_json.iter().map(|(id, pose)| (id.clone(), crate::pipeline::pose_params_to_transform(pose))).collect();
390                play.reference = poses_json;
391                (poses, false)
392            }
393            Err(error) => {
394                let poses = play.frames.last().map(|frame| frame.poses.clone()).unwrap_or_default();
395                play.error = Some(format!("frame {index} ({time:.3} s): {error}"));
396                (poses, true)
397            }
398        };
399        // The interference screen reads the scene, so the playback borrow ends
400        // here; its participants are lent out and put back.
401        let participants = std::mem::take(&mut play.participants);
402        let previous = play.frames.last().cloned();
403        let clashes = if participants.is_empty() { Vec::new() } else { self.simulation_frame_clashes(&participants, &poses, previous.as_ref()) };
404        let Some(play) = self.simulation_play.as_mut() else { return };
405        play.participants = participants;
406        play.frames.push(BakedFrame { poses, failed, clashes });
407    }
408
409    /// The occurrence pairs whose posed displays interfere at a frame: each
410    /// occurrence's displays are carried by its pose over the document
411    /// (identity for one the frame did not move), the pairs whose posed boxes
412    /// overlap are screened mesh against mesh, and a pair neither of whose
413    /// occurrences moved since the previous frame keeps that frame's verdict.
414    /// The geometry read is the display AS THE DOCUMENT POSES IT: a solid
415    /// already posed for a shown frame (the bake may still be running) is
416    /// read from its recorded original, never from the scene.
417    fn simulation_frame_clashes(&self, participants: &[(String, Vec<String>)], poses: &BTreeMap<String, [f64; 16]>, previous: Option<&BakedFrame>) -> Vec<(String, String)> {
418        let originals = self.simulation_play.as_ref().map(|play| &play.originals);
419        let display_of = |name: &String| -> Option<&SolidDisplay> { originals.and_then(|originals| originals.get(name)).or_else(|| self.scene.solid(name)) };
420        let delta_of = |occ: &str| -> [f64; 16] {
421            let top = occ.split(':').next().unwrap_or(occ);
422            let (key, world) = match poses.get(occ) {
423                Some(world) => (occ, world),
424                None => match poses.get(top) {
425                    Some(world) => (top, world),
426                    None => return IDENTITY,
427                },
428            };
429            match self.occurrence_document_matrix(key) {
430                Some(document) => mat_mul(world, &rigid_inverse(&document)),
431                None => IDENTITY,
432            }
433        };
434        let mut posed: Vec<(&str, [f64; 16], Aabb, &[String])> = Vec::new();
435        for (occ, solids) in participants {
436            let delta = delta_of(occ);
437            let mut bbox = Aabb::empty();
438            for name in solids {
439                if let Some(solid) = display_of(name) {
440                    bbox.union(&posed_bbox(&solid.bbox, &delta));
441                }
442            }
443            if !bbox.is_empty() {
444                posed.push((occ.as_str(), delta, bbox, solids.as_slice()));
445            }
446        }
447        let same_as_previous = |occ: &str, prev: &BakedFrame| {
448            let top = occ.split(':').next().unwrap_or(occ);
449            poses.get(occ) == prev.poses.get(occ) && poses.get(top) == prev.poses.get(top)
450        };
451        let mut clashes = Vec::new();
452        for i in 0..posed.len() {
453            for j in i + 1..posed.len() {
454                if !overlaps(&posed[i].2, &posed[j].2) {
455                    continue;
456                }
457                let pair = (posed[i].0.to_string(), posed[j].0.to_string());
458                if let Some(prev) = previous {
459                    if same_as_previous(&pair.0, prev) && same_as_previous(&pair.1, prev) {
460                        if prev.clashes.contains(&pair) {
461                            clashes.push(pair);
462                        }
463                        continue;
464                    }
465                }
466                let hit = posed[i].3.iter().filter_map(display_of).any(|a| posed[j].3.iter().filter_map(display_of).any(|b| displays_pierce(a, &posed[i].1, b, &posed[j].1)));
467                if hit {
468                    clashes.push(pair);
469                }
470            }
471        }
472        clashes
473    }
474
475    /// Show the wanted frame if it is baked and not already shown.
476    fn simulation_show_wanted(&mut self) {
477        let Some(play) = self.simulation_play.as_ref() else { return };
478        let Some(wanted) = play.wanted else { return };
479        if wanted >= play.frames.len() || play.shown == Some(wanted) {
480            return;
481        }
482        self.simulation_pose_frame(wanted);
483    }
484
485    /// Where every moved occurrence sits at frame `index` (row-major world
486    /// matrices): the solve's poses, plus an explode clip's steps — its view's
487    /// enabled steps, each `fraction` of the way at the frame's progress (the
488    /// steps below the progress whole, the one at it partly), translating
489    /// their target occurrences on top of the solve. `None` before the frame
490    /// is baked.
491    pub(crate) fn simulation_frame_worlds(&self, index: usize) -> Option<BTreeMap<String, [f64; 16]>> {
492        let play = self.simulation_play.as_ref()?;
493        let frame = play.frames.get(index)?;
494        let mut worlds = frame.poses.clone();
495        let time = play.baked_study.frame_time(index);
496        let base = &play.base;
497        let sample = play.baked_study.sample(time, &|id| base.get(id).copied());
498        for explode in &sample.explode {
499            let Some(view) = self.exploded_views().into_iter().find(|view| view.id == explode.view) else { continue };
500            let steps: Vec<_> = view.steps.iter().filter(|step| step.enabled).collect();
501            let count = steps.len() as f64;
502            for (k, step) in steps.iter().enumerate() {
503                let fraction = (explode.progress * count - k as f64).clamp(0.0, 1.0);
504                if fraction <= 0.0 {
505                    continue;
506                }
507                for target in &step.targets {
508                    let Some(world) = worlds.get(target).copied().or_else(|| self.occurrence_document_matrix(target)) else { continue };
509                    let mut shift = IDENTITY;
510                    for axis in 0..3 {
511                        shift[axis * 4 + 3] = step.translate[axis] * fraction;
512                    }
513                    worlds.insert(target.clone(), mat_mul(&shift, &world));
514                }
515            }
516        }
517        Some(worlds)
518    }
519
520    /// Pose the displays at frame `index`, touching only the occurrences
521    /// whose pose differs from what they show; then the frame's clips (hidden
522    /// occurrences, the camera) and the clash tint.
523    fn simulation_pose_frame(&mut self, index: usize) {
524        let Some(play) = self.simulation_play.as_ref() else { return };
525        if index >= play.frames.len() {
526            return;
527        }
528        let time = play.baked_study.frame_time(index);
529        let base = play.base.clone();
530        let sample = play.baked_study.sample(time, &|id| base.get(id).copied());
531        let Some(worlds) = self.simulation_frame_worlds(index) else { return };
532        let Some(play) = self.simulation_play.as_ref() else { return };
533        let frame = worlds;
534        // Occurrences posed last time and absent from this frame go back.
535        let gone: Vec<String> = play.applied.keys().filter(|id| !frame.contains_key(*id)).cloned().collect();
536        self.simulation_unsection();
537        let Some(_) = self.simulation_play.as_ref() else { return };
538        let mut changed = false;
539        for id in gone {
540            self.simulation_pose_occurrence(&id, None);
541            changed = true;
542        }
543        for (id, world) in &frame {
544            let Some(document) = self.occurrence_document_matrix(id) else { continue };
545            let shown = self.simulation_play.as_ref().and_then(|play| play.applied.get(id).copied()).unwrap_or(document);
546            if same_matrix(&shown, world) {
547                continue;
548            }
549            if same_matrix(world, &document) {
550                // Back at the document pose: the originals, not an identity pose.
551                self.simulation_pose_occurrence(id, None);
552            } else {
553                let delta = mat_mul(world, &rigid_inverse(&document));
554                self.simulation_pose_occurrence(id, Some((delta, *world)));
555            }
556            changed = true;
557        }
558        if let Some(play) = self.simulation_play.as_mut() {
559            play.shown = Some(index);
560        }
561        if changed {
562            self.dirty = true;
563        }
564        self.simulation_apply_section(sample.section.as_ref());
565        self.simulation_tint_clashes(index);
566        self.simulation_apply_hidden(&sample.hidden);
567        self.simulation_apply_opacity(&sample.opacity);
568        if let Some(camera) = &sample.camera {
569            self.simulation_apply_camera(&camera.from, &camera.to, camera.t);
570        }
571        if let Some(play) = self.simulation_play.as_mut() {
572            play.shown_sample = Some(sample);
573        }
574    }
575
576    /// The solids the last frame's section cut or hid go back to their
577    /// originals and, where their occurrence is posed, are posed again, so
578    /// this frame's section (or none) starts from whole geometry.
579    fn simulation_unsection(&mut self) {
580        let Some(play) = self.simulation_play.as_mut() else { return };
581        let sectioned = std::mem::take(&mut play.sectioned);
582        if sectioned.is_empty() {
583            return;
584        }
585        let applied: Vec<(String, [f64; 16])> = play.applied.iter().map(|(id, world)| (id.clone(), *world)).collect();
586        let mut reposed: Vec<String> = Vec::new();
587        for name in &sectioned {
588            if let (Some(original), Some(display)) = (play.originals.get(name), self.scene.solid_mut(name)) {
589                *display = original.clone();
590            }
591            // The longest posed occurrence this solid belongs to.
592            if let Some((id, _)) = applied.iter().filter(|(id, _)| name.starts_with(&format!("{id}:"))).max_by_key(|(id, _)| id.len()) {
593                if !reposed.contains(id) {
594                    reposed.push(id.clone());
595                }
596            }
597        }
598        for id in reposed {
599            let Some(world) = applied.iter().find(|(key, _)| *key == id).map(|(_, world)| *world) else { continue };
600            let Some(document) = self.occurrence_document_matrix(&id) else { continue };
601            self.simulation_pose_occurrence(&id, Some((mat_mul(&world, &rigid_inverse(&document)), world)));
602        }
603        self.dirty = true;
604    }
605
606    /// Cut the displays on the PMI view's section planes, moved `offset`
607    /// along their normals: a solid wholly on the removed side is hidden, one
608    /// the planes cross is clipped and capped, one the view's section
609    /// excludes stays whole. Nothing with no section.
610    fn simulation_apply_section(&mut self, section: Option<&SectionSample>) {
611        let Some(section) = section else { return };
612        let state = self.pmi_state_shared();
613        let Some(view) = state.find_view(&section.view) else { return };
614        let report = self.pmi_report.as_ref().and_then(|report| report.view(&section.view));
615        let planes: Vec<([f64; 3], [f64; 3])> = view
616            .section_planes_in(report)
617            .into_iter()
618            .map(|(point, normal)| (std::array::from_fn(|i| point[i] + normal[i] * section.offset), normal))
619            .collect();
620        if planes.is_empty() {
621            return;
622        }
623        let exclude = view.display.section.clone();
624        let names: Vec<(String, Side)> = self
625            .scene
626            .solids()
627            .iter()
628            .filter(|solid| solid.visible)
629            .map(|solid| (solid.name.clone(), if exclude.as_ref().is_some_and(|cut| cut.excludes(&solid.name)) { Side::Kept } else { side_of_all(solid, &planes) }))
630            .collect();
631        let mut sectioned = Vec::new();
632        for (name, side) in names {
633            if side == Side::Kept {
634                continue;
635            }
636            let Some(display) = self.scene.solid(&name).cloned() else { continue };
637            if let Some(play) = self.simulation_play.as_mut() {
638                play.originals.entry(name.clone()).or_insert(display);
639            }
640            if let Some(display) = self.scene.solid_mut(&name) {
641                match side {
642                    Side::Removed => display.visible = false,
643                    Side::Cut => clip_display_all(display, &planes),
644                    Side::Kept => {}
645                }
646                display.revision = crate::scene::next_revision();
647            }
648            sectioned.push(name);
649        }
650        if let Some(play) = self.simulation_play.as_mut() {
651            play.sectioned = sectioned;
652        }
653        self.dirty = true;
654    }
655
656    /// Set the opacity of the solids a transparency clip names at this frame
657    /// and give the last frame's see-through solids their original back.
658    fn simulation_apply_opacity(&mut self, opacity: &BTreeMap<String, f64>) {
659        let mut want: Vec<(String, f32)> = Vec::new();
660        for (id, value) in opacity {
661            for name in self.simulation_occurrence_solids(id) {
662                want.push((name, value.clamp(0.0, 1.0) as f32));
663            }
664        }
665        want.sort_by(|a, b| a.0.cmp(&b.0));
666        want.dedup_by(|a, b| a.0 == b.0);
667        let Some(play) = self.simulation_play.as_ref() else { return };
668        let previous = play.translucent.clone();
669        let mut changed = false;
670        for name in previous.iter().filter(|name| !want.iter().any(|(n, _)| n == *name)) {
671            let opacity = self.simulation_play.as_ref().and_then(|play| play.originals.get(name)).map(|original| original.opacity);
672            if let (Some(opacity), Some(display)) = (opacity, self.scene.solid_mut(name)) {
673                if display.opacity != opacity {
674                    display.opacity = opacity;
675                    display.revision = crate::scene::next_revision();
676                    changed = true;
677                }
678            }
679        }
680        for (name, value) in &want {
681            let Some(display) = self.scene.solid(name).cloned() else { continue };
682            if let Some(play) = self.simulation_play.as_mut() {
683                play.originals.entry(name.clone()).or_insert(display);
684            }
685            if let Some(display) = self.scene.solid_mut(name) {
686                if display.opacity != Some(*value) {
687                    display.opacity = Some(*value);
688                    display.revision = crate::scene::next_revision();
689                    changed = true;
690                }
691            }
692        }
693        if let Some(play) = self.simulation_play.as_mut() {
694            play.translucent = want.into_iter().map(|(name, _)| name).collect();
695        }
696        if changed {
697            self.dirty = true;
698        }
699    }
700
701    /// The solids of occurrence `id`: a nested occurrence's by name prefix, a
702    /// top component's members.
703    fn simulation_occurrence_solids(&self, id: &str) -> Vec<String> {
704        if id.contains(':') {
705            let prefix = format!("{id}:");
706            self.scene.solids().iter().filter(|solid| solid.name.starts_with(&prefix)).map(|solid| solid.name.clone()).collect()
707        } else {
708            self.member_solid_names(id)
709        }
710    }
711
712    /// Hide the solids of the frame's visibility clips and show again the
713    /// ones hidden for the last frame that no clip hides now (from their
714    /// originals, so a solid the document hides stays hidden).
715    fn simulation_apply_hidden(&mut self, occurrences: &[String]) {
716        let mut want: Vec<String> = occurrences.iter().flat_map(|id| self.simulation_occurrence_solids(id)).collect();
717        want.sort();
718        want.dedup();
719        let Some(play) = self.simulation_play.as_ref() else { return };
720        let previous = play.hidden.clone();
721        let mut changed = false;
722        for name in previous.iter().filter(|name| !want.contains(name)) {
723            let visible = self.simulation_play.as_ref().and_then(|play| play.originals.get(name)).map(|original| original.visible);
724            if let (Some(visible), Some(display)) = (visible, self.scene.solid_mut(name)) {
725                if display.visible != visible {
726                    display.visible = visible;
727                    changed = true;
728                }
729            }
730        }
731        for name in &want {
732            let Some(display) = self.scene.solid(name).cloned() else { continue };
733            if let Some(play) = self.simulation_play.as_mut() {
734                play.originals.entry(name.clone()).or_insert(display);
735            }
736            if let Some(display) = self.scene.solid_mut(name) {
737                if display.visible {
738                    display.visible = false;
739                    changed = true;
740                }
741            }
742        }
743        if let Some(play) = self.simulation_play.as_mut() {
744            play.hidden = want;
745        }
746        if changed {
747            self.dirty = true;
748        }
749    }
750
751    /// Put the camera `t` of the way from PMI view `from`'s camera to view
752    /// `to`'s (eye, target, up and the projection's scale blended; the
753    /// projection kind switches half way), keeping the camera as it stood
754    /// before the first such frame.
755    fn simulation_apply_camera(&mut self, from: &str, to: &str, t: f64) {
756        let Some(camera) = self.simulation_camera_between(from, to, t) else { return };
757        let standing = self.snapshot_camera();
758        if let Some(play) = self.simulation_play.as_mut() {
759            if play.camera_before.is_none() {
760                play.camera_before = Some(standing);
761            }
762        }
763        self.simulation_apply_pmi_camera(&camera);
764    }
765
766    /// The camera `t` of the way from PMI view `from`'s camera to view `to`'s
767    /// (eye, target, up and the projection's scale blended; the projection
768    /// kind switches half way); `None` when either view has no camera.
769    pub(crate) fn simulation_camera_between(&self, from: &str, to: &str, t: f64) -> Option<PmiCamera> {
770        let state = self.pmi_state_shared();
771        let a = state.find_view(from).and_then(|v| v.camera.clone())?;
772        let b = state.find_view(to).and_then(|v| v.camera.clone())?;
773        let t = t.clamp(0.0, 1.0);
774        let lerp = |p: [f64; 3], q: [f64; 3]| -> [f64; 3] { std::array::from_fn(|i| p[i] + (q[i] - p[i]) * t) };
775        let scale_of = |camera: &PmiCamera| match camera.projection {
776            PmiProjection::Orthographic { half_height } => half_height,
777            PmiProjection::Perspective { fov_y_deg } => fov_y_deg,
778        };
779        let orthographic = |camera: &PmiCamera| matches!(camera.projection, PmiProjection::Orthographic { .. });
780        let same_kind = orthographic(&a) == orthographic(&b);
781        let (ortho, scale) = if same_kind {
782            (orthographic(&a), scale_of(&a) + (scale_of(&b) - scale_of(&a)) * t)
783        } else if t < 0.5 {
784            (orthographic(&a), scale_of(&a))
785        } else {
786            (orthographic(&b), scale_of(&b))
787        };
788        Some(PmiCamera {
789            eye: lerp(a.eye, b.eye),
790            target: lerp(a.target, b.target),
791            up: lerp(a.up, b.up),
792            projection: if ortho { PmiProjection::Orthographic { half_height: scale } } else { PmiProjection::Perspective { fov_y_deg: scale } },
793            viewport: a.viewport,
794        })
795    }
796
797    /// Apply a PMI camera record as the live camera.
798    fn simulation_apply_pmi_camera(&mut self, camera: &PmiCamera) {
799        let (kind, scale) = match camera.projection {
800            PmiProjection::Orthographic { half_height } => ("orthographic", half_height),
801            PmiProjection::Perspective { fov_y_deg } => ("perspective", fov_y_deg),
802        };
803        let json = json!({ "kind": kind, "eye": camera.eye, "target": camera.target, "up": camera.up, "scale": scale }).to_string();
804        if self.apply_camera_state_json(&json).is_ok() {
805            self.controls_sync_after_camera_apply();
806        }
807    }
808
809    /// Tint the displays of the occurrences that clash at frame `index`, and
810    /// give back their colour to the ones tinted for the last frame that no
811    /// longer clash. Runs after the frame's posing (a re-posed display is
812    /// rebuilt from its original, which holds the colour the document gave it).
813    fn simulation_tint_clashes(&mut self, index: usize) {
814        let Some(play) = self.simulation_play.as_ref() else { return };
815        let Some(frame) = play.frames.get(index) else { return };
816        let mut want: Vec<String> = Vec::new();
817        for (a, b) in &frame.clashes {
818            for occ in [a, b] {
819                if let Some((_, solids)) = play.participants.iter().find(|(id, _)| id == occ) {
820                    want.extend(solids.iter().cloned());
821                }
822            }
823        }
824        want.sort();
825        want.dedup();
826        let previous = play.tinted.clone();
827        let mut changed = false;
828        for name in previous.iter().filter(|name| !want.contains(name)) {
829            let color = self.simulation_play.as_ref().and_then(|play| play.originals.get(name)).map(|original| original.color_override);
830            if let (Some(color), Some(display)) = (color, self.scene.solid_mut(name)) {
831                if display.color_override != color {
832                    display.color_override = color;
833                    display.revision = crate::scene::next_revision();
834                    changed = true;
835                }
836            }
837        }
838        for name in &want {
839            // The original is kept before the tint: an unmoved occurrence may
840            // not have been posed, so nothing recorded it yet.
841            let Some(display) = self.scene.solid(name).cloned() else { continue };
842            if let Some(play) = self.simulation_play.as_mut() {
843                play.originals.entry(name.clone()).or_insert(display);
844            }
845            if let Some(display) = self.scene.solid_mut(name) {
846                if display.color_override != Some(CLASH_TINT) {
847                    display.color_override = Some(CLASH_TINT);
848                    // The renderer re-derives a style on a new revision only.
849                    display.revision = crate::scene::next_revision();
850                    changed = true;
851                }
852            }
853        }
854        if let Some(play) = self.simulation_play.as_mut() {
855            play.tinted = want;
856        }
857        if changed {
858            self.dirty = true;
859        }
860    }
861
862    /// Pose occurrence `id`'s displays by `delta` over their originals (and
863    /// record the `world` pose they then show), or put them back (`None`).
864    /// A top component's pass re-poses the solids of its nested occurrences
865    /// too, so those are forgotten and posed again after it (they follow it
866    /// in a frame's map).
867    fn simulation_pose_occurrence(&mut self, id: &str, pose: Option<([f64; 16], [f64; 16])>) {
868        let names: Vec<String> = if id.contains(':') {
869            let prefix = format!("{id}:");
870            self.scene.solids().iter().filter(|solid| solid.name.starts_with(&prefix)).map(|solid| solid.name.clone()).collect()
871        } else {
872            self.member_solid_names(id)
873        };
874        let Some(play) = self.simulation_play.as_mut() else { return };
875        for name in names {
876            let Some(display) = self.scene.solid(&name) else { continue };
877            let original = play.originals.entry(name.clone()).or_insert_with(|| display.clone()).clone();
878            if let Some(display) = self.scene.solid_mut(&name) {
879                *display = original;
880                if let Some((delta, _)) = &pose {
881                    pose_display_by_matrix(display, delta);
882                }
883            }
884        }
885        let nested = format!("{id}:");
886        play.applied.retain(|key, _| !key.starts_with(&nested));
887        match pose {
888            Some((_, world)) => {
889                play.applied.insert(id.to_string(), world);
890            }
891            None => {
892                play.applied.remove(id);
893            }
894        }
895    }
896
897    /// Where occurrence `id`'s displays sit in the document: a top
898    /// component's solved pose, or that composed with a nested occurrence's
899    /// solved pose inside it (row-major 4×4).
900    pub(super) fn occurrence_document_matrix(&self, id: &str) -> Option<[f64; 16]> {
901        let (top, rest) = match id.split_once(':') {
902            Some((top, rest)) => (top, Some(rest)),
903            None => (id, None),
904        };
905        let record = self.assembly_components().iter().find(|record| record.id == top)?;
906        match rest {
907            None => Some(record.transform),
908            Some(rest) => Some(mat_mul(&record.transform, record.nested_poses.get(rest)?)),
909        }
910    }
911
912    /// Every posed display back exactly; the bake and the playhead are kept,
913    /// and the shown frame is asked for again (a run that rebuilds the
914    /// displays re-poses it; a stop forgets it).
915    pub(crate) fn simulation_restore_displays(&mut self) {
916        let Some(play) = self.simulation_play.as_mut() else { return };
917        play.applied.clear();
918        play.tinted.clear();
919        play.hidden.clear();
920        play.translucent.clear();
921        play.sectioned.clear();
922        play.shown_sample = None;
923        let camera_before = play.camera_before.take();
924        let originals = std::mem::take(&mut play.originals);
925        if let Some(camera) = camera_before {
926            self.simulation_apply_pmi_camera(&camera);
927        }
928        let Some(play) = self.simulation_play.as_mut() else { return };
929        if let Some(shown) = play.shown.take() {
930            play.wanted.get_or_insert(shown);
931        }
932        if originals.is_empty() {
933            return;
934        }
935        for (name, original) in originals {
936            if let Some(display) = self.scene.solid_mut(&name) {
937                *display = original;
938            }
939        }
940        self.dirty = true;
941    }
942
943    /// Post-apply tail: the displays are fresh (un-posed before the
944    /// reconcile), so the frame that was shown goes back on them when the
945    /// bake is still current; a moved document re-bakes on the next tick.
946    pub(crate) fn simulation_after_apply(&mut self) {
947        let Some(play) = self.simulation_play.as_ref() else { return };
948        if play.revision == self.history.revision() {
949            self.simulation_show_wanted();
950        }
951    }
952
953    /// Forget the playback entirely (displays restored): the document closed
954    /// or the workbench left.
955    pub fn simulation_forget_playback(&mut self) {
956        self.simulation_restore_displays();
957        self.simulation_play = None;
958    }
959
960    /// What automation and the pane read (`__brepSimulation.playback`):
961    /// `{study, time, playheadFrame, shown, baked, total, playing, looping,
962    /// failed: [frame…], error, poses: {occurrence: {translate,
963    /// rotateEulerDeg}}, interference, clashes: [frame…], shownClashes:
964    /// [[a, b]…], hidden: [occurrence…], explode: [{view, progress}…],
965    /// camera: {from, to, t} | null, cameraHeld, opacity: {occurrence:
966    /// value}, section: {view, offset} | null}` — `poses` are the
967    /// occurrences the shown frame moved from their document poses (explode
968    /// clips included), `clashes` the baked frames where parts interfere,
969    /// `shownClashes` the pairs at the shown frame, and `hidden`, `explode`
970    /// and `camera` the shown frame's clips (`cameraHeld`: a camera clip has
971    /// taken the camera, which Stop gives back); `null` with no playback.
972    pub fn simulation_playback_json(&self) -> Value {
973        let Some(play) = self.simulation_play.as_ref() else { return Value::Null };
974        let failed: Vec<usize> = play.frames.iter().enumerate().filter(|(_, frame)| frame.failed).map(|(index, _)| index).collect();
975        let poses: BTreeMap<&str, Value> = play
976            .applied
977            .iter()
978            .map(|(id, world)| (id.as_str(), brep_kernel::transform_to_pose_params(&brep_kernel::AffineTransform { elements: *world })))
979            .collect();
980        json!({
981            "study": play.study,
982            "time": play.time,
983            "playheadFrame": play.baked_study.frame_at(play.time),
984            "shown": play.shown,
985            "baked": play.frames.len(),
986            "total": play.total,
987            "playing": play.playing,
988            "looping": play.looping,
989            "failed": failed,
990            "error": play.error,
991            "poses": poses,
992            "interference": play.baked_study.interference.enabled,
993            "clashes": play.frames.iter().enumerate().filter(|(_, frame)| !frame.clashes.is_empty()).map(|(index, _)| index).collect::<Vec<usize>>(),
994            "shownClashes": play.shown.and_then(|index| play.frames.get(index)).map(|frame| frame.clashes.clone()).unwrap_or_default(),
995            "hidden": play.shown_sample.as_ref().map(|sample| sample.hidden.clone()).unwrap_or_default(),
996            "explode": play.shown_sample.as_ref().map(|sample| sample.explode.iter().map(|e| json!({ "view": e.view, "progress": e.progress })).collect::<Vec<Value>>()).unwrap_or_default(),
997            "camera": play.shown_sample.as_ref().and_then(|sample| sample.camera.as_ref()).map(|c| json!({ "from": c.from, "to": c.to, "t": c.t })),
998            "cameraHeld": play.camera_before.is_some(),
999            "opacity": play.shown_sample.as_ref().map(|sample| sample.opacity.clone()).unwrap_or_default(),
1000            "section": play.shown_sample.as_ref().and_then(|sample| sample.section.as_ref()).map(|s| json!({ "view": s.view, "offset": s.offset })),
1001        })
1002    }
1003}
1004
1005/// `a · b`, row-major 4×4.
1006pub(super) use crate::geometry3d::mat4_mul_row_major as mat_mul;
1007
1008/// The inverse of a rigid row-major 4×4: `[Rᵀ | −Rᵀ·t]`.
1009pub(super) use crate::geometry3d::mat4_rigid_inverse as rigid_inverse;
1010
1011/// Two poses within roundoff of each other.
1012pub(super) fn same_matrix(a: &[f64; 16], b: &[f64; 16]) -> bool {
1013    a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-9)
1014}
1015
1016/// `a · b`, column-major 4×4 (`SolidDisplay::pose`'s spelling).
1017use crate::view::mat4_mul_column_major;
1018
1019/// Move a display rigidly by the row-major `m`: the renderer draws the
1020/// buffers it holds for the shape through the matrix (`pose`, over any pose
1021/// already on it), and the positions, normals, edge polylines, vertices and
1022/// box follow for everything that reads them (picking, sheets, exports).
1023fn pose_display_by_matrix(display: &mut SolidDisplay, m: &[f64; 16]) {
1024    let column_major: [f32; 16] = std::array::from_fn(|k| {
1025        let (col, row) = (k / 4, k % 4);
1026        m[row * 4 + col] as f32
1027    });
1028    display.pose = if display.shape_revision == 0 {
1029        Some(column_major)
1030    } else {
1031        display.pose.map(|before| mat4_mul_column_major(&column_major, &before))
1032    };
1033    if display.shape_revision == 0 {
1034        display.shape_revision = display.revision;
1035    }
1036    display.revision = crate::scene::next_revision();
1037    let point = |p: [f64; 3]| -> [f64; 3] {
1038        std::array::from_fn(|i| m[i * 4] * p[0] + m[i * 4 + 1] * p[1] + m[i * 4 + 2] * p[2] + m[i * 4 + 3])
1039    };
1040    let vector = |v: [f64; 3]| -> [f64; 3] { std::array::from_fn(|i| m[i * 4] * v[0] + m[i * 4 + 1] * v[1] + m[i * 4 + 2] * v[2]) };
1041    let mut bbox = crate::camera::Aabb::empty();
1042    for position in &mut display.mesh.positions {
1043        let posed = point(position.map(f64::from));
1044        *position = posed.map(|v| v as f32);
1045        bbox.expand(posed);
1046    }
1047    for normal in &mut display.mesh.normals {
1048        let rotated = vector(normal.map(f64::from));
1049        let length = rotated.iter().map(|v| v * v).sum::<f64>().sqrt().max(1e-20);
1050        *normal = rotated.map(|v| (v / length) as f32);
1051    }
1052    for edge in &mut display.edges {
1053        for p in &mut edge.polyline {
1054            let posed = point(p.map(f64::from));
1055            *p = posed.map(|v| v as f32);
1056            bbox.expand(posed);
1057        }
1058    }
1059    for vertex in &mut display.vertices {
1060        vertex.position = point(vertex.position);
1061        bbox.expand(vertex.position);
1062    }
1063    if !bbox.is_empty() {
1064        display.bbox = bbox;
1065    }
1066}