diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index e9832fdb7..8fa1512ee 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -57,6 +57,9 @@ pub struct ModelBody { bytes: usize, /// In a world state: the [`ModelBody::geometry_key`] of the model body this one places (0: none). source_key: u64, + /// [`Body::outline_bounds`] of `body` (with the body it was measured on), worked out once + /// and shared by clones. + outline: Arc>, } impl ModelBody { @@ -79,6 +82,16 @@ impl ModelBody { imported: None, bytes: 0, source_key: 0, + outline: Arc::new(OnceLock::new()), + } + } + + /// A box around the body without meshing it ([`Body::outline_bounds`]), worked out once. + pub fn outline_bounds(&self) -> solidcraft_geom::Aabb3 { + match self.outline.get_or_init(|| (self.body.clone(), self.body.outline_bounds())) { + (measured, b) if measured.same(&self.body) => *b, + // The body was replaced in this cell's holder since: measure it again. + _ => self.body.outline_bounds(), } } diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 5e3c19a28..4ce7ec792 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -110,10 +110,21 @@ pub fn bounds(s: &Session) -> Aabb3 { /// [`bounds`], with the browser's Sketches folder shown (`sketches`) or hidden. pub fn visible_bounds(s: &Session, sketches: bool) -> Aabb3 { + bounds_by(s, sketches, |body| body.mesh().bounds()) +} + +/// [`visible_bounds`] without meshing anything: a body not meshed yet counts with its outline +/// ([`solidcraft_kernel::Body::outline_bounds`]), which a face curving out past all of its edges +/// can exceed. Frames a design whose bodies are still being meshed. +pub fn unmeshed_bounds(s: &Session, sketches: bool) -> Aabb3 { + bounds_by(s, sketches, |body| body.cached_mesh().map(|m| m.bounds()).unwrap_or_else(|| body.outline_bounds())) +} + +fn bounds_by(s: &Session, sketches: bool, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> Aabb3 { let st = s.world_state(); let mut b = Aabb3::EMPTY; for body in st.bodies.iter().filter(|x| s.body_visible(&x.name)) { - b = b.union(&body.mesh().bounds()); + b = b.union(&of(body)); } for ss in st.sketches.iter().filter(|x| sketch_drawn(s, x.feature, sketches)) { // All four corners: on a tilted plane two opposite ones don't span the rectangle. diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 33db86eeb..5b082e649 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -1077,6 +1077,52 @@ impl Body { if d.is_finite() && d > 0.0 { d } else { 1.0 } } + /// A box around the body worked out without meshing it: its vertices and its edges' control + /// points (a spline lies in the hull of its controls; a face's surface does not count, as an + /// imported face is often trimmed from a far larger one). A face curving out beyond all of + /// its edges (a dome on a circle) can reach past it, so it frames a view while the body is + /// still being meshed; [`Mesh::bounds`] is the exact one. + /// A mesh body's box is its triangles'. + pub fn outline_bounds(&self) -> solidcraft_geom::Aabb3 { + crate::guard("outline bounds", || Ok(self.outline_bounds_unguarded())).unwrap_or(solidcraft_geom::Aabb3::EMPTY) + } + + fn outline_bounds_unguarded(&self) -> solidcraft_geom::Aabb3 { + use mt::BoundedCurve; + let mut b = solidcraft_geom::Aabb3::EMPTY; + if let Some(m) = &self.mesh { + for p in &m.positions { + b.add(*p); + } + return b; + } + let homogeneous = |b: &mut solidcraft_geom::Aabb3, v: mt::Vector4| { + if v.w > 0.0 { + b.add(Vec3::new(v.x / v.w, v.y / v.w, v.z / v.w)); + } + }; + for v in self.solid.vertex_iter() { + b.add(from_p3(v.point())); + } + for e in self.solid.edge_iter() { + match e.curve() { + mt::Curve::Line(l) => { + b.add(from_p3(l.0)); + b.add(from_p3(l.1)); + } + mt::Curve::BSplineCurve(c) => c.control_points().iter().for_each(|p| b.add(from_p3(*p))), + mt::Curve::NurbsCurve(c) => c.control_points().iter().for_each(|p| homogeneous(&mut b, *p)), + mt::Curve::IntersectionCurve(c) => { + let (t0, t1) = c.range_tuple(); + for i in 0..=8 { + b.add(from_p3(mt::ParametricCurve::subs(&e.curve(), t0 + (t1 - t0) * f64::from(i) / 8.0))); + } + } + } + } + b + } + /// The body's volume from a mesh at `tol`, measured once per (solid, tolerance): clones of /// a body share the measurement, so an operand a later boolean takes again is not meshed /// twice for the same number. `None` when the body cannot be meshed. diff --git a/crates/kernel/src/display_mesh_tests.rs b/crates/kernel/src/display_mesh_tests.rs index ca5d94a41..c1cf7d45a 100644 --- a/crates/kernel/src/display_mesh_tests.rs +++ b/crates/kernel/src/display_mesh_tests.rs @@ -389,3 +389,24 @@ fn a_cylinder_wall_split_along_its_seam_meshes_round() { } } } + +/// A body's outline box, made without meshing, holds its display mesh and is not much larger. +#[test] +fn outline_bounds_hold_the_display_mesh() { + let cube = crate::box_solid(Vec3::ZERO, Vec3::new(40., 30., 10.)).unwrap(); + let rounded = crate::fillet(&cube, &[Vec3::new(20., 0., 10.)], 3.).unwrap(); + let rod = crate::cylinder(Vec3::new(5., 5., 0.), Vec3::Z, 4., 25.).unwrap(); + for body in [cube, rounded, rod] { + let outline = body.outline_bounds(); + let mesh = body.reference_display_mesh_angular(body.size() * 1e-3, crate::DISPLAY_ANGLE).unwrap().bounds(); + let slack = body.size() * 1e-6; + for (lo, hi, m_lo, m_hi) in [ + (outline.min.x, outline.max.x, mesh.min.x, mesh.max.x), + (outline.min.y, outline.max.y, mesh.min.y, mesh.max.y), + (outline.min.z, outline.max.z, mesh.min.z, mesh.max.z), + ] { + assert!(lo <= m_lo + slack && hi >= m_hi - slack, "outline {outline:?} holds the mesh {mesh:?}"); + } + assert!(outline.diagonal() <= mesh.diagonal() * 1.5, "and is not much larger"); + } +} diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index a66472230..bff9b92c6 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -737,13 +737,14 @@ fn compute( phase.store(1, Ordering::Relaxed); let world = session.world_state(); let placement_ms = view_began.elapsed().as_secs_f64() * 1000.0; - let mesh_began = std::time::Instant::now(); - // Fit, picking and the first viewport frame must not trigger cold tessellation on the UI. - world.warm_meshes(|| !progress.is_cancelled()); - if progress.is_cancelled() { - return cancelled(); - } - let tessellation_ms = mesh_began.elapsed().as_secs_f64() * 1000.0; + // The display meshes are made once the design is in the window, which shows its bodies as + // they come ([`crate::open_meshing`]): framing, picking and drawing never mesh on the UI. + // Its outlines frame it in the window until it is meshed: measured here, not there. + solidcraft_engine::kernel::for_each_on_threads(&world.bodies, 16, |b| { + let _ = b.outline_bounds(); + }); + drop(world); + let tessellation_ms = 0.0; phase.store(2, Ordering::Relaxed); let view_ms = view_began.elapsed().as_secs_f64() * 1000.0; if profile { @@ -794,6 +795,9 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { } _ if running.cancelled() => request.answer(Err("file operation cancelled".into())), Ok(made) if running.matches(&app.session) => { + // Not meshed yet: framing it while it goes in must not mesh it here. + app.open_meshing_next = true; + crate::frame_watch::step(app, "before the open"); if request.insert() { app.session.accept_computed(made.session); app.big_operation = true; @@ -801,17 +805,19 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { crate::documents::adopt(app, made.session); if request.kind == Kind::Open { app.home.add_recent(&request.path); - if made.thumbnail { - crate::home::remember_source(&mut app.home, &app.session, &request.path); - } } } app.home.open = false; - app.fit_view(); + crate::frame_watch::step(app, "adopt the design"); + // Shown as its bodies are meshed, framed from their outlines meanwhile; its Home + // picture is drawn once they all are. + crate::open_meshing::start(app, (request.kind == Kind::Open && made.thumbnail).then(|| request.path.clone())); + crate::frame_watch::step(app, "start meshing and frame"); // A caller that said which way is up has been answered: no offer to stand the part up. if (request.kind == Kind::Open || request.insert()) && !request.options.contains_key("up") { crate::stand_up::offer(app, &request.path, &running.before, Some(&made.result)); } + crate::frame_watch::step(app, "stand-up offer"); let warnings = made.result.get("warnings").and_then(Value::as_array); if let Kind::Recover { .. } = request.kind { recovered(app, request); @@ -855,6 +861,17 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { /// The light overlay over everything under the title bar while a file loads. The title bar, /// its window buttons and the window's resize edges stay live; the design underneath takes no /// pointer input until the file is in. +/// What a file operation under way is doing (for the frame watch), if one is. +pub(crate) fn phase(app: &SolveApp) -> Option<&'static str> { + let r = app.file_load.running.as_ref()?; + Some(match (r.staged.is_some(), r.phase.load(Ordering::Relaxed)) { + (true, 0) => "reading the file (staged)", + (_, 0) => "reading the file", + (_, 1) => "preparing the view", + _ => "finishing the open", + }) +} + pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let Some(r) = &app.file_load.running else { return }; let cancelled = r.cancelled(); diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs index c2d7635f5..d6aa945f0 100644 --- a/crates/ui-egui/src/file_load_ui_tests.rs +++ b/crates/ui-egui/src/file_load_ui_tests.rs @@ -211,7 +211,10 @@ fn a_control_open_answers_after_loading_without_freezing_the_window() { assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"], expected); assert!(count_rx.try_recv().is_ok(), "inspection answered while the file loaded"); - // Its Home picture is drawn after it opened, not before. + // Its bodies are meshed after it opened, and its Home picture drawn then, off the UI thread. + while crate::open_meshing::active(&w.app) { + w.frame(vec![]); + } assert!(crate::home::remembering(&w.app.home), "the Home picture is drawn off the UI thread"); for _ in 0..3 { w.frame(vec![]); @@ -267,3 +270,153 @@ fn a_control_import_passes_up_and_names_on() { assert!(size[1] > 39.9 && !offered, "{size:?} {offered}"); let _ = std::fs::remove_dir_all(&dir); } + +/// An opened design is in the window before its bodies are meshed: the view draws the bodies +/// meshed so far (never meshing one itself), framed from their outlines, until all are. +#[test] +fn an_opened_design_shows_its_bodies_as_they_are_meshed() { + let dir = scratch("progressive"); + let path = large_design(&dir, 24); + let mut w = Win::new(); + let (tx, rx) = std::sync::mpsc::channel(); + w.app.control_rx = Some(rx); + let (open, open_rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": "doc.open", "params": {"path": path}})); + tx.send(open).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + while open_rx.try_recv().is_err() { + w.frame(vec![]); + std::thread::sleep(std::time::Duration::from_millis(1)); + assert!(std::time::Instant::now() < deadline, "the open answers"); + } + let mut seen = Vec::new(); + while crate::open_meshing::active(&w.app) { + let shown = crate::open_meshing::shown_world(&w.app); + assert!(shown.bodies.iter().all(|b| b.cached_mesh().is_some()), "only meshed bodies are drawn"); + let (done, total) = crate::open_meshing::progress(&w.app).unwrap(); + assert!(done <= total && total == w.app.session.world_state().bodies.len(), "Loading parts {done}/{total}"); + seen.push(shown.bodies.len()); + w.frame(vec![]); + } + assert!(seen.windows(2).all(|p| p[0] <= p[1]), "the picture only grows: {seen:?}"); + let world = w.app.session.world_state(); + // Then the whole design (in the order its bodies came, kept until the design changes). + let names = |st: &solidcraft_engine::doc::ModelState| { + let mut n: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); + n.sort(); + n + }; + assert_eq!(names(&crate::open_meshing::shown_world(&w.app)), names(&world), "then the whole design"); + assert!(world.bodies.iter().all(|b| b.cached_mesh().is_some())); + // Framed from the meshes now, as a synchronous open frames it. + let framed = w.app.cam; + w.app.fit_view(); + assert_eq!(w.app.cam, framed); + // An edit after that: the viewport draws the session's world again. + w.app.session.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "operation": "new"})).unwrap(); + w.frame(vec![]); + assert!(std::sync::Arc::ptr_eq(&crate::open_meshing::shown_world(&w.app), &w.app.session.world_state())); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A screenshot asked for right after an open shows the whole design: it waits for the meshing, +/// and what was asked after it waits for it. +#[test] +fn a_screenshot_after_an_open_waits_for_the_whole_design() { + let dir = scratch("progressive-shot"); + let path = large_design(&dir, 24); + let mut w = Win::new(); + let (tx, rx) = std::sync::mpsc::channel(); + w.app.control_rx = Some(rx); + let (open, open_rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": "doc.open", "params": {"path": path}})); + tx.send(open).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + while open_rx.try_recv().is_err() { + w.frame(vec![]); + std::thread::sleep(std::time::Duration::from_millis(1)); + assert!(std::time::Instant::now() < deadline, "the open answers"); + } + if !crate::open_meshing::active(&w.app) { + return; // Meshed already: nothing to wait for on this machine. + } + let (shot, _shot_rx) = crate::control::ControlRequest::new("ui.screenshot", json!({})); + let (count, count_rx) = crate::control::ControlRequest::new("document.inspect", json!({})); + tx.send(shot).unwrap(); + tx.send(count).unwrap(); + w.frame(vec![]); + if crate::open_meshing::active(&w.app) { + assert!(count_rx.try_recv().is_err(), "a request after the screenshot waits for it"); + } + while crate::open_meshing::active(&w.app) { + w.frame(vec![]); + } + for _ in 0..3 { + w.frame(vec![]); + } + assert!(count_rx.try_recv().is_ok(), "answered once the design is meshed"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An assembly of a few rounded parts placed many times, as a STEP file: an import that takes a +/// while to read, place and mesh. +fn step_assembly(dir: &std::path::Path) -> String { + let mut s = Session::default(); + // Distinct parts (each meshed on its own), each placed a few times (placed copies share it). + for k in 0..40 { + let len = 30.0 + k as f64; + let part = s.execute("component.create", &json!({"name": format!("Bracket {k}")})).unwrap()["component"].as_u64().unwrap(); + s.execute("solid.box", &json!({"length": len, "width": 20, "height": 8, "operation": "new"})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 6, "height": 20, "base": [10, 10, 0], "operation": "join"})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 2.5, "height": 40, "base": [len - 10.0, 10, -10], "operation": "cut"})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[len / 2.0, 0, 8]], "radius": 3})).unwrap(); + s.execute("solid.sphere", &json!({"radius": 4, "center": [10, 10, 24], "operation": "join"})).unwrap(); + s.execute("component.activate", &json!({"component": 0})).unwrap(); + for i in 1..5 { + s.execute("occurrence.copy", &json!({"component": part, "translate": [i as f64 * 80.0, k as f64 * 40.0, 0]})).unwrap(); + } + } + let path = dir.join("assembly.step").to_string_lossy().to_string(); + s.execute("file.export", &json!({"path": path})).unwrap(); + path +} + +/// Open `path` through the window as a person would, every frame timed, until it is in and meshed. +/// The slowest frame: ms and the phase it was in. +fn open_timed(path: &str) -> (Win, (f64, &'static str)) { + let mut w = Win::new(); + w.app.frame_watch.slowest = (0.0, "idle"); + let (tx, rx) = std::sync::mpsc::channel(); + w.app.control_rx = Some(rx); + let (open, open_rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": "doc.open", "params": {"path": path}})); + tx.send(open).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300); + let mut answered = false; + while !answered || crate::open_meshing::active(&w.app) || !w.app.file_load.idle() { + w.frame(vec![]); + answered |= open_rx.try_recv().is_ok(); + std::thread::sleep(std::time::Duration::from_millis(1)); + assert!(std::time::Instant::now() < deadline, "{path} opens"); + } + let slowest = w.app.frame_watch.slowest; + eprintln!("{path}: slowest frame {:.1} ms while {}, {} bodies", slowest.0, slowest.1, w.app.session.world_state().bodies.len()); + (w, slowest) +} + +/// The window stays responsive through every phase of opening a design: a STEP assembly imported, +/// the design saved with its model and opened again, and saved without it and opened again. No +/// frame on the window thread takes longer than 250 ms (the test names the phase that did). +#[test] +fn opening_a_large_design_never_stalls_the_window() { + const BUDGET_MS: f64 = 250.0; + let dir = scratch("watchdog"); + let step = step_assembly(&dir); + let (mut w, (ms, phase)) = open_timed(&step); + assert!(ms < BUDGET_MS, "STEP import: a {ms:.0} ms frame while {phase}"); + assert!(w.app.session.world_state().bodies.len() >= 200); + for (name, cache) in [("cached.solidcraft", true), ("plain.solidcraft", false)] { + let path = dir.join(name).to_string_lossy().to_string(); + w.app.session.execute("file.save_as", &json!({"path": path, "cache": cache})).unwrap(); + let (_, (ms, phase)) = open_timed(&path); + assert!(ms < BUDGET_MS, "{name}: a {ms:.0} ms frame while {phase}"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/frame_watch.rs b/crates/ui-egui/src/frame_watch.rs new file mode 100644 index 000000000..0c3e74231 --- /dev/null +++ b/crates/ui-egui/src/frame_watch.rs @@ -0,0 +1,62 @@ +//! How long the window thread spends on each frame, by what the app is doing (#3053): the window +//! must stay responsive through every phase of opening a design. `SOLIDCRAFT_PROFILE_FRAMES=1` +//! logs every frame slower than [`SLOW_MS`] with its phase; tests read [`Watch::slowest`]. + +use crate::SolveApp; + +/// A frame slower than this is logged (ms). +pub(crate) const SLOW_MS: f64 = 50.0; + +#[derive(Default)] +pub(crate) struct Watch { + began: Option, + phase: &'static str, + /// This frame's named steps so far, and when the last one ended (ms). + steps: Vec<(&'static str, f64)>, + last: f64, + /// The slowest frame so far: ms, and the phase it was in. + pub slowest: (f64, &'static str), +} + +/// What the app is doing this frame, as far as opening a design goes. +pub(crate) fn phase(app: &SolveApp) -> &'static str { + if let Some(p) = crate::file_load::phase(app) { + return p; + } + if crate::open_meshing::active(app) { "loading parts" } else { "idle" } +} + +/// The frame starts (before any of its work). +pub(crate) fn begin(app: &mut SolveApp) { + let now = crate::now_ms(); + app.frame_watch.began = Some(now); + app.frame_watch.last = now; + app.frame_watch.steps.clear(); + app.frame_watch.phase = phase(app); +} + +/// A named step of this frame's work ended: a slow frame is logged with them. +pub(crate) fn step(app: &mut SolveApp, name: &'static str) { + let now = crate::now_ms(); + let w = &mut app.frame_watch; + if w.began.is_some() && w.steps.len() < 32 { + w.steps.push((name, now - w.last)); + } + w.last = now; +} + +/// The frame's work is done. +pub(crate) fn end(app: &mut SolveApp) { + step(app, "the rest of the frame"); + let Some(began) = app.frame_watch.began.take() else { return }; + let ms = crate::now_ms() - began; + // The phase the frame started in names it (a frame that finishes an open did that work). + let phase = app.frame_watch.phase; + if ms > app.frame_watch.slowest.0 { + app.frame_watch.slowest = (ms, phase); + } + if ms > SLOW_MS && solidcraft_engine::geom::env::var_os("PROFILE_FRAMES").is_some() { + let steps: Vec = app.frame_watch.steps.iter().filter(|(_, t)| *t >= 1.0).map(|(n, t)| format!("{n} {t:.0}")).collect(); + eprintln!("SolidCraft slow frame: {ms:.0} ms ({phase}) [{}]", steps.join(", ")); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 60870c71f..5fbbe848a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -115,6 +115,7 @@ mod extrude_edit_tests; mod extrude_preview; mod file_load; mod file_picker; +pub(crate) mod frame_watch; #[cfg(test)] mod history_off_thread_tests; pub use file_picker::FilePickerFuture; @@ -130,6 +131,7 @@ mod file_load_ui_tests; #[cfg(test)] mod fillet_spline_handle_tests; pub(crate) mod navigation; +pub(crate) mod open_meshing; pub mod palette; pub mod params_dialog; pub(crate) mod pick_buffer; @@ -437,6 +439,12 @@ pub struct SolveApp { /// The 3D mouse: which device, its reading, and the calibration window. pub space_mouse: space_mouse::Input, pub file_load: file_load::FileLoad, + /// An opened design's bodies still being meshed, off the UI thread. + pub(crate) open_meshing: Option, + /// A design is being put in the window and will be meshed after it: framing it uses outlines. + pub(crate) open_meshing_next: bool, + /// How long each frame takes on the window thread, by phase. + pub(crate) frame_watch: frame_watch::Watch, /// The other open designs (tabs). pub docs: documents::Documents, /// The language the installed font fallback chain is ordered for (`fonts::fallback_order`); @@ -533,6 +541,9 @@ impl SolveApp { home: home::HomeState::default(), space_mouse: Default::default(), file_load: file_load::FileLoad::default(), + open_meshing: None, + open_meshing_next: false, + frame_watch: Default::default(), docs: documents::Documents::default(), applied_fonts_language: "en".into(), applied_ui_font: String::new(), @@ -1314,6 +1325,7 @@ impl SolveApp { /// Per-frame logic before layout. pub fn logic(&mut self, ctx: &egui::Context) { + frame_watch::begin(self); file_picker::tick(self, ctx); render_workspace::sync_backend(self); render_workspace::tick(self, ctx); @@ -1322,6 +1334,8 @@ impl SolveApp { if self.saving.is_some() { ctx.request_repaint_after(std::time::Duration::from_millis(16)); } + open_meshing::tick(self, ctx); + open_meshing::refresh(self, ctx.input(|i| i.time)); self.esc_handled = false; prefs::apply(self, ctx); if !self.styled || theme::is_dark() != self.ui.dark || theme::vision() != self.preferences.color_vision { @@ -1431,6 +1445,7 @@ impl SolveApp { ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); } self.frame_ms = now_ms() - t0; + frame_watch::end(self); } fn cad_ui(&mut self, ui: &mut egui::Ui, report_input: &mut Option) { @@ -1440,6 +1455,7 @@ impl SolveApp { toolbar::app_bar(self, ui); issue_report::CadInput::block(self, ui, report_input); file_load::show(self, ui.ctx()); + open_meshing::show(self, ui.ctx()); documents::prompt(self, ui.ctx()); update::show(self, ui.ctx()); install::show(self, ui.ctx()); @@ -1524,13 +1540,25 @@ impl SolveApp { break; } // Held requests go first, in order, once the file is in. - let held = if self.file_load.busy() || self.file_picker.is_some() { None } else { self.control_held.pop_front() }; + // A screenshot waiting for an opened design to be meshed holds what came after it. + let shot_waits = open_meshing::active(self) && self.control_held.front().is_some_and(|r| r.method == "ui.screenshot"); + let held = if self.file_load.busy() || self.file_picker.is_some() || shot_waits { None } else { self.control_held.pop_front() }; let Some(req) = held.or_else(|| rx.as_ref().and_then(|rx| rx.try_recv().ok())) else { break }; + if shot_waits { + if self.control_held.len() < MAX_HELD { + self.control_held.push_back(req); + } else { + let _ = req.reply.send(json!({"ok": false, "error": "a file operation is in progress"})); + } + continue; + } // A file is loading: commands that change the design wait for it (the window, // inspection and screenshots still answer). if ((self.file_load.busy() || self.file_picker.is_some()) && matches!(req.method.as_str(), "engine.execute" | "command" | "engine.script" | "engine.batch")) || (self.file_picker_busy() && matches!(req.method.as_str(), "ui.file" | "ui.home")) + // A screenshot shows the whole design: it waits until an opened one is meshed. + || (open_meshing::active(self) && req.method == "ui.screenshot") { if self.control_held.len() < MAX_HELD { self.control_held.push_back(req); diff --git a/crates/ui-egui/src/open_meshing.rs b/crates/ui-egui/src/open_meshing.rs new file mode 100644 index 000000000..7843ceef8 --- /dev/null +++ b/crates/ui-egui/src/open_meshing.rs @@ -0,0 +1,249 @@ +//! A design that has just opened shows its parts as they are meshed (#3053). +//! +//! Opening hands the design to the window once its timeline is evaluated (or taken from its +//! file) and placed; the display meshes are made afterwards, off the UI thread. Until they all +//! are, the viewport draws the bodies already meshed ([`shown_world`]), so the first parts show +//! within moments and the window stays responsive while the rest come in. The first placement of +//! every part is meshed first: its other placements only move that mesh. The view is framed from +//! the bodies' outlines meanwhile, and framed again from the meshes when they are all made, unless +//! the camera was moved in between. Editing the design meanwhile meshes the new world instead. +//! +//! The picture lists the bodies in the order they were meshed, and is kept once complete until +//! the design changes: the viewport's scene keeps the blocks it built for the bodies already +//! shown and builds only the new ones, and finishing does not build the whole scene again. It is +//! remade at most every [`REFRESH`] seconds, and less often while a remake takes longer. +//! +//! Display only: commands, picking of what is drawn and exports read the session's world as ever. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use solidcraft_engine::doc::ModelState; + +use crate::SolveApp; + +/// How often a growing picture is remade at most (s). +const REFRESH: f64 = 0.25; +/// A remake waits this many times as long as the last scene build took, so remakes take at most +/// a small share of the window thread. +const REFRESH_SHARE: f64 = 6.0; + +pub(crate) struct Meshing { + /// The world being meshed (the session's when it started). + world: Arc, + /// The bodies of `world` whose display (mesh, and plans when drawn from them) is made, in + /// the order they were made. + ready: Arc>>, + done: Arc, + /// All are meshed and framed: the picture is kept until the design changes. + complete: bool, + stop: Arc, + /// The picture so far: the bodies shown, and how many were ready when it was made. + shown: Option<(usize, Arc)>, + shown_at: f64, + /// The camera the outline framing left (a refit at the end only replaces that one). + framed: Option, + /// Draw the design's Home picture when all is meshed. + remember: Option, + /// When it started, and whether the first bodies have been shown (`SOLIDCRAFT_PROFILE_OPEN`). + began: Option, + first_shown: bool, +} + +impl Meshing { + fn start(world: Arc, plans: bool) -> Meshing { + let n = world.bodies.len(); + let ready = Arc::new(Mutex::new(Vec::with_capacity(n))); + let (done, stop) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicBool::new(false))); + // The first placement of each part first: the others only move its mesh. + let mut seen = std::collections::HashSet::new(); + let (mut first, mut rest) = (Vec::new(), Vec::new()); + for (i, b) in world.bodies.iter().enumerate() { + if seen.insert(b.definition_name().to_string()) { first.push(i) } else { rest.push(i) } + } + first.extend(rest); + let job = (world.clone(), ready.clone(), done.clone(), stop.clone()); + let spawned = std::thread::Builder::new().name("open-meshing".into()).spawn(move || { + let (world, ready, done, stop) = job; + solidcraft_engine::kernel::for_each_on_threads(&first, 16, |&i| { + if stop.load(Ordering::Relaxed) { + return; + } + if let Some(b) = world.bodies.get(i) { + let _ = b.mesh(); + if plans { + let _ = b.display_plan(); + let _ = b.plan_mesh(); + } + } + if let Ok(mut r) = ready.lock() { + r.push(i); + } + done.fetch_add(1, Ordering::Release); + }); + }); + if spawned.is_err() { + // No thread: the viewport meshes as it draws, as before. + done.store(n, Ordering::Release); + } + Meshing { + world, + ready, + done, + stop, + complete: false, + shown: None, + shown_at: f64::NEG_INFINITY, + framed: None, + remember: None, + began: None, + first_shown: false, + } + } + + fn finished(&self) -> bool { + self.done.load(Ordering::Acquire) >= self.world.bodies.len() + } +} + +impl Drop for Meshing { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} + +/// Start meshing the session's world off the UI thread (an opened design), framing the view from +/// the bodies' outlines; `remember`: then draw the Home picture of that file. +pub(crate) fn start(app: &mut SolveApp, remember: Option) { + app.open_meshing_next = false; + let plans = app.viewport.gpu.is_some_and(|g| g.tess); + let mut meshing = Meshing::start(app.session.world_state(), plans); + meshing.remember = remember; + app.open_meshing = Some(meshing); + app.fit_view(); + if let Some(m) = app.open_meshing.as_mut() { + m.framed = Some(app.cam); + } +} + +/// How far the meshing is: bodies done, and of how many. +pub(crate) fn progress(app: &SolveApp) -> Option<(usize, usize)> { + app.open_meshing.as_ref().filter(|m| !m.complete).map(|m| (m.done.load(Ordering::Acquire).min(m.world.bodies.len()), m.world.bodies.len())) +} + +/// A small "Loading parts n/N" note at the foot of the viewport while bodies are being meshed: +/// a part not drawn yet can't be picked yet either, and this says why. +pub(crate) fn show(app: &SolveApp, ctx: &egui::Context) { + let (Some((done, total)), Some(view)) = (progress(app), app.viewport.rect) else { return }; + let t = crate::theme::Tokens::get(); + let at = egui::pos2(view.left() + 12.0, view.bottom() - 12.0); + egui::Area::new(egui::Id::new("open_meshing")) + .order(egui::Order::Foreground) + .pivot(egui::Align2::LEFT_BOTTOM) + .fixed_pos(at) + .interactable(false) + .show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(t.panel).show(ui, |ui| { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(egui::RichText::new(format!("Loading parts {done}/{total}")).color(t.text)); + }); + }); + }); +} + +/// Whether bodies are still being meshed after an open. +pub(crate) fn active(app: &SolveApp) -> bool { + app.open_meshing.as_ref().is_some_and(|m| !m.complete) +} + +/// Whether the view is framed from outlines: bodies being meshed, or about to be. +pub(crate) fn framing(app: &SolveApp) -> bool { + active(app) || app.open_meshing_next +} + +/// Per frame: follow the session's world, show more as it is meshed, and frame the finished +/// picture. +pub(crate) fn tick(app: &mut SolveApp, ctx: &egui::Context) { + let Some(m) = app.open_meshing.as_ref() else { return }; + let world = app.session.world_state(); + if !Arc::ptr_eq(&world, &m.world) { + if m.complete { + // The design changed after its open: the viewport draws it as ever. + app.open_meshing = None; + return; + } + // The design changed (an edit, an undo): mesh the new world; what is made is kept. + let (framed, remember) = (m.framed, m.remember.clone()); + let plans = app.viewport.gpu.is_some_and(|g| g.tess); + let mut next = Meshing::start(world.clone(), plans); + (next.framed, next.remember) = (framed, remember); + app.open_meshing = Some(next); + } + let Some(m) = app.open_meshing.as_ref().filter(|m| !m.complete) else { return }; + if m.finished() && m.shown.as_ref().is_some_and(|(n, _)| *n >= m.world.bodies.len()) { + let (framed, remember, began) = (m.framed, m.remember.clone(), m.began); + if let Some(m) = app.open_meshing.as_mut() { + m.complete = true; + } + if profiling() { + let ms = began.map_or(0.0, |t| (ctx.input(|i| i.time) - t) * 1000.0); + eprintln!("SolidCraft open meshing: all {} bodies shown after {ms:.0} ms", world.bodies.len()); + } + // Framed from outlines and not moved since: frame the meshes. + if framed == Some(app.cam) { + app.fit_view(); + } + crate::frame_watch::step(app, "frame the meshes"); + if let Some(key) = remember { + crate::home::remember_source(&mut app.home, &app.session, &key); + } + crate::frame_watch::step(app, "home picture"); + return; + } + ctx.request_repaint(); +} + +/// The world the viewport draws: while an opened design is being meshed, the bodies meshed so +/// far (the picture grows a few times a second), then all of them, in the order they came, until +/// the design changes; otherwise the session's. +pub(crate) fn shown_world(app: &SolveApp) -> Arc { + let Some(m) = app.open_meshing.as_ref() else { return app.session.world_state() }; + if !Arc::ptr_eq(&app.session.world_state(), &m.world) { + return app.session.world_state(); + } + m.shown.as_ref().map(|(_, st)| st.clone()).unwrap_or_else(|| Arc::new(ModelState::default())) +} + +/// Remake the picture so far, at most every [`REFRESH`] seconds and no sooner than +/// [`REFRESH_SHARE`] times the last scene build (the bodies shown before keep their place, so the +/// viewport builds only the new ones). +pub(crate) fn refresh(app: &mut SolveApp, now: f64) { + let build_s = app.viewport.build_ms / 1000.0; + let Some(m) = app.open_meshing.as_mut().filter(|m| !m.complete) else { return }; + let order: Vec = match m.ready.lock() { + Ok(r) => r.clone(), + Err(_) => return, + }; + let done = order.len(); + let all = done >= m.world.bodies.len(); + let wait = REFRESH.max(build_s * REFRESH_SHARE); + if m.shown.as_ref().is_some_and(|(n, _)| *n == done) || (now - m.shown_at < wait && !all) { + return; + } + let began = *m.began.get_or_insert(now); + let mut st = (*m.world).clone(); + st.bodies = order.iter().filter_map(|&i| m.world.bodies.get(i).cloned()).collect(); + if !m.first_shown && !st.bodies.is_empty() { + m.first_shown = true; + if profiling() { + eprintln!("SolidCraft open meshing: first {} bodies shown after {:.0} ms", st.bodies.len(), (now - began) * 1000.0); + } + } + m.shown = Some((done, Arc::new(st))); + m.shown_at = now; +} + +fn profiling() -> bool { + solidcraft_engine::geom::env::var_os("PROFILE_OPEN").is_some() +} diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index 04a56dac0..6a002fa82 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -256,7 +256,9 @@ impl Harness { } // A file opening, recovering or saving in the background: wait for it (as a person would). let began = std::time::Instant::now(); - while (!self.app.file_load.idle() || self.app.saving.is_some()) && began.elapsed() < std::time::Duration::from_secs(120) { + while (!self.app.file_load.idle() || self.app.saving.is_some() || crate::open_meshing::active(&self.app)) + && began.elapsed() < std::time::Duration::from_secs(120) + { self.frame(); std::thread::sleep(std::time::Duration::from_millis(1)); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1686c59ce..c23cbbb75 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -284,20 +284,24 @@ pub fn projection(app: &SolveApp, rect: Rect) -> Proj { /// Sketches drawn in the viewport: the active one, and finished ones not yet used by a feature. pub(crate) fn visible_sketches(app: &SolveApp) -> Vec { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); st.sketches.iter().filter(|s| solidcraft_engine::view::sketch_drawn(&app.session, s.feature, app.ui.show_sketches)).map(|s| s.feature).collect() } /// What Home, Fit and the orbit pivot frame: the bodies and sketches shown now, where they are /// now (see [`solidcraft_engine::view::visible_bounds`]). pub fn view_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 { + // Bodies still being meshed after an open frame the view by their outlines. + if crate::open_meshing::framing(app) { + return solidcraft_engine::view::unmeshed_bounds(&app.session, app.ui.show_sketches); + } solidcraft_engine::view::visible_bounds(&app.session, app.ui.show_sketches) } fn scene_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.revision.hash(&mut h); - (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut h); + (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); app.ui.show_grid.hash(&mut h); app.ui.visual_style.hash(&mut h); app.ui.ground_shadow.hash(&mut h); @@ -331,7 +335,7 @@ fn sketch_scene_key(app: &SolveApp, proj: &Proj) -> u64 { // The grid this scene draws follows the view when the preference says so (#1470): turning it // on or off redraws even while the camera holds still. app.preferences.grid_follows_view.hash(&mut h); - (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut h); + (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); crate::sketch_display::projection_key(proj, app.viewport.pixels_per_point()).hash(&mut h); h.finish() } @@ -499,7 +503,7 @@ fn update_refinement(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) { } let t0 = crate::now_ms(); app.viewport.lod_view = view; - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let ppp = f64::from(app.viewport.pixels_per_point()); let lens = crate::display_lod::Lens::new(&proj.cam, f64::from(proj.rect.height()) * ppp); let bounds = body_bounds(app, &st); @@ -642,7 +646,7 @@ fn build_scene(app: &SolveApp) -> GpuScene { let mut sc = GpuScene::default(); let s = &app.session; // Bodies where their occurrences place them. - let st = s.world_state(); + let st = crate::open_meshing::shown_world(app); let active_bodies = s.active_occurrence_path.as_ref().and_then(|p| s.occurrence_bodies(p, true).ok()); let (shaded, edges) = match app.ui.visual_style { 1 => (true, false), @@ -744,7 +748,7 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let tk = Tokens::get(); let mut sc = GpuScene::default(); let s = &app.session; - let st = s.world_state(); + let st = crate::open_meshing::shown_world(app); let mut fill_budget = 131_072; let sketch_plane = solidcraft_engine::view::open_sketch_plane(s); if sketch_plane.is_some() || (app.ui.show_grid && !active_view(app).hide_grid) { @@ -1065,7 +1069,7 @@ type BodyBounds = (std::sync::Arc, std::sync /// The model's extent: bodies (from the cached boxes) and sketches. pub fn model_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let mut b = body_bounds(app, &st).iter().fold(solidcraft_engine::geom::Aabb3::EMPTY, |a, (_, x)| a.union(x)); for ss in &st.sketches { if let Some((lo, hi)) = ss.sketch.bounds() { @@ -1139,7 +1143,7 @@ pub(crate) fn pick_cached(app: &mut SolveApp, proj: &Proj, pos: Pos2) -> Vec Near { fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, all: bool) -> Vec { let s = &app.session; - let st = s.world_state(); + let st = crate::open_meshing::shown_world(app); let bounds = body_bounds(app, &st); let mut hits = Vec::new(); let (o, d) = proj.ray(pos); @@ -1466,7 +1470,7 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, /// The section cut shown now: the open Section Analysis dialog's plane, else the session's. /// The active sketch's display options (defaults when not sketching). pub fn active_view(app: &SolveApp) -> solidcraft_engine::sketch::SketchView { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); app.session.active_sketch.and_then(|s| st.sketch(s)).map(|ss| ss.sketch.view.clone()).unwrap_or_default() } @@ -1480,7 +1484,7 @@ pub fn section_plane(app: &SolveApp) -> Option<(Vec3, Vec3)> { } // Slice (Sketch Palette): cut the model at the plane of the sketch being edited. if app.session.section.is_none() { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); if let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)).filter(|ss| ss.sketch.view.slice) { return Some((ss.plane.origin, ss.plane.normal())); } @@ -1496,7 +1500,7 @@ fn feature_geometry(app: &SolveApp, id: u64) -> Vec { if !app.session.model.result(id).is_some_and(|r| !r.skipped && r.error.is_none()) { return Vec::new(); } - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let prefix = format!("F{id}:"); let mut out = Vec::new(); for b in &st.bodies { @@ -1541,7 +1545,7 @@ fn displayed_selection(app: &SolveApp, item: &Sel) -> Vec { /// The box around what is selected (bodies, faces, edges, vertices, sketch curves and the /// bodies of selected features), where it is shown. pub fn selection_bounds(app: &SolveApp) -> Option { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let mut b = solidcraft_engine::geom::Aabb3::EMPTY; for s in app.session.selection.iter().flat_map(|item| displayed_selection(app, item)) { match &s { @@ -1851,7 +1855,7 @@ fn hidden_face_outline(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, fac } pub(crate) fn profile_fill(sc: &mut GpuScene, app: &SolveApp, sketch: u64, index: usize, fill: Color32, edge: Color32) { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let Some(ss) = st.sketch(sketch) else { return }; let Some(p) = ss.profiles.get(index) else { return }; let plane = match crate::dialogs::emboss_profile_plane(app, sketch) { @@ -1908,7 +1912,7 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); let selected = app.highlighted(); app.session.revision.hash(&mut h); - (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut h); + (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); serde_json::to_string(&selected).unwrap_or_default().hash(&mut h); format!("{:?}", app.viewport.hover).hash(&mut h); app.viewport.hover_feature.hash(&mut h); @@ -1960,7 +1964,7 @@ struct HoverBlock { fn build_highlight(app: &SolveApp) -> GpuScene { let t = Tokens::get(); let mut sc = GpuScene::default(); - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let s = &app.session; let active_bodies = s.active_occurrence_path.as_ref().and_then(|p| s.occurrence_bodies(p, true).ok()); // Faces lit over the model use the triangles the model shows them with. @@ -2250,7 +2254,7 @@ fn body_color(doc: &solidcraft_engine::doc::Document, b: &solidcraft_engine::doc /// A body's display colour (else the theme's) as RGB. fn body_rgb(app: &SolveApp, name: &str) -> (u8, u8, u8) { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let c = st.body(name).and_then(|b| body_color(&app.session.doc, b)).unwrap_or(Tokens::get().body); (c.r(), c.g(), c.b()) } @@ -2280,7 +2284,7 @@ fn seg_dist(p: Pos2, a: Pos2, b: Pos2) -> f32 { /// id of the sketch point it snapped to. pub fn sketch_point_at(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option<(Vec2, Option)> { let sid = app.session.active_sketch?; - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let ss = st.sketch(sid)?; for h in pick(app, proj, pos) { if let Hit::SketchPoint { sketch, id, at } = h @@ -2372,7 +2376,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } let proj = projection(app, rect); if let Ok(mut cache) = app.viewport.display.lock() { - cache.prepare(app.session.world_state(), &proj, app.viewport.pixels_per_point()); + cache.prepare(crate::open_meshing::shown_world(app), &proj, app.viewport.pixels_per_point()); } // Suppress hover for the whole navigation gesture, including frames between pointer // events. Testing delta made the highlight reappear whenever a held drag paused. @@ -2420,7 +2424,9 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { painter.add(Shape::mesh(mesh)); // ---- model ---- + crate::frame_watch::step(app, "viewport before the model"); update_refinement(app, ui.ctx(), &proj); + crate::frame_watch::step(app, "display refinement"); let key = scene_key(app); let t0 = crate::now_ms(); // Drawn on the GPU; without one (the headless harness, tests) the model is not drawn. @@ -2432,6 +2438,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } app.viewport.key = key; app.viewport.build_ms = crate::now_ms() - t0; + crate::frame_watch::step(app, "model scene"); } let sk = sketch_scene_key(app, &proj); if sk != app.viewport.sketch_key { @@ -2562,7 +2569,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some((hit, Some(sel))) = cand { dialog_pick(app, &hit, sel); } else if let Some(mut dialog) = app.dialog.take() { - let state = app.session.world_state(); + let state = crate::open_meshing::shown_world(app); if let Some(sketch) = app.session.active_sketch.and_then(|id| state.sketch(id)) { let (origin, direction) = proj.ray(p); if let Some(point) = sketch.plane.intersect_ray(origin, direction) { @@ -2637,7 +2644,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && app.tool.is_none() && app.dialog.is_none() && let Some(Hit::Edge { body, index, .. }) = app.viewport.hover.clone() - && let Some(b) = app.session.world_state().body(&body).cloned() + && let Some(b) = crate::open_meshing::shown_world(app).body(&body).cloned() { let m = b.mesh(); let items: Vec = m @@ -2658,7 +2665,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // Dragging a sketch point of the active sketch moves it; the solver keeps the constraints. if app.tool.is_none() && app.dialog.is_none() && primary_nav.is_none() && mode.is_none() && app.session.active_sketch.is_some() && !held { let on_plane = |app: &SolveApp, p: Pos2| { - let ss = app.session.active_sketch.and_then(|sid| app.session.world_state().sketch(sid).cloned())?; + let ss = app.session.active_sketch.and_then(|sid| crate::open_meshing::shown_world(app).sketch(sid).cloned())?; let (o, d) = proj.ray(p); ss.plane.intersect_ray(o, d).map(|w| ss.plane.to_local(w)) }; @@ -2745,7 +2752,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let with = dragged_with(app, &id); // Snap the dragged point (or the line's ends) to other geometry, like drawing. let snap = { - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); app.session.active_sketch.and_then(|s| st.sketch(s)).and_then(|ss| { let sk = &ss.sketch; let (mut own, mut exclude) = crate::drag_snap::moving_points(sk, &id); @@ -3083,7 +3090,7 @@ fn box_select(app: &mut SolveApp, proj: &Proj, bx: BoxSel, add: bool) { if app.applying.is_some() { return; } - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); let mut out: Vec = Vec::new(); let to2 = |pts: &[Vec3]| -> Vec { pts.iter().filter_map(|p| proj.to_screen(*p)).collect() }; let sketch_dialog = app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::SketchModify(_))); @@ -3271,7 +3278,7 @@ fn grid_centre(tf: Vec3, back: Vec3, n: Vec3, ext: f64) -> Vec3 { /// Hover feedback for the active sketch's points and curves (drawn on top of everything). fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let col = Tokens::get().hover_profile_edge; - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); match &app.viewport.hover { // Trim shows the piece it would take away instead (`sketch_tools::preview`, #3052). Some(Hit::SketchCurve { sketch, id, .. }) if crate::sketch_tools::trim_hover_piece(app, *sketch, id).is_some() => {} @@ -3326,7 +3333,7 @@ pub(crate) fn standalone_points(app: &SolveApp) -> Vec { /// Sketch points and the status of the active sketch (constraint glyphs: `sketch_tools`). fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { let t = Tokens::get(); - let st = app.session.world_state(); + let st = crate::open_meshing::shown_world(app); for item in &app.session.selection { if let Sel::ExternalSketchPoint { sketch, id } = item && let Some(ss) = st.sketch(*sketch)