From 9a79588575c8bd284bb73a9edadf2e76b6e5c050 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:38:41 -0400 Subject: [PATCH] doc, engine, ui: placing the model returns its error; placements are checked where they are set doc: world_state, world_state_reusing, state_in_frame_at, state_in_frame, face_point_state, face_point_names and construction_state return Result. A body that could not be placed, a frame that could not be inverted, a sketch plane or thread axis that did not survive the placement, or a failed placing worker used to leave things where they were without a word; now the call fails with what could not be placed. is_placement is the one test of an occurrence's placement (finite, a rotation that does not mirror, a translation within 1e9 mm). Opening a design names every occurrence that fails it; add_occurrence refuses one; a joint solution that would place an occurrence outside one is not applied and the joints placing it report it. engine: Session::world_state returns Result and keeps a failure in its cache as it keeps a placed model. bounds, home_camera, open_sketch_plane, the scene builders, the world previews, frames::to_local and auto_operation pass the error on; helpers answering "not found" take the placed model from their caller. Commands setting a placement check it (valid_position, exploded view, fastener at a point, STEP insert matrix). ui: panels, picks and hovers read the session's placed model through open_meshing::session_world; a model that cannot be placed shows no placed bodies, and the viewport says why across its bottom. Pictures and the control channel report the error. cli, mcp: snapshots, renders, benches and the oracle report the error; the kernel-case rig records it as the case's failure. Tests read the new Results with unwrap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017itGh5fpMEousnZ91cYcVt --- apps/solidcraft-cli/src/bench_agent.rs | 6 +- apps/solidcraft-cli/src/kernel_cases.rs | 9 +- apps/solidcraft-cli/src/main.rs | 13 +- apps/solidcraft-cli/src/oracle.rs | 2 +- apps/solidcraft-cli/tests/action_matrix.rs | 18 ++- apps/solidcraft-cli/tests/model_cache.rs | 2 +- apps/solidcraft-cli/tests/naming_corpus.rs | 4 +- apps/solidcraft-cli/tests/rebuild_topology.rs | 4 +- apps/solidcraft-cli/tests/snapshot_camera.rs | 8 +- .../tests/straight_edges_after_cuts.rs | 2 +- crates/doc/src/anchor_frame.rs | 2 +- crates/doc/src/assembly.rs | 23 ++- crates/doc/src/body_transfer.rs | 13 +- crates/doc/src/eval.rs | 144 +++++++++--------- crates/doc/src/format.rs | 32 +--- crates/doc/src/joints.rs | 9 ++ crates/doc/src/lib.rs | 4 +- crates/doc/src/placed_mesh.rs | 6 +- crates/doc/src/progress.rs | 3 +- crates/engine/src/cmd/browser.rs | 18 ++- crates/engine/src/cmd/clearance.rs | 2 +- crates/engine/src/cmd/clearance_tests.rs | 2 +- crates/engine/src/cmd/clipboard.rs | 2 +- crates/engine/src/cmd/compare.rs | 2 +- crates/engine/src/cmd/component.rs | 12 +- crates/engine/src/cmd/component_link.rs | 2 +- .../src/cmd/component_transfer_tests.rs | 46 +++--- crates/engine/src/cmd/config.rs | 2 +- .../src/cmd/config_certificate_tests.rs | 6 +- crates/engine/src/cmd/config_style_tests.rs | 8 +- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/edit_tests.rs | 12 +- crates/engine/src/cmd/face_join_tests.rs | 4 +- crates/engine/src/cmd/face_tests.rs | 6 +- crates/engine/src/cmd/features.rs | 31 ++-- crates/engine/src/cmd/features_more.rs | 11 +- crates/engine/src/cmd/features_more_tests.rs | 32 ++-- crates/engine/src/cmd/file.rs | 32 ++-- crates/engine/src/cmd/file_thumbnail.rs | 6 +- crates/engine/src/cmd/inspect.rs | 15 +- crates/engine/src/cmd/interference.rs | 2 +- crates/engine/src/cmd/interference_tests.rs | 4 +- crates/engine/src/cmd/loft_rails_tests.rs | 2 +- crates/engine/src/cmd/measure_sel.rs | 16 +- crates/engine/src/cmd/motion.rs | 6 +- crates/engine/src/cmd/motion_animation.rs | 17 ++- crates/engine/src/cmd/motion_tests.rs | 2 +- crates/engine/src/cmd/occurrence_tests.rs | 10 +- .../engine/src/cmd/offset_edit_guard_tests.rs | 6 +- .../engine/src/cmd/offset_identity_tests.rs | 2 +- .../engine/src/cmd/offset_topology_tests.rs | 10 +- crates/engine/src/cmd/parts.rs | 5 +- crates/engine/src/cmd/patterns_tests.rs | 4 +- .../engine/src/cmd/render/settings_tests.rs | 4 +- crates/engine/src/cmd/sheet_tests.rs | 20 +-- crates/engine/src/cmd/silhouette.rs | 2 +- .../engine/src/cmd/sketch_3d_frame_tests.rs | 22 +-- .../engine/src/cmd/sketch_clipboard_tests.rs | 2 +- .../src/cmd/sketch_dimensioned_tests.rs | 2 +- .../engine/src/cmd/sketch_drag_live_tests.rs | 2 +- crates/engine/src/cmd/sketch_face_tests.rs | 12 +- crates/engine/src/cmd/sketch_modify_tests.rs | 14 +- crates/engine/src/cmd/sketch_project.rs | 4 +- crates/engine/src/cmd/sketch_project_tests.rs | 2 +- .../engine/src/cmd/sketch_text_move_tests.rs | 10 +- crates/engine/src/cmd/surface.rs | 133 ++++++++-------- crates/engine/src/cmd/surface_analysis.rs | 2 +- .../engine/src/cmd/surface_boundary_tests.rs | 10 +- crates/engine/src/cmd/surface_match.rs | 6 +- crates/engine/src/cmd/sweep_options_tests.rs | 4 +- crates/engine/src/cmd/sweep_rails_tests.rs | 2 +- crates/engine/src/cmd/view_dxf_meshes.rs | 2 +- crates/engine/src/display_mesh_tests.rs | 6 +- crates/engine/src/frames.rs | 28 ++-- crates/engine/src/frames_tests.rs | 2 +- crates/engine/src/large_assembly_tests.rs | 4 +- crates/engine/src/lib.rs | 77 +++++----- crates/engine/src/pattern_suppress_tests.rs | 2 +- crates/engine/src/product_scene.rs | 4 +- crates/engine/src/profile_refs_tests.rs | 4 +- crates/engine/src/sample.rs | 4 +- .../engine/src/sketch_edit_removed_tests.rs | 4 +- crates/engine/src/tests.rs | 66 ++++---- crates/engine/src/tests/component_frames.rs | 14 +- crates/engine/src/tests/gltf_import.rs | 1 + crates/engine/src/tests/import_component.rs | 6 +- crates/engine/src/tests/mirror_placed.rs | 4 +- crates/engine/src/tests/native_cad_import.rs | 2 +- crates/engine/src/tests/primitive_points.rs | 2 +- .../engine/src/tests/step_import_options.rs | 2 +- crates/engine/src/view.rs | 102 +++++++------ crates/engine/src/view_bounds_tests.rs | 40 ++--- crates/engine/src/view_display_tests.rs | 9 +- crates/engine/src/view_palette_tests.rs | 18 +-- .../engine/src/world_placement_cache_tests.rs | 85 ++++++----- crates/engine/tests/save_as_cache.rs | 2 +- crates/gpu/src/tests.rs | 5 +- crates/gpu/tests/capture.rs | 31 ++-- crates/gpu/tests/depth.rs | 8 +- crates/io/src/design/native_cache.rs | 2 +- crates/mcp/src/backend.rs | 17 ++- crates/ui-egui/src/access.rs | 2 +- crates/ui-egui/src/agent_cursor.rs | 2 +- crates/ui-egui/src/blend_arrow_tests.rs | 4 +- crates/ui-egui/src/blend_dialog_tests.rs | 4 +- crates/ui-egui/src/boundary_dialog_tests.rs | 6 +- crates/ui-egui/src/browser.rs | 6 +- crates/ui-egui/src/browser/features.rs | 6 +- crates/ui-egui/src/canvas.rs | 14 +- crates/ui-egui/src/context_menu.rs | 16 +- crates/ui-egui/src/control.rs | 20 ++- crates/ui-egui/src/dialogs.rs | 71 ++++----- crates/ui-egui/src/dialogs_all_tests.rs | 6 +- crates/ui-egui/src/dialogs_appearance.rs | 2 +- crates/ui-egui/src/dialogs_assembly.rs | 8 +- crates/ui-egui/src/dialogs_assembly_tests.rs | 4 +- crates/ui-egui/src/dialogs_cam_tests.rs | 2 +- crates/ui-egui/src/dialogs_coupling.rs | 2 +- crates/ui-egui/src/dialogs_coupling_tests.rs | 2 +- crates/ui-egui/src/dialogs_motion.rs | 2 +- crates/ui-egui/src/dialogs_part_size.rs | 6 +- crates/ui-egui/src/dialogs_sheet.rs | 8 +- crates/ui-egui/src/dialogs_surface.rs | 8 +- crates/ui-egui/src/dim_view.rs | 8 +- .../ui-egui/src/dimension_create_ui_tests.rs | 24 +-- crates/ui-egui/src/drag_snap.rs | 2 +- crates/ui-egui/src/extrude_edit_tests.rs | 50 +++--- crates/ui-egui/src/extrude_preview.rs | 8 +- crates/ui-egui/src/file_load.rs | 10 +- crates/ui-egui/src/file_load_ui_tests.rs | 16 +- .../ui-egui/src/fillet_spline_handle_tests.rs | 4 +- crates/ui-egui/src/help.rs | 2 +- crates/ui-egui/src/hole_placement_ui_tests.rs | 17 ++- crates/ui-egui/src/home.rs | 11 +- crates/ui-egui/src/inference.rs | 2 +- .../src/infinite_line_display_tests.rs | 4 +- crates/ui-egui/src/lib.rs | 4 +- crates/ui-egui/src/menu_tests.rs | 16 +- crates/ui-egui/src/occurrence_ui_tests.rs | 6 +- crates/ui-egui/src/open_meshing.rs | 25 ++- crates/ui-egui/src/pick_index_tests.rs | 2 +- crates/ui-egui/src/prefs.rs | 2 +- crates/ui-egui/src/preselect_tests.rs | 63 +++++--- crates/ui-egui/src/preview.rs | 2 +- crates/ui-egui/src/render_workspace.rs | 2 +- crates/ui-egui/src/revolve_edit_tests.rs | 28 ++-- .../ui-egui/src/revolve_manipulator_tests.rs | 16 +- crates/ui-egui/src/scale_tests.rs | 6 +- crates/ui-egui/src/select_other.rs | 4 +- .../ui-egui/src/shell_face_sketch_ui_tests.rs | 4 +- crates/ui-egui/src/sketch3d.rs | 12 +- crates/ui-egui/src/sketch3d_frame_ui_tests.rs | 16 +- .../ui-egui/src/sketch_attachment_ui_tests.rs | 8 +- crates/ui-egui/src/sketch_clover_ui_tests.rs | 6 +- crates/ui-egui/src/sketch_corner_ui_tests.rs | 22 +-- crates/ui-egui/src/sketch_dims.rs | 4 +- crates/ui-egui/src/sketch_dims_tests.rs | 22 +-- crates/ui-egui/src/sketch_display.rs | 4 +- .../src/sketch_display_preview_tests.rs | 8 +- crates/ui-egui/src/sketch_display_ui_tests.rs | 14 +- crates/ui-egui/src/sketch_drag_ui_tests.rs | 16 +- .../ui-egui/src/sketch_guidance_ui_tests.rs | 14 +- crates/ui-egui/src/sketch_modify_ui.rs | 22 +-- crates/ui-egui/src/sketch_modify_ui_tests.rs | 6 +- .../ui-egui/src/sketch_neutral_click_tests.rs | 2 +- crates/ui-egui/src/sketch_palette.rs | 20 +-- crates/ui-egui/src/sketch_shortcut_tests.rs | 6 +- crates/ui-egui/src/sketch_side_ui_tests.rs | 6 +- crates/ui-egui/src/sketch_text.rs | 36 ++--- crates/ui-egui/src/sketch_text_handles.rs | 8 +- crates/ui-egui/src/sketch_tools.rs | 18 +-- .../ui-egui/src/sketch_trim_drag_ui_tests.rs | 2 +- .../ui-egui/src/sketch_typed_intent_tests.rs | 26 +++- crates/ui-egui/src/smart_extrude_ui_tests.rs | 4 +- crates/ui-egui/src/stand_up.rs | 3 +- crates/ui-egui/src/thin_extrude_tests.rs | 2 +- crates/ui-egui/src/timeline.rs | 4 +- crates/ui-egui/src/timeline_left.rs | 2 +- crates/ui-egui/src/tools.rs | 6 +- crates/ui-egui/src/view_home_tests.rs | 4 +- crates/ui-egui/src/viewport.rs | 57 ++++--- .../ui-egui/src/viewport_appearance_tests.rs | 4 +- .../src/viewport_plane_target_tests.rs | 2 +- crates/ui-egui/src/workspace.rs | 6 +- .../ui-egui/tests/constraint_preselection.rs | 2 +- crates/ui-egui/tests/icon_audit.rs | 2 +- .../tests/point_constraint_preselection.rs | 2 +- .../ui-egui/tests/projection_preselection.rs | 8 +- crates/ui-egui/tests/stand_up_offer.rs | 2 +- 189 files changed, 1273 insertions(+), 1123 deletions(-) diff --git a/apps/solidcraft-cli/src/bench_agent.rs b/apps/solidcraft-cli/src/bench_agent.rs index d21867190..a15005915 100644 --- a/apps/solidcraft-cli/src/bench_agent.rs +++ b/apps/solidcraft-cli/src/bench_agent.rs @@ -184,7 +184,7 @@ pub fn run(args: &[String]) -> Result<(), String> { s.execute(id, &c["params"]).map_err(|e| format!("command {i} ({id}): {e}"))?; run.push(t.elapsed().as_secs_f64() * 1000.0); let t = std::time::Instant::now(); - s.world_state().warm_meshes(|| true); + s.world_state().map_err(|e| e.to_string())?.warm_meshes(|| true); shown.push(t.elapsed().as_secs_f64() * 1000.0); if run.len() == 100 || i + 1 == commands.len() { let mean = |v: &[f64]| v.iter().sum::() / v.len().max(1) as f64; @@ -198,7 +198,7 @@ pub fn run(args: &[String]) -> Result<(), String> { shown.clear(); } } - let world = s.world_state(); + let world = s.world_state().map_err(|e| e.to_string())?; println!( "{}", json!({"step": "built", "ms": began.elapsed().as_secs_f64() * 1000.0, "commands": commands.len(), "features": s.doc.features.len(), "bodies": world.bodies.len()}) @@ -233,7 +233,7 @@ mod tests { } } assert!(s.model.results.iter().all(|r| r.error.is_none())); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(world.bodies.len() > 40, "{} bodies", world.bodies.len()); assert!(world.bodies.iter().any(|b| b.name.contains("spoke"))); } diff --git a/apps/solidcraft-cli/src/kernel_cases.rs b/apps/solidcraft-cli/src/kernel_cases.rs index a703f92cc..d75f83ae0 100644 --- a/apps/solidcraft-cli/src/kernel_cases.rs +++ b/apps/solidcraft-cli/src/kernel_cases.rs @@ -211,7 +211,14 @@ fn check_case(dir: &str, dumps: Option<&std::path::Path>) -> Value { } // Every body in the world, imported components included. - let world = s.world_state(); + let world = match s.world_state() { + Ok(w) => w, + Err(e) => { + out["status"] = json!("fail"); + out["error"] = json!(e.to_string()); + return out; + } + }; let mut bodies = Vec::new(); let mut c = Checks { list: Vec::new(), pass: true }; let want_valid = want["valid"].as_bool().unwrap_or(true); diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 82836583f..1f75f1105 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -564,9 +564,12 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { } (None, None) => {} } - let cam = s.camera.unwrap_or_else(|| solidcraft_engine::view::home_camera(&s)); + let cam = match s.camera { + Some(cam) => cam, + None => solidcraft_engine::view::home_camera(&s).map_err(|e| e.to_string())?, + }; let guides = Guides { grid: !args.iter().any(|a| a == "--no-grid"), axes: !args.iter().any(|a| a == "--no-axes") }; - let scene = solidcraft_engine::view::scene_with_guides(&s, &cam, s.section, guides); + let scene = solidcraft_engine::view::scene_with_guides(&s, &cam, s.section, guides).map_err(|e| e.to_string())?; let png = solidcraft_engine::capture::png(&scene, &cam, w, h)?; std::fs::write(out, &png.bytes).map_err(|e| format!("{out}: {e}"))?; let mut reply = json!({"path": out, "width": w, "height": h, "bytes": png.bytes.len(), "renderer": png.renderer}); @@ -803,7 +806,7 @@ fn bench_ops(mut s: Session, script: &str) -> Result { let r = s.execute(id, p).map_err(|e| format!("{id}: {e}"))?; let ms = t.elapsed().as_secs_f64() * 1000.0; let t = std::time::Instant::now(); - s.world_state().warm_meshes(|| true); + s.world_state().map_err(|e| e.to_string())?.warm_meshes(|| true); let view_ms = t.elapsed().as_secs_f64() * 1000.0; println!("{}", json!({"step": "op", "command": id, "ms": ms, "view_ms": view_ms})); Ok(r) @@ -859,7 +862,7 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { println!("{}", json!({"step": "feature", "id": r.id, "name": r.name, "ms": r.ms, "error": r.error})); } let t = std::time::Instant::now(); - let st = s.world_state(); + let st = s.world_state().map_err(|e| e.to_string())?; let place_ms = t.elapsed().as_secs_f64() * 1000.0; // As the desktop app prepares a design it opened. st.warm_meshes(|| true); @@ -929,7 +932,7 @@ pub(crate) fn cmd_bench_open(args: &[String]) -> Result<(), String> { let t = std::time::Instant::now(); s.execute("parameters.change", &json!({"name": name, "expression": expr})).map_err(|e| e.to_string())?; let eval_ms = t.elapsed().as_secs_f64() * 1000.0; - let st = s.world_state(); + let st = s.world_state().map_err(|e| e.to_string())?; let t = std::time::Instant::now(); st.warm_meshes(|| true); let mesh_ms = t.elapsed().as_secs_f64() * 1000.0; diff --git a/apps/solidcraft-cli/src/oracle.rs b/apps/solidcraft-cli/src/oracle.rs index 42be25eb8..c27b102c8 100644 --- a/apps/solidcraft-cli/src/oracle.rs +++ b/apps/solidcraft-cli/src/oracle.rs @@ -186,7 +186,7 @@ fn step_export_check(s: &solidcraft_engine::Session, volume: f64) -> (bool, Stri /// Our part as a triangle soup (curved faces refined onto the surface). fn our_mesh(s: &solidcraft_engine::Session) -> Result, String> { let mut ours: Vec = Vec::new(); - for b in &s.world_state().bodies { + for b in &s.world_state().map_err(|e| e.to_string())?.bodies { let m = b.body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(MESH_TOL)).map_err(|e| e.to_string())?; let p = |i: u32| m.positions.get(i as usize).map(|v: &Vec3| [v.x, v.y, v.z]); for t in &m.triangles { diff --git a/apps/solidcraft-cli/tests/action_matrix.rs b/apps/solidcraft-cli/tests/action_matrix.rs index 977e2e72a..c61af32b5 100644 --- a/apps/solidcraft-cli/tests/action_matrix.rs +++ b/apps/solidcraft-cli/tests/action_matrix.rs @@ -196,7 +196,7 @@ fn round3(x: f64) -> f64 { /// Every action on every entity of the design's final bodies, in a fixed order. fn actions(s: &Session) -> Vec { - let st = s.world_state(); + let st = s.world_state().unwrap(); let placed = s.placed_document(); let paths: BTreeMap> = placed.body_frames_with_source(&s.model.state()).into_iter().map(|(world, _, _, path, _)| (world, path)).collect(); @@ -1338,7 +1338,9 @@ fn a_fillet_or_chamfer_on_one_edge_ending_at_a_cylinder() { fn a_round_on_a_knuckle_cap_circle() { for (cmd, size, removed) in [("solid.fillet", "radius", (2.4, 2.8)), ("solid.chamfer", "distance", (5.6, 6.3))] { let mut s = load(&root().join("tests/oracle/63-hinge-knuckle/recipe.json")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.001)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute(cmd, &json!({"edges": [[40.0, 29.837_722, 6.449_490]], size: 0.728})).unwrap_or_else(|e| panic!("{cmd}: {e}")); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{cmd}: {kind}: {e}")); @@ -1358,7 +1360,9 @@ fn a_round_on_a_knuckle_cap_circle() { #[test] fn a_hair_thin_hole_on_a_ledge_beside_a_loft_cut() { let mut s = load(&root().join("examples/regressions/loft_cut_beside_round_hole.json")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.005)).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.005)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute("solid.hole", &json!({"diameter": 0.133, "position": [357.22, -150.993_333, 730.0]})).unwrap(); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{kind}: {e}")); @@ -1375,7 +1379,9 @@ fn a_hair_thin_hole_on_a_ledge_beside_a_loft_cut() { #[test] fn a_small_hole_through_the_wall_of_a_plastic_rest() { let mut s = load(&root().join("apps/solidcraft-cli/tests/corpus/modern-plastic.solidcraft")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.002)).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.002)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute("solid.hole", &json!({"diameter": 0.8, "position": [63.069_841_5, 28.333_333, 4.0]})).unwrap(); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{kind}: {e}")); @@ -1390,7 +1396,9 @@ fn a_small_hole_through_the_wall_of_a_plastic_rest() { #[test] fn a_hole_square_to_a_45_degree_flange() { let mut s = load(&root().join("tests/oracle/70-sm-flange-45/recipe.json")).unwrap(); - let volume = |s: &Session| s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.002)).unwrap().measure().volume).sum::(); + let volume = |s: &Session| { + s.model.state().bodies.iter().map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.002)).unwrap().measure().volume).sum::() + }; let before = volume(&s); s.execute("solid.hole", &json!({"diameter": 3.448, "position": [66.666_667, -4.511_845, 4.511_845]})).unwrap(); check(&s, 0, &BTreeMap::new()).unwrap_or_else(|(kind, e)| panic!("{kind}: {e}")); diff --git a/apps/solidcraft-cli/tests/model_cache.rs b/apps/solidcraft-cli/tests/model_cache.rs index 42a91adae..c08d5948b 100644 --- a/apps/solidcraft-cli/tests/model_cache.rs +++ b/apps/solidcraft-cli/tests/model_cache.rs @@ -63,7 +63,7 @@ fn model(name: &str, s: &Session) -> Value { .iter() .map(|r| json!({"id": r.id, "name": r.name, "error": r.error, "warning": r.warning, "skipped": r.skipped, "state": state(name, &r.state)})) .collect(); - json!({"results": results, "world": state(name, &s.world_state())}) + json!({"results": results, "world": state(name, &s.world_state().unwrap())}) } /// The same edit on both: a parameter's value when the design has one, else a new body. diff --git a/apps/solidcraft-cli/tests/naming_corpus.rs b/apps/solidcraft-cli/tests/naming_corpus.rs index d5f95af72..d54e6ff32 100644 --- a/apps/solidcraft-cli/tests/naming_corpus.rs +++ b/apps/solidcraft-cli/tests/naming_corpus.rs @@ -168,7 +168,7 @@ fn record_refs(out: &mut Vec, s: &Session, f: &Feature) { // Faces a feature picks by point and stores by name (shell, draft, hole, …). let explicit_emboss = matches!(&f.kind, FeatureKind::Emboss { face: Some(_), .. }); if f.face_names.iter().any(|n| !n.is_empty()) { - let fst = solidcraft_engine::doc::face_point_state(doc, &before, &f.kind, f.component); + let fst = solidcraft_engine::doc::face_point_state(doc, &before, &f.kind, f.component).unwrap(); for (k, (p, n)) in f.kind.face_points().into_iter().zip(&f.face_names).enumerate() { if n.is_empty() { continue; @@ -269,7 +269,7 @@ fn record_refs(out: &mut Vec, s: &Session, f: &Feature) { FaceAttachmentStatus::Lost { message, .. } => format!("lost: {message}"), FaceAttachmentStatus::Legacy { .. } => { // Found by its name among the faces facing the same way, nearest the pick. - let fst = solidcraft_engine::doc::state_in_frame(doc, &before, f.component); + let fst = solidcraft_engine::doc::state_in_frame(doc, &before, f.component).unwrap(); let mut list: Vec = match name { Some(n) => fst .bodies diff --git a/apps/solidcraft-cli/tests/rebuild_topology.rs b/apps/solidcraft-cli/tests/rebuild_topology.rs index f097b3f4b..0d17567f7 100644 --- a/apps/solidcraft-cli/tests/rebuild_topology.rs +++ b/apps/solidcraft-cli/tests/rebuild_topology.rs @@ -31,7 +31,7 @@ struct Topology { /// Every solid body's topology, by name. fn topology(s: &Session) -> BTreeMap { - let st = s.world_state(); + let st = s.world_state().unwrap(); st.bodies .iter() .filter(|b| !b.body.is_mesh()) @@ -174,7 +174,7 @@ fn pi_case_faces_per_step_at_both_heights() { for (k, want) in FACES { let mut t = s.scratch(); t.execute("timeline.rollback", &json!({"position": k})).unwrap(); - let st = t.world_state(); + let st = t.world_state().unwrap(); let body = st.bodies.iter().find(|b| b.name == "Body1").unwrap(); assert_eq!(body.body.face_count(), want, "{case}: faces after feature {k}"); // Each outer side: the faces in its plane. diff --git a/apps/solidcraft-cli/tests/snapshot_camera.rs b/apps/solidcraft-cli/tests/snapshot_camera.rs index 69e4f89b7..f5ad66ab9 100644 --- a/apps/solidcraft-cli/tests/snapshot_camera.rs +++ b/apps/solidcraft-cli/tests/snapshot_camera.rs @@ -171,9 +171,9 @@ fn a_saved_view_is_its_camera_and_a_standard_view_is_unchanged() { let top = dir.snapshot(&script, "top.png", &["--view", "top"]); let mut s = Session::default(); s.run_script(&serde_json::from_slice(&std::fs::read(&script).unwrap()).unwrap()).unwrap(); - let mut cam = solidcraft_engine::view::home_camera(&s); + let mut cam = solidcraft_engine::view::home_camera(&s).unwrap(); cam.set_view(solidcraft_engine::render::StandardView::Top); - let scene = solidcraft_engine::view::scene(&s, &cam); + let scene = solidcraft_engine::view::scene(&s, &cam).unwrap(); assert_same(&top, &solidcraft_engine::capture::png(&scene, &cam, SIZE.0, SIZE.1).unwrap().bytes, "the home camera turned to the top"); assert_same(&top, &dir.mcp(&script, "mcp-top.png", json!({"view": "top"})), "the MCP top view"); assert_differs(&top, &saved, "top and the saved view"); @@ -335,9 +335,9 @@ fn a_forced_cpu_snapshot_is_the_cpu_rasterizers_and_says_so() { assert!(stderr.contains("CPU rasterizer"), "{stderr}"); let mut s = Session::default(); s.run_script(&serde_json::from_slice(&std::fs::read(&script).unwrap()).unwrap()).unwrap(); - let mut cam = solidcraft_engine::view::home_camera(&s); + let mut cam = solidcraft_engine::view::home_camera(&s).unwrap(); cam.set_view(solidcraft_engine::render::StandardView::Top); - let scene = solidcraft_engine::view::scene(&s, &cam); + let scene = solidcraft_engine::view::scene(&s, &cam).unwrap(); let cpu = solidcraft_engine::render::render_png(&scene, &cam, SIZE.0 as usize, SIZE.1 as usize).unwrap(); assert_eq!(std::fs::read(dir.0.join("cpu.png")).unwrap(), cpu); } diff --git a/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs b/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs index 89a0a7a2f..8446d8252 100644 --- a/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs +++ b/apps/solidcraft-cli/tests/straight_edges_after_cuts.rs @@ -48,7 +48,7 @@ fn key(v: Vec3) -> [i64; 3] { fn straight_edges_are_one_edge_after_many_cuts() { for (what, s) in [("as saved", open(&design())), ("built from scratch", rebuilt())] { assert_eq!(errors(&s), vec![], "{what}: every feature evaluates"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let bodies: Vec<_> = st.bodies.iter().filter(|b| !b.body.is_mesh()).collect(); assert_eq!(bodies.len(), 1, "{what}: one body"); let body = &bodies[0].body; diff --git a/crates/doc/src/anchor_frame.rs b/crates/doc/src/anchor_frame.rs index 9dd56cd1e..091cec098 100644 --- a/crates/doc/src/anchor_frame.rs +++ b/crates/doc/src/anchor_frame.rs @@ -6,7 +6,7 @@ pub fn state_in_face_anchor_frame<'a>(doc: &Document, state: &'a ModelState, anc let frame = anchor.author_frame(doc, author)?; let raw = state.body(&anchor.target.body).ok_or_else(|| DocError::Unknown(format!("anchored body `{}`", anchor.target.body)))?; let relative = anchor.source_to_author(doc, author, raw)?; - let mut output = crate::state_in_frame_at(doc, state, author, frame).into_owned(); + let mut output = crate::state_in_frame_at(doc, state, author, frame)?.into_owned(); // In place, the body is the model's own, display mesh included: a sketch projecting the // face's edges meshes it once for the features after it too, rather than a copy. let body = state.body_in_frame(raw, &relative)?; diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index 0ca382f85..03f01e361 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -84,6 +84,23 @@ pub fn mat_inverse(m: &Mat) -> Option { Some(out) } +/// Whether `m` is a placement an occurrence may have: finite, a rotation (orthonormal axes, not +/// mirrored) and a translation within 1e9 mm, its last column `0, 0, 0, 1`. Every placement is +/// checked against this where it enters the document (a design file, a command, an import). +pub fn is_placement(m: &Mat) -> bool { + let axis = |i: usize| Vec3::new(m[i][0], m[i][1], m[i][2]); + let (x, y, z) = (axis(0), axis(1), axis(2)); + m.iter().flatten().all(|v| v.is_finite()) + && m[3][..3].iter().all(|v| v.abs() <= 1e9) + && [x, y, z].iter().all(|v| (v.dot(*v) - 1.0).abs() < 1e-6) + && x.dot(y).abs() < 1e-6 + && x.dot(z).abs() < 1e-6 + && y.dot(z).abs() < 1e-6 + && x.cross(y).dot(z) > 0.0 + && [m[0][3], m[1][3], m[2][3]].iter().all(|v| v.abs() < 1e-9) + && (m[3][3] - 1.0).abs() < 1e-9 +} + /// A rigid transform: rotation by `angle` about `axis` through `origin`, then a translation. pub fn rigid(translate: Vec3, origin: Vec3, axis: Vec3, angle: f64) -> Mat { let k = axis.normalized().unwrap_or(Vec3::Z); @@ -392,7 +409,8 @@ impl Document { false } - /// Add an occurrence of an existing component into `parent`. + /// Add an occurrence of an existing component into `parent`, placed by `transform` (which + /// must pass [`is_placement`]). pub fn add_occurrence(&mut self, component: u64, parent: u64, transform: Mat) -> Result { if component == 0 || !self.components.iter().any(|c| c.id == component) { return Err(DocError::Unknown(format!("component {component}"))); @@ -403,6 +421,9 @@ impl Document { if self.occurrences.len() >= 100_000 { return Err(DocError::Invalid("too many occurrences".into())); } + if !is_placement(&transform) { + return Err(DocError::Invalid("an occurrence's placement must be a rigid motion (no scaling or mirroring) within 1e9 mm".into())); + } let id = self.next_id.max(1); self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let cname = self.components.iter().find(|c| c.id == component).map(|c| c.name.clone()).unwrap_or_default(); diff --git a/crates/doc/src/body_transfer.rs b/crates/doc/src/body_transfer.rs index 1eca9bbe6..1226ea1d0 100644 --- a/crates/doc/src/body_transfer.rs +++ b/crates/doc/src/body_transfer.rs @@ -1,20 +1,9 @@ //! Recorded ownership changes are evaluated at their timeline position. use crate::{DocError, Document, Mat, ModelBody, ModelState, Result}; -use solidcraft_geom::Vec3; use std::collections::BTreeSet; pub fn valid_transfer_matrix(m: &Mat) -> bool { - let axis = |i: usize| Vec3::new(m[i][0], m[i][1], m[i][2]); - let (x, y, z) = (axis(0), axis(1), axis(2)); - m.iter().flatten().all(|v| v.is_finite()) - && m[3][..3].iter().all(|v| v.abs() <= 1e9) - && [x, y, z].iter().all(|v| (v.dot(*v) - 1.0).abs() < 1e-6) - && x.dot(y).abs() < 1e-6 - && x.dot(z).abs() < 1e-6 - && y.dot(z).abs() < 1e-6 - && x.cross(y).dot(z) > 0.0 - && [m[0][3], m[1][3], m[2][3]].iter().all(|v| v.abs() < 1e-9) - && (m[3][3] - 1.0).abs() < 1e-9 + crate::is_placement(m) } /// Validate the stored boundary before allocation, loading, or evaluation. diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 8f01f3711..844096e3a 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2192,19 +2192,24 @@ impl Model { // Face references by name: move each face point onto its named face (on the body the // feature names, when it names one and the face is there). let renamed; + let mut frame_error: Option = None; let f = match with_named_face_points(doc, &state, f) { - Some((g, notes)) => { + Ok(Some((g, notes))) => { if !notes.is_empty() { warning = Some(notes.join("; ")); } renamed = g; &renamed } - None => f, + Ok(None) => f, + Err(e) => { + frame_error = Some(e.to_string()); + f + } }; // A parameter with an error fails the features using it, with that error. let bad_param = param_names(f).into_iter().find_map(|n| self.param_errors.get(&n).map(|e| format!("parameter `{n}`: {e}"))); - let r = match bad_param { + let r = match frame_error.or(bad_param) { Some(e) => Err(kernel::KernelError::Failed(e)), None => kernel::guard(&f.name, || { eval_feature(doc, &vals, f, &mut next, &mut warning).map_err(|e| kernel::KernelError::Failed(e.to_string())) @@ -4516,7 +4521,7 @@ fn feature_tools_with_constructor( // model is seen from there: a target in another, moved component where it is shown. let n = ss.plane.normal(); let tst = - if extent.to.is_some() || extent.from.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; + if extent.to.is_some() || extent.from.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) }; // Through all, and where the tool meets its targets, is measured where they are shown. let shown = targets_as_shown(st, f, &crate::plain(targets))?; let st: &ModelState = &shown; @@ -4724,7 +4729,7 @@ fn feature_tools_with_constructor( let (o, d) = revolve_axis(&ss, axis, &axis_state(doc, st, f.component, axis), &|name| construction_axis_in(Some(doc), st, name, f.component))?; // To Object is in this feature's component frame: the model as seen from there. - let tst = if to.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; + let tst = if to.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) }; // Where the tool meets its targets is measured where they are shown (#3383). let shown = targets_as_shown(st, f, &feature_op(f).1)?; let st: &ModelState = &shown; @@ -5692,13 +5697,14 @@ fn copied_features(doc: &Document, vals: &BTreeMap, st: &ModelSta /// own, so no two copies of one feature share an instance. Suppressed sources copy nothing. /// `f` with each face point moved onto its named face (on the body the feature names, when it /// names one and the face is there) in `state`, and notes for names that no longer find their -/// face. `None` when `f` names no face. -fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Option<(Feature, Vec)> { +/// face. `None` when `f` names no face; an error when the frame the faces are looked up in +/// cannot be made (the feature fails with it). +fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Result)>> { // Cylindrical emboss resolves its named face in the selected body's frame // and certifies an analytic anchor; mesh projection here would undo that. let explicit_emboss = matches!(&f.kind, FeatureKind::Emboss { face: Some(_), .. }); if explicit_emboss || !f.face_names.iter().any(|n| !n.is_empty()) { - return None; + return Ok(None); } let mut g = f.clone(); let mut notes = Vec::new(); @@ -5709,7 +5715,7 @@ fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Op FeatureKind::Hole { direction, points: None | Some(crate::SketchPoints { single: true, .. }), .. } => direction.normalized(), _ => None, }; - let fst = face_point_state(doc, state, &f.kind, f.component); + let fst = face_point_state(doc, state, &f.kind, f.component)?; for (k, (p, n)) in g.kind.face_points_mut().into_iter().zip(&f.face_names).enumerate() { if n.is_empty() { continue; @@ -5735,7 +5741,7 @@ fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Op None => notes.push(format!("face `{n}` no longer exists; using the face at the picked point")), } } - Some((g, notes)) + Ok(Some((g, notes))) } fn copy_plan<'a>( @@ -5927,7 +5933,7 @@ fn replay( // Each copy's faces are named as the source feature's, with the instance. Its face // points follow their named faces, as the feature's own did (#2121): a To Object // extrude's copies reach the face where it is now, not where it was picked. - let moved = with_named_face_points(doc, st, src).map(|(g, _)| g); + let moved = with_named_face_points(doc, st, src)?.map(|(g, _)| g); let tools = feature_tools_with_constructor(doc, vals, moved.as_ref().unwrap_or(src), st, &mut None, &mut None, &mut None)?; for (k, m) in mats.iter().enumerate() { let start = copies.len(); @@ -6404,7 +6410,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // component's bodies moved into its frame: placing every body of a large // assembly again is what made each sketch edit as slow as the design is big. None if !plane_reads_geometry(plane) && sketch.links.is_empty() => std::borrow::Cow::Borrowed(st), - None => state_in_frame(doc, st, f.component), + None => state_in_frame(doc, st, f.component)?, }; let (plane, face_warning) = match (anchor, plane) { (Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?, @@ -6644,14 +6650,14 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: // A plane of numbers alone reads no body: placing them all is the design's size. None if plane_is_fixed(plane) => doc.resolve_plane_in(vals, plane, 0, Some(st))?, // Picks on bodies of other (moved) components are where those bodies are shown. - None => doc.resolve_plane_in(vals, plane, 0, Some(&construction_state(doc, st, f.component)))?, + None => doc.resolve_plane_in(vals, plane, 0, Some(&*construction_state(doc, st, f.component)?))?, }; st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Plane(pl) }); Ok(()) } FeatureKind::ConstructionAxis { def } => { let (origin, dir) = - crate::construct::resolve_axis(&crate::construct::Ctx { doc, vals, st: &construction_state(doc, st, f.component), depth: 0 }, def)?; + crate::construct::resolve_axis(&crate::construct::Ctx { doc, vals, st: &*construction_state(doc, st, f.component)?, depth: 0 }, def)?; st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), @@ -6660,8 +6666,10 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: Ok(()) } FeatureKind::ConstructionPoint { def } => { - let p = - crate::construct::resolve_point(&crate::construct::Ctx { doc, vals, st: &construction_state(doc, st, f.component), depth: 0 }, def)?; + let p = crate::construct::resolve_point( + &crate::construct::Ctx { doc, vals, st: &*construction_state(doc, st, f.component)?, depth: 0 }, + def, + )?; st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Point(p) }); Ok(()) } @@ -7246,9 +7254,9 @@ fn unique_body_name(st: &ModelState, base: &str) -> String { /// What construction geometry of component `comp` is built on: the model as that component sees /// it, other components' bodies where they are placed. In the root, every placement of a /// component (its pasted instances too) is there, as the viewport shows it. -fn construction_state<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std::borrow::Cow<'a, ModelState> { +fn construction_state<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> Result> { if comp == 0 && !doc.occurrences.is_empty() { - return std::borrow::Cow::Owned(world_state(doc, st)); + return Ok(std::borrow::Cow::Owned(world_state(doc, st)?)); } state_in_frame(doc, st, comp) } @@ -7391,7 +7399,7 @@ fn tool_in(tool: &Traced, m: Option) -> Result { } } -pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std::borrow::Cow<'a, ModelState> { +pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> Result> { state_in_frame_at(doc, st, comp, doc.component_transform(comp)) } @@ -7400,10 +7408,10 @@ pub fn state_in_frame<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std: /// (`comp`): the model as that component sees it, a target in another, moved component where it /// is shown (#928). Other face points are picks, kept in the frame of the body they lie on: the /// model itself. -pub fn face_point_state<'a>(doc: &Document, st: &'a ModelState, kind: &FeatureKind, comp: u64) -> std::borrow::Cow<'a, ModelState> { +pub fn face_point_state<'a>(doc: &Document, st: &'a ModelState, kind: &FeatureKind, comp: u64) -> Result> { match kind { FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. } => state_in_frame(doc, st, comp), - _ => std::borrow::Cow::Borrowed(st), + _ => Ok(std::borrow::Cow::Borrowed(st)), } } @@ -7411,19 +7419,20 @@ pub fn face_point_state<'a>(doc: &Document, st: &'a ModelState, kind: &FeatureKi /// [`face_point_state`]. A To / From point is named after the nearest face over every body, the /// one `object_height` resolves it to, not the first body with a face within tolerance: a part /// resting a hair from the picked face would otherwise take its name. -pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, comp: u64) -> Vec { +pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, comp: u64) -> Result> { let pts = kind.face_points(); if !matches!(kind, FeatureKind::Extrude { .. } | FeatureKind::Revolve { .. }) { - return crate::naming::face_names_at(st, &pts); + return Ok(crate::naming::face_names_at(st, &pts)); } - let fst = face_point_state(doc, st, kind, comp); + let fst = face_point_state(doc, st, kind, comp)?; let normal = match kind { FeatureKind::Extrude { sketch, .. } => { st.sketch(sketch.0).and_then(|ss| sketch_in_feature_frame(doc, ss, comp).ok()).map(|ss| ss.plane.normal()) } _ => None, }; - pts.iter() + Ok(pts + .iter() .map(|p| { fst.bodies .iter() @@ -7436,16 +7445,16 @@ pub fn face_point_names(doc: &Document, st: &ModelState, kind: &FeatureKind, com .and_then(|(_, b, fi)| crate::naming::face_names(b).get(fi).cloned()) .unwrap_or_default() }) - .collect() + .collect()) } /// As `state_in_frame`, using the exact active placement for its shared source geometry. -pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, frame: Mat) -> std::borrow::Cow<'a, ModelState> { +pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, frame: Mat) -> Result> { use std::borrow::Cow; if doc.occurrences.is_empty() && doc.body_offsets.is_empty() { - return Cow::Borrowed(st); + return Ok(Cow::Borrowed(st)); } - let Some(inv) = crate::mat_inverse(&frame) else { return Cow::Borrowed(st) }; + let inv = crate::mat_inverse(&frame).ok_or_else(|| DocError::Invalid(format!("component {comp}'s frame cannot be inverted")))?; let comp_of_feature = |id: u64| doc.feature(id).map(|f| f.component).unwrap_or(0); let rel = |c: u64, body: Option<&str>| { let m = crate::mat_mul(&inv, &if c == comp { frame } else { doc.component_transform(c) }); @@ -7466,13 +7475,12 @@ pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, fram let world_wires_need_mapping = !crate::is_identity(&inv) && st.sketches.iter().any(|sketch| sketch.sketch.wires.iter().any(|wire| wire.space == solidcraft_sketch::WireSpace::World)); if body_m.iter().chain(&sketch_m).all(crate::is_identity) && !world_wires_need_mapping { - return Cow::Borrowed(st); + return Ok(Cow::Borrowed(st)); } let mut out = st.clone(); for (b, m) in out.bodies.iter_mut().zip(&body_m) { - if !crate::is_identity(m) - && let Ok(moved) = st.body_in_frame(b, m) - { + if !crate::is_identity(m) { + let moved = st.body_in_frame(b, m).map_err(|e| DocError::Invalid(format!("body `{}` cannot be moved into the frame: {e}", b.name)))?; *b = moved; } } @@ -7483,24 +7491,22 @@ pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, fram continue; } let s = Arc::make_mut(s); - if !crate::is_identity(m) - && let Some(np) = Plane::new(crate::apply_point(m, s.plane.origin), crate::apply_vector(m, s.plane.x), crate::apply_vector(m, s.plane.y)) - { - s.plane = np; + if !crate::is_identity(m) { + s.plane = placed_plane(m, &s.plane)?; } for wire in &mut s.sketch.wires { let matrix = if wire.space == solidcraft_sketch::WireSpace::Component { m } else { &inv }; map_wire(wire, matrix); } } - Cow::Owned(out) + Ok(Cow::Owned(out)) } /// The model placed in the world: each component's bodies, sketches, threads and construction /// geometry through every occurrence of it (bodies of the first placement keep their names; /// further instances get the occurrence path in brackets). Without components this is the model /// itself. -pub fn world_state(doc: &Document, st: &ModelState) -> ModelState { +pub fn world_state(doc: &Document, st: &ModelState) -> Result { world_state_reusing(doc, st, &mut PlacedBodies::default()) } @@ -7532,19 +7538,16 @@ impl PlacedBodies { .map(|(_, placed)| placed) } - /// The body `b` placed by `m`, from an earlier call when `b` is the same body as then. - fn placed(&self, b: &ModelBody, m: &crate::Mat, name: String) -> ModelBody { + /// The body `b` placed by `m`, from an earlier call when `b` is the same body as then; an + /// error when it cannot be placed. + fn placed(&self, b: &ModelBody, m: &crate::Mat, name: String) -> Result { if let Some(placed) = self.taken(b, m, &name) { - return placed; - } - match kernel::place_matrix(&b.body, *m) { - Ok(body) => { - let mut fresh = ModelBody::new(name, body, b.feature); - fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new); - fresh - } - Err(_) => ModelBody::new(name, b.body.clone(), b.feature), + return Ok(placed); } + let body = kernel::place_matrix(&b.body, *m).map_err(|e| DocError::Invalid(format!("body `{}` cannot be placed: {e}", b.name)))?; + let mut fresh = ModelBody::new(name, body, b.feature); + fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new); + Ok(fresh) } /// The body `b` placed by `m` as an earlier call placed it, when `b` is the same body as then. @@ -7631,9 +7634,9 @@ fn placed_key(b: &ModelBody, m: &crate::Mat) -> (usize, [u64; 16]) { /// [`world_state`], reusing the bodies `placed` holds from an earlier call and leaving it holding /// this call's. -pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut PlacedBodies) -> ModelState { +pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut PlacedBodies) -> Result { if doc.occurrences.is_empty() { - return st.clone(); + return Ok(st.clone()); } let mut placed_now = PlacedBodies::default(); let comp_of_feature = |id: u64| doc.feature(id).map(|f| f.component).unwrap_or(0); @@ -7673,7 +7676,10 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut let reused: Vec<_> = jobs.iter().map(|(b, bm, name)| placed_before.taken(b, bm, name)).collect(); let fresh: Vec<_> = jobs.iter().zip(&reused).filter(|(_, r)| r.is_none()).map(|(job, _)| job).collect(); let mut placed_fresh = kernel::map_on_threads(&fresh, 16, |(b, bm, name)| placed_before.placed(b, bm, name.clone())).into_iter(); - let mut moved = reused.into_iter().map(|r| r.or_else(|| placed_fresh.next().flatten())).zip(&jobs); + let mut moved = reused.into_iter().map(|r| match r { + Some(placed) => Some(Ok(placed)), + None => placed_fresh.next().flatten(), + }); for (comp, path, m) in placements { let primary = path == first_path(comp); let ident = crate::is_identity(&m); @@ -7686,11 +7692,11 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut placed.name = names.name(&b.name, comp, &path); placed } else { - // The same order as the jobs: this body's, made above (again here if it failed). + // The same order as the jobs: this body's, made above. let placed = match moved.next() { - Some((Some(placed), _)) => placed, - Some((None, (_, _, name))) => placed_before.placed(b, &bm, name.clone()), - None => placed_before.placed(b, &bm, names.name(&b.name, comp, &path)), + Some(Some(placed)) => placed?, + Some(None) => return Err(DocError::Invalid(format!("body `{}` could not be placed (its worker failed)", b.name))), + None => return Err(DocError::Invalid(format!("body `{}` has no placement", b.name))), }; placed_now.by_source.insert(placed_key(b, &bm), (b.clone(), placed.clone())); placed @@ -7717,12 +7723,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut continue; } let mut s2 = SolvedSketch::clone(s); - if !ident { - let p = &s.plane; - if let Some(np) = Plane::new(crate::apply_point(&m, p.origin), crate::apply_vector(&m, p.x), crate::apply_vector(&m, p.y)) { - s2.plane = np; - } - } + s2.plane = placed_plane(&m, &s.plane)?; for wire in &mut s2.sketch.wires { if wire.space == solidcraft_sketch::WireSpace::Component { map_wire(wire, &m); @@ -7748,12 +7749,19 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut t2.body = names.name(&t.body, comp, &path); let frame = st.body(&t.body).and_then(|body| doc.model_body_offset(body)).map(|offset| crate::mat_mul(&m, offset)).unwrap_or(m); t2.axis_point = crate::apply_point(&frame, t.axis_point); - t2.axis = crate::apply_vector(&frame, *t.axis).unit().unwrap_or(t.axis); + t2.axis = crate::apply_vector(&frame, *t.axis).unit().ok_or_else(|| DocError::Invalid("a thread's axis cannot be placed".into()))?; out.threads.push(t2); } } *placed_before = placed_now; - out + Ok(out) +} + +/// `plane` moved by the placement `m`; an error when `m` does not keep it a plane (a placement +/// that is not a rigid motion, which [`Document`] does not take). +fn placed_plane(m: &crate::Mat, plane: &Plane) -> Result { + Plane::new(crate::apply_point(m, plane.origin), crate::apply_vector(m, plane.x), crate::apply_vector(m, plane.y)) + .ok_or_else(|| DocError::Invalid("a sketch plane cannot be placed: the placement is not a rigid motion".into())) } #[cfg(test)] @@ -7830,7 +7838,7 @@ mod world_placement_cache_tests { let source = &state.bodies[0]; assert!(source.names.origin.is_some()); assert!(source.mesh.get().is_none()); - let world = world_state(&doc, &state); + let world = world_state(&doc, &state).unwrap(); let names = crate::naming::face_names(&world.bodies[0]); assert!(Arc::ptr_eq(&names, &crate::naming::face_names(source))); assert!(names.iter().all(|name| name.starts_with(&format!("F{feature}:")))); @@ -7853,7 +7861,7 @@ mod world_placement_cache_tests { state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1)); state.bodies[0].key = 1234; let source = &state.bodies[0]; - let world = world_state(&doc, &state); + let world = world_state(&doc, &state).unwrap(); assert_eq!(world.bodies.len(), 2); let first = world.body("Block").unwrap(); let second_name = doc.world_body_name(&state, "Block", component, &[second]); @@ -7876,7 +7884,7 @@ mod world_placement_cache_tests { assert!(Arc::ptr_eq(&names, &crate::naming::face_names(placed))); let original_mesh = source.mesh(); assert!(Arc::ptr_eq(&original_mesh, &first.mesh())); - let again = world_state(&doc, &state); + let again = world_state(&doc, &state).unwrap(); assert!(Arc::ptr_eq(&original_mesh, &again.body("Block").unwrap().mesh())); assert!(Arc::ptr_eq(&names, &crate::naming::face_names(again.body(&second_name).unwrap()))); } diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index ae40e8bc0..81e915599 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -654,10 +654,14 @@ pub fn read(s: &str) -> Result { if let Some(id) = crate::non_contiguous_timeline_group(&d.features, &d.timeline_groups) { return Err(DocError::Invalid(format!("damaged design: timeline folder {id} is not contiguous"))); } - for o in &d.occurrences { - if !rigid(&o.transform) { - return Err(DocError::Invalid(format!("damaged design: occurrence `{}` has an invalid placement", o.name))); - } + // Every occurrence whose placement is not a rigid motion within range, by name. + let unplaced: Vec = d.occurrences.iter().filter(|o| !crate::is_placement(&o.transform)).map(|o| format!("`{}`", o.name)).collect(); + if !unplaced.is_empty() { + return Err(DocError::Invalid(format!( + "damaged design: {} not placed by a rigid motion within 1e9 mm: {}", + if unplaced.len() == 1 { "an occurrence is" } else { "occurrences are" }, + unplaced.join(", ") + ))); } if !all_unique(d.features.iter().map(|f| f.id)) || !all_unique(d.components.iter().map(|c| c.id)) @@ -1122,26 +1126,6 @@ fn check_numbers(v: &Value, depth: usize) -> Result<()> { Ok(()) } -/// A placement: rotation (orthonormal, not mirrored) and a translation in range. -fn rigid(m: &crate::Mat) -> bool { - let row = |i: usize| m.get(i).copied().unwrap_or_default(); - let (x, y, z, t) = (row(0), row(1), row(2), row(3)); - let dot = |a: [f64; 4], b: [f64; 4]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - let unit = |a: [f64; 4]| (dot(a, a) - 1.0).abs() < 1e-6; - let det = x[0] * (y[1] * z[2] - y[2] * z[1]) - x[1] * (y[0] * z[2] - y[2] * z[0]) + x[2] * (y[0] * z[1] - y[1] * z[0]); - m.iter().flatten().all(|v| v.is_finite()) - && unit(x) - && unit(y) - && unit(z) - && dot(x, y).abs() < 1e-6 - && dot(y, z).abs() < 1e-6 - && dot(x, z).abs() < 1e-6 - && det > 0.0 - && [x[3], y[3], z[3]].iter().all(|v| v.abs() < 1e-9) - && (t[3] - 1.0).abs() < 1e-9 - && t[..3].iter().all(|v| v.abs() <= MAX_REAL) -} - /// Feature input names and component occurrences, which format 1 files may predate. fn normalise(d: &mut Document) -> Result<()> { d.normalise_component_color_indices()?; diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index ff7f93e06..62d18796b 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -1904,6 +1904,15 @@ pub fn solve_holding_with_analysis(doc: &Document, st: &ModelState, held: &Held, dof.clear(); } placed.remove(&0); + // A placement that is not a rigid motion within range (values that ran off to infinity, say) + // is not applied: the joints placing that occurrence report it. + let bad: Vec = placed.iter().filter(|(_, m)| !crate::is_placement(m)).map(|(occ, _)| *occ).collect(); + for occ in bad { + placed.remove(&occ); + for j in asm.joints.iter().filter(|j| !j.suppressed && (j.a.occurrence == occ || j.b.occurrence == occ)) { + sol.errors.push((j.id, j.name.clone(), format!("it would place occurrence {occ} outside a rigid placement within 1e9 mm"))); + } + } sol.world = placed; sol.dof = dof; sol diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 3f436adbc..491986451 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -69,8 +69,8 @@ pub mod sheet; pub mod text_params; pub use assembly::{ - IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, WorldNames, apply_point, apply_vector, is_identity, map_point_expr, mat_inverse, - mat_mul, rigid, + IDENTITY, MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, Mat, Occurrence, WorldNames, apply_point, apply_vector, is_identity, is_placement, + map_point_expr, mat_inverse, mat_mul, rigid, }; pub use document::*; pub use eval::KeptResults; diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs index 2ca1bd5d8..0bea5cdf5 100644 --- a/crates/doc/src/placed_mesh.rs +++ b/crates/doc/src/placed_mesh.rs @@ -363,18 +363,18 @@ mod tests { let mut state = crate::ModelState::default(); state.bodies.push(ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2., 8.).unwrap(), 1)); let mut cache = super::super::PlacedBodies::default(); - let before = super::super::world_state_reusing(&doc, &state, &mut cache); + let before = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); assert!(state.bodies[0].cached_mesh().is_none(), "placing bodies must remain lazy"); let old = before.bodies[0].mesh(); assert!(state.bodies[0].cached_mesh().is_some()); let (_, work) = kernel::profile::capture(|| before.bodies[1].mesh()); assert_eq!(work.tessellate_ms, 0., "the second instance shares the first one's triangulation"); doc.occurrences.iter_mut().find(|o| o.id == first).unwrap().transform = crate::rigid(Vec3::new(30., 0., 0.), Vec3::ZERO, Vec3::Y, 0.9); - let moved = super::super::world_state_reusing(&doc, &state, &mut cache); + let moved = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); let (_, work) = kernel::profile::capture(|| moved.bodies[0].mesh()); assert_eq!(work.tessellate_ms, 0., "a new pose shares the same definition"); state.bodies[0] = ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 4., 8.).unwrap(), 1); - let edited = super::super::world_state_reusing(&doc, &state, &mut cache); + let edited = super::super::world_state_reusing(&doc, &state, &mut cache).unwrap(); assert!(state.bodies[0].cached_mesh().is_none()); let new = edited.bodies[0].mesh(); assert!(state.bodies[0].cached_mesh().is_some(), "changed geometry warms its new definition cache"); diff --git a/crates/doc/src/progress.rs b/crates/doc/src/progress.rs index e78dc4a97..c3c1ca0b1 100644 --- a/crates/doc/src/progress.rs +++ b/crates/doc/src/progress.rs @@ -216,7 +216,8 @@ impl Evaluation { if !due { return; } - let world = Arc::new(crate::world_state(doc, state)); + // A world that cannot be placed is shown with the evaluation's own error, at its end. + let Ok(world) = crate::world_state(doc, state).map(Arc::new) else { return }; if let Ok(mut p) = progress.partial.lock() { *p = (Some(Partial { features, world }), Some(web_time::Instant::now())); } diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 5bd8a8836..b59628742 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -196,7 +196,8 @@ fn is_construction(k: &FeatureKind) -> bool { matches!(k, FeatureKind::ConstructionPlane { .. } | FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. }) } -fn shown_item(s: &Session, key: &str) -> Option { +/// The item `key` names; bodies are looked for in the placed model `world`. +fn shown_item(s: &Session, world: &solidcraft_doc::ModelState, key: &str) -> Option { if let Some(f) = s.doc.find_feature(key) { if matches!(f.kind, FeatureKind::Sketch { .. }) { return Some(Shown::Sketch(f.id)); @@ -205,7 +206,7 @@ fn shown_item(s: &Session, key: &str) -> Option { return Some(Shown::Origin(f.name.clone())); } } - if s.world_state().bodies.iter().any(|b| b.name == key) { + if world.bodies.iter().any(|b| b.name == key) { return Some(Shown::Body(key.to_string())); } if let Some(j) = s.doc.assembly.joints.iter().find(|j| j.name == key) { @@ -333,7 +334,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result { list.iter().map(|j| super::joints::joint_id(s, Some(j), cmd).map(Shown::Joint)).collect::>()? } (Some(_), Some(_)) => return Err(bad(cmd, "give `items` or `folder`, not both")), - (Some("bodies"), None) => s.world_state().bodies.iter().map(|b| Shown::Body(b.name.clone())).collect(), + (Some("bodies"), None) => s.world_state()?.bodies.iter().map(|b| Shown::Body(b.name.clone())).collect(), (Some("sketches"), None) => s.model.state().sketches.iter().map(|x| Shown::Sketch(x.feature)).collect(), (Some("construction"), None) => s.doc.features.iter().filter(|f| is_construction(&f.kind)).map(|f| Shown::Origin(f.name.clone())).collect(), (Some("origin"), None) => ORIGIN.iter().map(|o| Shown::Origin(o.to_string())).collect(), @@ -355,8 +356,9 @@ fn visibility(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "`items` must list sketches, bodies or construction geometry")); } // Every item is found before anything changes. + let world = s.world_state()?; keys.iter() - .map(|k| shown_item(s, k).ok_or_else(|| bad(cmd, format!("no sketch, body, construction item or joint `{k}`")))) + .map(|k| shown_item(s, &world, k).ok_or_else(|| bad(cmd, format!("no sketch, body, construction item or joint `{k}`")))) .collect::>()? } (None, None) => return Err(bad(cmd, "`items` or `folder` is required")), @@ -712,9 +714,9 @@ fn view_apply(s: &mut Session, p: &Value) -> Result { // Standard view names come first, as in the browser's Named Views folder. (Some(name), None) => match crate::render::StandardView::parse(name) { Some(sv) => { - let mut c = crate::view::home_camera(s); + let mut c = crate::view::home_camera(s)?; c.set_view(sv); - c.fit(&crate::view::bounds(s)); + c.fit(&crate::view::bounds(s)?); c } None => s.doc.named_views.iter().find(|v| v.name == name).map(camera_of).ok_or_else(|| bad(cmd, format!("no named view `{name}`")))?, @@ -1603,7 +1605,7 @@ mod tests { let body = s.model.state().bodies[0].name.clone(); let drain_name = s.doc.feature(drain).unwrap().name.clone(); let cam = solidcraft_render::Camera::default(); - let lines = |s: &Session| crate::view::scene(s, &cam).lines.len(); + let lines = |s: &Session| crate::view::scene(s, &cam).unwrap().lines.len(); let shown = |s: &mut Session| { let d = run(s, "document.inspect", json!({})); d["sketches"].as_array().unwrap().iter().filter(|x| x["visible"] == true).count() @@ -1631,7 +1633,7 @@ mod tests { run(&mut s, "browser.visibility", json!({"tree_folders": ["c0/sketches"], "visible": true})); // Bodies (following a rename) and construction planes. run(&mut s, "browser.visibility", json!({"items": [body.clone(), "Floor", "xy"], "visible": false})); - assert!(crate::view::scene(&s, &cam).meshes.is_empty()); + assert!(crate::view::scene(&s, &cam).unwrap().meshes.is_empty()); assert_eq!(s.visibility.hidden_origin, vec!["Floor".to_string(), "XY".to_string()]); run(&mut s, "body.rename", json!({"body": body, "name": "Tray"})); assert_eq!(s.visibility.hidden_bodies, vec!["Tray".to_string()]); diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index b0e636f8e..e398f3f84 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -88,7 +88,7 @@ fn clearance(s: &mut Session, p: &Value) -> Result { }, }; - let st = s.world_state(); + let st = s.world_state()?; let (mesh_bodies, solid): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = st.bodies.iter().partition(|b| b.body.is_mesh()); // Mesh bodies are not measured. A mesh body named in `bodies` or `against` is left out of the // pairs and listed as unchecked, rather than refused as "no solid body". diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 9a2207d30..68dfe0758 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -441,7 +441,7 @@ fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); } let _ = std::fs::remove_dir_all(&dir); - s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() + s.world_state().unwrap().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() } /// #3249: mesh bodies are not measured, and used to vanish from the answer (`bodies: 0`, nothing diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 899aea072..b27e98f37 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -620,7 +620,7 @@ mod tests { let spring = r["pasted"][1]["name"].as_str().unwrap_or_default().to_string(); let def = run(&mut s, "timeline.inspect", json!({"feature": spring})); assert_eq!(def["definition"]["targets"], json!(["Plate (2)"]), "{def}"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let v = |name: &str| solidcraft_kernel::measure(&st.body(name).unwrap().body).unwrap().volume; // A spring on the wrong plate is hundreds of mm³ off. The two plates are measured apart // (one moved 50 mm), which the boolean and the measure each round in their own way: diff --git a/crates/engine/src/cmd/compare.rs b/crates/engine/src/cmd/compare.rs index fe26fad19..c4dd5820d 100644 --- a/crates/engine/src/cmd/compare.rs +++ b/crates/engine/src/cmd/compare.rs @@ -155,7 +155,7 @@ fn compare_bodies(s: &mut Session, p: &Value) -> Result { let max_points = number(cmd, p, "max_points", 8e6, 1e4..=5e7)? as usize; let max_regions = number(cmd, p, "max_regions", 50.0, 1.0..=1000.0)? as usize; let colors = colours(cmd, p)?; - let st = s.world_state(); + let st = s.world_state()?; let (na, nb) = pair(s, &st, p, cmd)?; let (Some(ba), Some(bb)) = (st.body(&na), st.body(&nb)) else { return Err(bad(cmd, "no such body")) }; // Meshed within a quarter of the tolerance (the kernel goes no finer than a millionth of a diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index de8931629..a99d000a5 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -125,17 +125,7 @@ fn move_vector(p: &Value, key: &str, default: Vec3, coordinate: bool, cmd: &str) } pub(super) fn valid_position(m: &Mat) -> bool { - let column = |i: usize| Vec3::new(m[i][0], m[i][1], m[i][2]); - let (x, y, z) = (column(0), column(1), column(2)); - m.iter().flatten().all(|x| x.is_finite()) - && m[3][..3].iter().all(|x| x.abs() <= 1e9) - && [x, y, z].iter().all(|axis| (axis.dot(*axis) - 1.0).abs() < 1e-6) - && x.dot(y).abs() < 1e-6 - && x.dot(z).abs() < 1e-6 - && y.dot(z).abs() < 1e-6 - && x.cross(y).dot(z) > 0.0 - && [m[0][3], m[1][3], m[2][3]].iter().all(|x| x.abs() < 1e-9) - && (m[3][3] - 1.0).abs() < 1e-9 + solidcraft_doc::is_placement(m) } pub(super) fn new_component(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index 011c6b831..391d976e6 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -110,7 +110,7 @@ fn session_bodies(part: &Session, shown: &str) -> Result { if let Some(e) = part.model.results.iter().find_map(|r| r.error.clone()) { return Err(EngineError::Other(format!("{shown}: the design has a feature that fails ({e}); fix it before linking it"))); } - let world = part.world_state(); + let world = part.world_state()?; let solids: Vec = world.bodies.iter().filter(|b| !b.body.is_mesh()).map(|b| b.name.clone()).collect(); if solids.is_empty() { return Err(EngineError::Other(format!("{shown}: the design has no solid bodies to link"))); diff --git a/crates/engine/src/cmd/component_transfer_tests.rs b/crates/engine/src/cmd/component_transfer_tests.rs index 921d66117..eb5d4144d 100644 --- a/crates/engine/src/cmd/component_transfer_tests.rs +++ b/crates/engine/src/cmd/component_transfer_tests.rs @@ -24,10 +24,10 @@ fn recorded_assignment_preserves_sample_joined_material_and_timeline() { let index = s.doc.feature_index(feature).unwrap(); s.doc_mut().marker = Some(index); s.refresh(); - assert_eq!(s.world_state().body("Plate").unwrap().component, 0); + assert_eq!(s.world_state().unwrap().body("Plate").unwrap().component, 0); s.doc_mut().marker = None; s.refresh(); - assert_eq!(s.world_state().body("Plate").unwrap().component, to); + assert_eq!(s.world_state().unwrap().body("Plate").unwrap().component, to); } #[test] @@ -39,19 +39,19 @@ fn transformed_pending_destination_repeated_transfer_preserves_world_pose() { let occurrence = created["occurrence"].as_u64().unwrap(); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,20,0],"angle":90,"axis":[0,0,1],"capture":false})); run(&mut s, "component.move_bodies", json!({"component":to,"bodies":["Block"]})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let bounds = state.body("Block").unwrap().mesh().bounds(); assert!(bounds.min.dist(Vec3::ZERO) < 1e-6); assert!(bounds.max.dist(Vec3::new(10.0, 10.0, 10.0)) < 1e-6); assert!(!s.pending_moves.contains_key(&occurrence)); let mut destination_reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; destination_reopened.refresh(); - assert!(destination_reopened.world_state().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); + assert!(destination_reopened.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); run(&mut s, "component.move_bodies", json!({"component":0,"bodies":["Block"]})); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - assert!(reopened.world_state().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); + assert!(reopened.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(Vec3::ZERO) < 1e-6); } #[test] @@ -134,7 +134,7 @@ fn failed_transfer_cannot_change_evaluated_world_owner() { .unwrap(); s.refresh(); assert!(s.model.result(id).unwrap().error.is_some()); - assert_eq!(s.world_state().body("Block").unwrap().component, 0); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, 0); } #[test] @@ -142,18 +142,18 @@ fn transferred_thread_follows_body_frame_without_changing_world_axis() { let mut s = Session::default(); run(&mut s, "solid.cylinder", json!({"radius":4,"height":20,"body_name":"Shaft"})); run(&mut s, "solid.thread", json!({"face":[4,0,10],"designation":"M8"})); - let before = s.world_state().threads[0].clone(); + let before = s.world_state().unwrap().threads[0].clone(); let c = run(&mut s, "component.create", json!({"name":"Threaded","grounded":false})); let to = c["component"].as_u64().unwrap(); let occurrence = c["occurrence"].as_u64().unwrap(); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,20,10],"axis":[1,0,0],"angle":90,"capture":true})); run(&mut s, "component.move_bodies", json!({"component":to,"bodies":["Shaft"]})); - let after = s.world_state().threads[0].clone(); + let after = s.world_state().unwrap().threads[0].clone(); assert!(after.axis_point.dist(before.axis_point) < 1e-6); assert!(after.axis.dist(*before.axis) < 1e-6); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - assert!(reopened.world_state().threads[0].axis.dist(*before.axis) < 1e-6); + assert!(reopened.world_state().unwrap().threads[0].axis.dist(*before.axis) < 1e-6); } #[test] @@ -178,10 +178,10 @@ fn inherited_component_appearance_and_legacy_assignment_survive_transfer() { legacy.refresh(); assert!(!legacy.model.state().body("Old").unwrap().transferred); run(&mut legacy, "component.move_bodies", json!({"component":0,"bodies":["Old"]})); - assert!((legacy.world_state().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); + assert!((legacy.world_state().unwrap().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&legacy.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); - assert!((reopened.world_state().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); + assert!((reopened.world_state().unwrap().body("Old").unwrap().mesh().bounds().min.x - 7.0).abs() < 1e-6); } #[test] @@ -209,7 +209,7 @@ fn earlier_selected_cylinder_emboss_keeps_source_frame_after_transfer_and_edit() run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-2,5],"p1":[2,10]})); run(&mut s, "sketch.finish", json!({})); let emboss = run(&mut s, "solid.emboss", json!({"sketch":"Badge","face":[30,10,7.5],"depth":1}))["feature"].as_u64().unwrap(); - let before = solidcraft_kernel::measure(&s.world_state().body("Sleeve").unwrap().body).unwrap().volume; + let before = solidcraft_kernel::measure(&s.world_state().unwrap().body("Sleeve").unwrap().body).unwrap().volume; run(&mut s, "component.activate", json!({"component":0})); let destination = run(&mut s, "component.create", json!({"name":"Destination"})); let to = destination["component"].as_u64().unwrap(); @@ -220,10 +220,10 @@ fn earlier_selected_cylinder_emboss_keeps_source_frame_after_transfer_and_edit() let mut reopened = Session { doc: solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap().into(), ..Session::default() }; reopened.refresh(); assert!(reopened.doc.features.iter().all(|feature| reopened.model.result(feature.id).is_some_and(|result| result.error.is_none()))); - assert!((solidcraft_kernel::measure(&reopened.world_state().body("Sleeve").unwrap().body).unwrap().volume - before).abs() < 1e-5); + assert!((solidcraft_kernel::measure(&reopened.world_state().unwrap().body("Sleeve").unwrap().body).unwrap().volume - before).abs() < 1e-5); let depth = reopened.doc.feature(emboss).unwrap().param_names[0].clone(); run(&mut reopened, "parameters.change", json!({"name":depth,"expression":"2 mm"})); - assert!(solidcraft_kernel::measure(&reopened.world_state().body("Sleeve").unwrap().body).unwrap().volume > before); + assert!(solidcraft_kernel::measure(&reopened.world_state().unwrap().body("Sleeve").unwrap().body).unwrap().volume > before); } #[test] @@ -235,16 +235,16 @@ fn transfer_undo_redo_restores_original_pending_source_world_pose() { run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Block"})); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":false})); let pending = s.pending_moves.clone(); - let before = s.world_state().body("Block").unwrap().mesh().bounds(); + let before = s.world_state().unwrap().body("Block").unwrap().mesh().bounds(); run(&mut s, "component.move_bodies", json!({"component":0,"bodies":["Block"]})); run(&mut s, "edit.undo", json!({})); assert_eq!(s.pending_moves, pending); - assert_eq!(s.world_state().body("Block").unwrap().component, source); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, source); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); run(&mut s, "edit.redo", json!({})); assert!(s.pending_moves.is_empty()); - assert_eq!(s.world_state().body("Block").unwrap().component, 0); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, 0); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); } #[test] @@ -256,15 +256,15 @@ fn transfer_checkpoint_restores_pending_world_pose_and_history() { run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"body_name":"Block"})); run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":false})); let pending = s.pending_moves.clone(); - let before = s.world_state().body("Block").unwrap().mesh().bounds(); + let before = s.world_state().unwrap().body("Block").unwrap().mesh().bounds(); let undo_count = s.undo.len(); let checkpoint = s.checkpoint(); run(&mut s, "component.move_bodies", json!({"component":0,"bodies":["Block"]})); s.restore_checkpoint(checkpoint).unwrap(); assert_eq!(s.pending_moves, pending); assert_eq!(s.undo.len(), undo_count); - assert_eq!(s.world_state().body("Block").unwrap().component, source); - assert!(s.world_state().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); + assert_eq!(s.world_state().unwrap().body("Block").unwrap().component, source); + assert!(s.world_state().unwrap().body("Block").unwrap().mesh().bounds().min.dist(before.min) < 1e-6); } #[test] diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rs index 2a6792674..ff4210c49 100644 --- a/crates/engine/src/cmd/config.rs +++ b/crates/engine/src/cmd/config.rs @@ -77,7 +77,7 @@ fn column_of(s: &Session, p: &Value, cmd: &str) -> Result { } let body_name = value.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "face body required"))?; let point = value.get("point").and_then(crate::params::vec3).ok_or_else(|| bad(cmd, "finite face point required"))?; - let world = s.world_state(); + let world = s.world_state()?; let body = world.body(body_name).ok_or_else(|| bad(cmd, "no face body"))?; if body.body.is_mesh() { return Err(bad(cmd, "mesh faces have no supported semantic lineage")); diff --git a/crates/engine/src/cmd/config_certificate_tests.rs b/crates/engine/src/cmd/config_certificate_tests.rs index f1501a212..ffd0fd20e 100644 --- a/crates/engine/src/cmd/config_certificate_tests.rs +++ b/crates/engine/src/cmd/config_certificate_tests.rs @@ -225,14 +225,14 @@ fn certified_side_transfer_preserves_geometry_and_unsupported_taper_refuses_atom run(&mut s, "component.move_bodies", json!({"component":destination,"bodies":["Round"]})); run(&mut s, "config.activate", json!({"row":"Painted"})); assert_eq!(painted_radius(&s, "Round", 10.), 2); - let before = s.world_state().body("Round").unwrap().mesh().bounds(); + let before = s.world_state().unwrap().body("Round").unwrap().mesh().bounds(); let mut s = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); run(&mut s, "config.activate", json!({"row":"Painted"})); assert_eq!(painted_radius(&s, "Round", 10.), 2); assert!( - s.world_state().body("Round").unwrap().mesh().bounds().min.dist(before.min) < 1e-8, + s.world_state().unwrap().body("Round").unwrap().mesh().bounds().min.dist(before.min) < 1e-8, "before {before:?}, reopened {:?}", - s.world_state().body("Round").unwrap().mesh().bounds() + s.world_state().unwrap().body("Round").unwrap().mesh().bounds() ); // A successful ordinary modifier has no exact untapered source certificate. let FeatureKind::Extrude { extent, .. } = &mut s.doc_mut().feature_mut(source).unwrap().kind else { panic!() }; diff --git a/crates/engine/src/cmd/config_style_tests.rs b/crates/engine/src/cmd/config_style_tests.rs index c34b81340..f353a0d8f 100644 --- a/crates/engine/src/cmd/config_style_tests.rs +++ b/crates/engine/src/cmd/config_style_tests.rs @@ -23,11 +23,11 @@ fn component_appearance_shared_definition_inheritance_and_delete() { let key = table["columns"][0].as_str().unwrap().to_string(); run(&mut s, "config.row", json!({"name":"Red","values":{key.clone():"ABS - Red"}})); run(&mut s, "config.activate", json!({"row":"Red"})); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), 2); assert!(world.bodies.iter().all(|body| s.doc.model_body_look(body).unwrap().name == "ABS - Red")); run(&mut s, "appearance.assign", json!({"bodies":[body],"appearance":"ABS - Yellow"})); - assert!(s.world_state().bodies.iter().all(|body| s.doc.model_body_look(body).unwrap().name == "ABS - Yellow")); + assert!(s.world_state().unwrap().bodies.iter().all(|body| s.doc.model_body_look(body).unwrap().name == "ABS - Yellow")); run(&mut s, "config.activate", json!({"row":"Default"})); assert!(!s.doc.appearances.components.contains_key(&component)); assert_eq!(s.doc.appearances.bodies[&body].name, "ABS - Yellow"); @@ -147,7 +147,7 @@ fn face_occurrence_pick_uses_definition_identity_and_coordinates() { let component = run(&mut s, "component.create", json!({"name":"Part"}))["component"].as_u64().unwrap(); let body = block(&mut s); run(&mut s, "occurrence.copy", json!({"component":component,"translate":[30,0,0]})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let placed = world.bodies.iter().find(|body| body.name != body.definition_name()).unwrap(); let placed_name = placed.name.clone(); let point = solidcraft_doc::apply_point(&placed.source_transform, solidcraft_geom::Vec3::new(5., 5., 10.)); @@ -157,7 +157,7 @@ fn face_occurrence_pick_uses_definition_identity_and_coordinates() { assert!(target.point.dist(solidcraft_geom::Vec3::new(5., 5., 10.)) < 1e-8); run(&mut s, "config.row", json!({"name":"Paint","values":{key:"ABS - Blue"}})); run(&mut s, "config.activate", json!({"row":"Paint"})); - assert!(s.world_state().bodies.iter().all(|body| s.doc.face_colors(body).len() == 1)); + assert!(s.world_state().unwrap().bodies.iter().all(|body| s.doc.face_colors(body).len() == 1)); } #[test] diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 27ee8dd0d..d4a81c856 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1110,7 +1110,7 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { } // New face points: their faces' names now. if nf.kind.face_points() != f.kind.face_points() { - nf.face_names = solidcraft_doc::face_point_names(&s.doc, &s.model.state_before(id), &nf.kind, nf.component); + nf.face_names = solidcraft_doc::face_point_names(&s.doc, &s.model.state_before(id), &nf.kind, nf.component)?; } if let Some(slot) = s.doc_mut().feature_mut(id) { *slot = nf; diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index c54ef1f2e..1c30a85fa 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -290,17 +290,17 @@ fn redefine_keeps_allocator_above_component_and_occurrence_ids() { assert!( matches!(&s.doc.features[combine_index + 1].kind, solidcraft_doc::FeatureKind::BodyTransfer { bodies, to, .. } if bodies == &["Base"] && *to == destination) ); - assert!((solidcraft_kernel::measure(&s.world_state().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); - assert_eq!(s.world_state().bodies.len(), 1); + assert!((solidcraft_kernel::measure(&s.world_state().unwrap().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); run(&mut s, "timeline.rollback", json!({"position":combine_index + 1})); - assert_eq!(s.world_state().body("Base").unwrap().component, 0, "the result transfers only AFTER Combine"); + assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, 0, "the result transfers only AFTER Combine"); run(&mut s, "edit.undo", json!({})); run(&mut s, "edit.undo", json!({})); assert_eq!(*s.doc, *original); run(&mut s, "edit.redo", json!({})); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert_eq!(reopened.world_state().body("Base").unwrap().component, destination); - assert!((solidcraft_kernel::measure(&reopened.world_state().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); + assert_eq!(reopened.world_state().unwrap().body("Base").unwrap().component, destination); + assert!((solidcraft_kernel::measure(&reopened.world_state().unwrap().body("Base").unwrap().body).unwrap().volume - 6000.0).abs() < 1e-6); let max_id = s.doc.components.iter().map(|c| c.id).chain(s.doc.occurrences.iter().map(|o| o.id)).chain(s.doc.features.iter().map(|f| f.id)).max().unwrap(); assert!(s.doc.next_id > max_id); @@ -332,7 +332,7 @@ fn redefine_cannot_publish_a_second_transfer_that_breaks_existing_ownership() { assert_eq!(s.pending_moves, pending); } let reopened = Session::new(solidcraft_doc::Document::from_json(&full).unwrap()); - assert_eq!(reopened.world_state().body("Base").unwrap().component, reopened.doc.find_component("Original").unwrap()); + assert_eq!(reopened.world_state().unwrap().body("Base").unwrap().component, reopened.doc.find_component("Original").unwrap()); assert!(reopened.doc.features.iter().all(|feature| reopened.model.result(feature.id).is_some_and(|result| result.error.is_none()))); } diff --git a/crates/engine/src/cmd/face_join_tests.rs b/crates/engine/src/cmd/face_join_tests.rs index 7ebd9a7a1..49a563884 100644 --- a/crates/engine/src/cmd/face_join_tests.rs +++ b/crates/engine/src/cmd/face_join_tests.rs @@ -81,13 +81,13 @@ fn face_join_maps_the_picked_instance_body_and_point_together() { run(&mut s, "component.activate", json!({"component":0})); let occurrence = run(&mut s, "occurrence.copy", json!({"component":component,"translate":[100,0,0]}))["occurrence"].as_u64().unwrap(); run(&mut s, "component.activate", json!({"component":component,"occurrence":occurrence})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.iter().find(|body| body.body.contains(Vec3::new(139.0, 15.0, 10.0))).unwrap().name.clone(); assert_ne!(body, "Wall", "exercise an instance body name"); let result = run(&mut s, "solid.extrude", json!({"face":[140,15,10],"face_body":body,"distance":10,"operation":"join"})); let FeatureKind::Extrude { targets, .. } = &s.doc.feature(result["feature"].as_u64().unwrap()).unwrap().kind else { panic!("extrude") }; assert_eq!(targets, &["Wall"]); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), 2); for point in [Vec3::new(49.0, 15.0, 10.0), Vec3::new(149.0, 15.0, 10.0)] { assert!(world.bodies.iter().any(|body| body.body.contains(point)), "{point:?}"); diff --git a/crates/engine/src/cmd/face_tests.rs b/crates/engine/src/cmd/face_tests.rs index c180e83e2..5af20f9c2 100644 --- a/crates/engine/src/cmd/face_tests.rs +++ b/crates/engine/src/cmd/face_tests.rs @@ -113,7 +113,7 @@ fn generated_profiles_and_press_pull_convert_rotated_occurrence_picks_once() { run(&mut s, "edit.redo", json!({})); assert_eq!(s.doc.to_json(), after_cut); check(&mut s, area * height, hole, height); - let world = s.world_state(); + let world = s.world_state().unwrap(); let occupied = Vec3::new(35.0, 21.0 - height, 15.0); let absent = Vec3::new(35.0, 19.0 - height, 15.0); assert!(world.bodies.iter().any(|body| body.body.contains(occupied))); @@ -124,7 +124,7 @@ fn generated_profiles_and_press_pull_convert_rotated_occurrence_picks_once() { let before_volume: f64 = world.bodies.iter().map(|body| solidcraft_kernel::measure(&body.body).unwrap().volume).sum(); let before_bounds: Vec<_> = world.bodies.iter().map(|body| (body.name.clone(), body.mesh().bounds())).collect(); let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); - let after = reopened.world_state(); + let after = reopened.world_state().unwrap(); assert!(after.bodies.iter().any(|body| body.body.contains(occupied))); let v: f64 = after.bodies.iter().map(|body| solidcraft_kernel::measure(&body.body).unwrap().volume).sum(); assert!((v - area * height).abs() < area * height * 1e-4); @@ -191,7 +191,7 @@ fn repeated_source_face_profile_requires_and_uses_the_exact_active_occurrence() assert_eq!(s.doc.to_json(), before); run(&mut s, "component.activate", json!({"component":cid,"occurrence":occurrence})); run(&mut s, "solid.extrude", json!({"face":[55,5,10],"distance":5,"operation":"new"})); - let state = s.world_state(); + let state = s.world_state().unwrap(); for x in [5.0, 55.0] { assert!(state.bodies.iter().any(|body| body.body.contains(Vec3::new(x, 5.0, 14.0)))); assert!(!state.bodies.iter().any(|body| body.body.contains(Vec3::new(x, 5.0, 16.0)))); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 11af84fa2..15616d467 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -179,8 +179,12 @@ const START_PROBE_MM: f64 = 0.1; /// "Goes into a body" is decided where the extrude starts: just past the profile in the /// direction it grows, or halfway along it. With the halfway point alone, a cut dragged far /// past a body's far side read as a Join (#1257). -pub fn auto_operation(s: &Session, p: &Value) -> Option<&'static str> { - auto_operation_in(s, p, true) +/// +/// Faces picked in the world are probed in the placed model; one that cannot be placed is the +/// error. +pub fn auto_operation(s: &Session, p: &Value) -> Result> { + let st = if grouped_face(p).is_some() { s.world_state()? } else { s.model.state() }; + Ok(auto_operation_in(s, p, &st)) } impl Session { @@ -193,17 +197,22 @@ impl Session { } } -fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'static str> { +/// The first of an extrude's grouped face picks. +fn grouped_face(p: &Value) -> Option { + p.get("faces").and_then(Value::as_array).and_then(|faces| faces.first()).and_then(vec3) +} + +/// [`auto_operation`] probing the model `st`. +fn auto_operation_in(s: &Session, p: &Value, st: &solidcraft_doc::ModelState) -> Option<&'static str> { let symmetric = p.get("to").is_none() && str_(p, "direction").is_some_and(|d| d.eq_ignore_ascii_case("symmetric")); // Imported face groups can belong to a child of an empty active component. // Probe in the same coordinate frame as the face picks. - let grouped = p.get("faces").and_then(Value::as_array).and_then(|faces| faces.first()).and_then(vec3); - let st = if grouped.is_some() && world_faces { s.world_state() } else { s.model.state() }; + let grouped = grouped_face(p); // The body the extrude starts on, when it is in a component inside the active one: it takes // part as the active component's own bodies do (#5679). let mut started_on = None; let (base, n) = if let Some(point) = grouped { - let (mesh, index, distance, name) = super::face::face_at_state(&st, point, str_(p, "face_body")).ok().flatten()?; + let (mesh, index, distance, name) = super::face::face_at_state(st, point, str_(p, "face_body")).ok().flatten()?; if distance > (mesh.bounds().diagonal() * 1e-3).max(1e-3) * 10.0 { return None; } @@ -663,7 +672,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> } else if pts.is_empty() { Vec::new() } else { - solidcraft_doc::face_point_names(&s.doc, &s.model.state(), &kind, s.active_component) + solidcraft_doc::face_point_names(&s.doc, &s.model.state(), &kind, s.active_component)? } }; // Primitives have no `targets` of their own: their `targets` are the bodies taking part (#259). @@ -820,7 +829,9 @@ fn extrude(s: &mut Session, p: &Value) -> Result { _ => None, }; let operation = match str_(p, "operation") { - Some(o) if o.eq_ignore_ascii_case("auto") => Operation::parse(auto_operation_in(s, p, false).unwrap_or("new")).unwrap_or(Operation::NewBody), + Some(o) if o.eq_ignore_ascii_case("auto") => { + Operation::parse(auto_operation_in(s, p, &s.model.state()).unwrap_or("new")).unwrap_or(Operation::NewBody) + } _ => operation(p, cmd)?, }; let mut targets = string_list(p, "targets"); @@ -3079,8 +3090,8 @@ mod corner_tests { let (default, reply) = cornered(None); assert_eq!(reply["warning"], json!(null), "{reply}"); let (rolling, _) = cornered(Some("rolling")); - let ball = default.world_state().body("B").unwrap().body.clone(); - let same = rolling.world_state().body("B").unwrap().body.clone(); + let ball = default.world_state().unwrap().body("B").unwrap().body.clone(); + let same = rolling.world_state().unwrap().body("B").unwrap().body.clone(); // `corner: rolling` is the default: the same body, to the last bit of its area. assert_eq!(solidcraft_kernel::measure(&ball).unwrap().area, solidcraft_kernel::measure(&same).unwrap().area); assert!(solidcraft_kernel::measure(&ball).unwrap().volume > 7000.0); diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs index df4ee9844..f5aa6e430 100644 --- a/crates/engine/src/cmd/features_more.rs +++ b/crates/engine/src/cmd/features_more.rs @@ -189,7 +189,7 @@ fn emboss(s: &mut Session, p: &Value) -> Result { let face = if let Some(value) = p.get("face") { let local = vec3(value).ok_or_else(|| bad(cmd, "`face` must be a finite point [x,y,z]"))?; let at = solidcraft_doc::apply_point(&s.active_component_frame(), local); - let state = s.world_state(); + let state = s.world_state()?; let mut candidates = Vec::new(); // The nearest face off the point: (distance, body), for the error when none holds it. let mut nearest: Option<(f64, &str)> = None; @@ -328,7 +328,7 @@ fn infer_emboss_selection( let regions = solidcraft_doc::select_profiles(ss, profiles).map_err(|e| bad(cmd, e.to_string()))?; let sketch_owner = s.doc.feature(sketch).map(|f| f.component).ok_or_else(|| bad(cmd, "profile sketch no longer exists"))?; let d = s.doc.eval(&s.doc.with_design_unit(depth, Kind::Length), Kind::Length).map_err(|e| bad(cmd, e.to_string()))?; - let world = s.world_state(); + let world = s.world_state()?; let placed = s.placed_document(); let mut chosen = None; let mut faces = 0usize; @@ -448,7 +448,7 @@ fn align(s: &mut Session, p: &Value) -> Result { if let Some(o) = p.get(pk).filter(|v| v.is_object()) { let at = o.get("at").and_then(vec3).ok_or_else(|| bad(cmd, format!("`{pk}.at` must be [x, y, z]")))?; let kind = o.get("snap").and_then(Value::as_str).unwrap_or("vertex"); - return snap_point(s, kind, at).map(|q| (q, None)).ok_or_else(|| bad(cmd, format!("no {kind} to snap to near `{pk}`"))); + return snap_point(&*s.world_state()?, kind, at).map(|q| (q, None)).ok_or_else(|| bad(cmd, format!("no {kind} to snap to near `{pk}`"))); } p.get(pk) .and_then(vec3) @@ -505,9 +505,8 @@ fn remove(s: &mut Session, p: &Value) -> Result { mod tests; /// A snap point near `at` on the model: the nearest vertex, edge midpoint, planar face's centre -/// or circular edge's centre (the end of a cylindrical face). -pub(super) fn snap_point(s: &Session, kind: &str, at: Vec3) -> Option { - let st = s.world_state(); +/// or circular edge's centre (the end of a cylindrical face) of the placed model `st`. +pub(super) fn snap_point(st: &solidcraft_doc::ModelState, kind: &str, at: Vec3) -> Option { let near = |pts: Vec| pts.into_iter().min_by(|a, b| a.dist(at).total_cmp(&b.dist(at))); match kind { "vertex" => near( diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 5dfe90f1c..58e502b51 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -17,14 +17,14 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() { for (height, expected) in [(8., "cut"), (12., "join")] { let params = json!({"faces":[[offset+2.,2,10],[offset+8.,8,10]],"face_body":"Stock", "to":[offset+5.,5,height],"direction":"negative"}); - assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected)); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some(expected)); } for distance in [-2., 2.] { let mut params = json!({"faces":[[offset+2.,2,10],[offset+8.,8,10]],"distance":distance}); let expected = if distance < 0. { "cut" } else { "join" }; - assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected)); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some(expected)); params["face_body"] = json!("Stock"); - assert_eq!(crate::auto_operation(&s, ¶ms), Some(expected)); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some(expected)); let mut actual = s.scratch(); if offset != 0. { run(&mut actual, "component.activate", json!({"component":part["component"]})); @@ -54,7 +54,7 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() { let mut params = json!({"faces":[[32,2,10],[38,8,10]],"face_body":"Stock","distance":-2}); // The picked part takes part beside the active component's own body (#5679): going in cuts // it, and the top level's own body is left alone. - assert_eq!(crate::auto_operation(&s, ¶ms), Some("cut"), "the picked body takes part beside the active component's own"); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some("cut"), "the picked body takes part beside the active component's own"); for operation in ["auto", "cut"] { let mut t = s.scratch(); let mut p = params.clone(); @@ -69,9 +69,9 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() { ); } params["participants"] = json!(["Stock"]); - assert_eq!(crate::auto_operation(&s, ¶ms), Some("cut")); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some("cut")); params["participants"] = json!(["Other"]); - assert_eq!(crate::auto_operation(&s, ¶ms), Some("join")); + assert_eq!(crate::auto_operation(&s, ¶ms).unwrap(), Some("join")); } /// A part inserted into a new design (a STEP file) sits in its own component under the empty @@ -628,6 +628,7 @@ fn cylinder_cross_component_emboss_keeps_source_owner_and_placements() { let placements = serde_json::to_value(&s.doc.occurrences).unwrap(); let target = s .world_state() + .unwrap() .bodies .iter() .find(|b| { @@ -658,7 +659,7 @@ fn cylinder_cross_component_emboss_keeps_source_owner_and_placements() { let selected = s.doc.features.last().unwrap().face_names.first().unwrap(); assert!(!selected.is_empty() && source_names.contains(selected), "{selected:?} not in {source_names:?}"); assert!((exact_cylinder_volume(&s) - before - 21.).abs() < 0.02); - let world = s.world_state(); + let world = s.world_state().unwrap(); for x in [39.5, 119.5] { assert!( world.bodies.iter().any(|b| b @@ -816,6 +817,7 @@ fn check_body_offset(auto: bool) { assert_eq!(s.doc.body_component("Sleeve", s.model.state().body("Sleeve").unwrap().feature), holder); assert!( s.world_state() + .unwrap() .body("Sleeve") .unwrap() .body @@ -1320,7 +1322,7 @@ fn cutting_a_text_removes_each_letter_whether_its_letters_stand_apart_or_touch() } else { run(&mut s, "sketch.text", json!({"text":text,"at":[5,12],"height":14})); } - let state = s.world_state(); + let state = s.world_state().unwrap(); let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); // The profiles cut: the letters, not their counters (the inside of an O, whose outline // is a hole of its letter). @@ -1335,7 +1337,7 @@ fn cutting_a_text_removes_each_letter_whether_its_letters_stand_apart_or_touch() run(&mut s, "solid.extrude", json!({"distance":2,"operation":"cut"})); let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); assert!((volume - (200.0 * 40.0 * 10.0 - 2.0 * area)).abs() < 1e-3 * area, "{text:?}: {volume} for {area} mm² cut 2 mm deep"); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } } @@ -1353,7 +1355,7 @@ fn a_tapered_text_joins_a_block_on_its_face_or_hanging_over_its_edge() { run(&mut s, "solid.extrude", json!({"distance":-10})); run(&mut s, "sketch.create", json!({"plane":"XY"})); run(&mut s, "sketch.text", json!({"text":"tres long","at":at,"height":8})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); // The letters' area, counters left out (a letter's hole is its own profile too). let sorted = |ids: &[String]| { @@ -1370,7 +1372,7 @@ fn a_tapered_text_joins_a_block_on_its_face_or_hanging_over_its_edge() { let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); let (block, text) = (200.0 * 40.0 * 10.0, 2.0 * area); assert!(volume > block + text && volume < block + 1.3 * text, "hanging {hanging}: {volume} for {text} mm³ of straight text"); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } } @@ -1445,7 +1447,7 @@ fn a_tapered_foot_under_a_part_joins_as_drawn() { // for a hair first. let tol = if round || half < 15.0 { 2e-4 } else { 1e-9 } * (part + frustum); assert!((v - (part + frustum)).abs() < tol, "round {round}, half {half}, taper {taper}: {v} for {}", part + frustum); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); let state = s.model.state(); let mesh = state.body("B").unwrap().mesh(); // Beside the part, above the foot's start: nothing. @@ -1826,7 +1828,7 @@ fn a_line_of_text_cuts_into_a_block_at_any_depth() { run(&mut s, "solid.extrude", json!({"distance":-40})); run(&mut s, "sketch.create", json!({"plane":"XY"})); run(&mut s, "sketch.text", json!({"text":"textvraiment tres long","at":[3,9],"height":7.81})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); // The letters' area, counters left out (a letter's hole is its own profile too). let sorted = |ids: &[String]| { @@ -1840,7 +1842,7 @@ fn a_line_of_text_cuts_into_a_block_at_any_depth() { run(&mut s, "solid.extrude", json!({"distance":-depth,"operation":"cut"})); let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); removed.push((105.0 * 26.0 * 40.0 - volume) / depth); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } let (shallow, deep) = (removed[0], removed[1]); assert!((deep - shallow).abs() < 1e-3 * shallow, "{shallow} mm² taken out at 1 mm, {deep} mm² at 3.5 mm"); @@ -1863,7 +1865,7 @@ fn fillets_on_tapered_bosses_saved_before_still_find_their_edges() { } // The build that saved it measured 69454.885209 mm³. assert!((volume - 69454.8852092132).abs() < 1e-3, "{volume}"); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); } /// #1360: a ring drawn round a hole, its inner circle on the hole's wall, cut into a chamfered diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 02c6e4e27..cab0ffc50 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -262,7 +262,11 @@ fn insert_step(s: &mut Session, p: &Value) -> Result { if let Some(m) = placement { let occ = out["occurrence"].as_u64().ok_or_else(|| EngineError::Other("the import has no placement to move".into()))?; if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) { - o.transform = solidcraft_doc::mat_mul(&m, &o.transform); + let placed = solidcraft_doc::mat_mul(&m, &o.transform); + if !solidcraft_doc::is_placement(&placed) { + return Err(bad(cmd, "`matrix` moves the import out of a rigid placement within 1e9 mm")); + } + o.transform = placed; out["transform"] = json!(o.transform); } s.refresh(); @@ -610,7 +614,7 @@ fn export_to(s: &Session, path: &str, format: Format, bodies: &[String], quality } else { // Bodies carry the colour they are shown in (appearance, material or imported), and the // file the design's properties where the format has a place for them. - solidcraft_io::export_with_quality(&s.doc.painted(&s.world_state()), bodies, format, &name, &s.doc.metadata, quality)? + solidcraft_io::export_with_quality(&s.doc.painted(&*s.world_state()?), bodies, format, &name, &s.doc.metadata, quality)? }; solidcraft_io::vfs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; Ok(json!({"path": path, "bytes": bytes.len(), "format": format!("{format:?}")})) @@ -972,7 +976,7 @@ mod tests { let input = target.join("issue303-step.json"); let doc = solidcraft_io::read_design(&std::fs::read(input).unwrap()).unwrap(); let mut session = Session::new(doc); - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } let mut samples = [Vec::new(), Vec::new()]; @@ -1011,7 +1015,7 @@ mod tests { let mut s = Session::default(); s.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); assert!(saved_preview(&s).is_none(), "save must not triangulate a cold body"); - let state = s.world_state(); + let state = s.world_state().unwrap(); for body in &state.bodies { body.mesh(); } @@ -1062,19 +1066,19 @@ mod tests { assert!(saved_preview(&s).is_none()); assert!(saved_geometry(&s, &s.doc).is_some(), "the timeline's bodies need no placement"); assert!(s.world_cache.lock().unwrap().is_none(), "saving must not prepare cold placements"); - for body in &s.world_state().bodies { + for body in &s.world_state().unwrap().bodies { body.mesh(); } assert!(saved_preview(&s).is_some()); s.execute("occurrence.move", &json!({"occurrence":occurrence,"translate":[10,0,0],"capture":false})).unwrap(); - for body in &s.world_state().bodies { + for body in &s.world_state().unwrap().bodies { body.mesh(); } assert!(!s.pending_moves.is_empty()); assert!(saved_preview(&s).is_none(), "uncaptured positions are not in the saved document"); assert!(saved_geometry(&s, &s.doc).is_none()); s.execute("component.capture_position", &json!({})).unwrap(); - for body in &s.world_state().bodies { + for body in &s.world_state().unwrap().bodies { body.mesh(); } let preview = saved_preview(&s).unwrap(); @@ -1082,7 +1086,7 @@ mod tests { assert!((min_x - 10.0).abs() < 1e-9); let mut editing = s.scratch(); editing.execute("sketch.create", &json!({"plane":"XY"})).unwrap(); - for body in &editing.world_state().bodies { + for body in &editing.world_state().unwrap().bodies { body.mesh(); } assert!(editing.active_sketch.is_some()); @@ -1096,7 +1100,7 @@ mod tests { crate::capture::install_test_renderer(); let mut session = Session::new(Document::new("Cache opt-in")); session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); for body in &world.bodies { body.mesh(); } @@ -1150,7 +1154,7 @@ mod tests { fn saved_model_needs_no_meshes_and_is_adopted_only_for_its_document() { let mut session = Session::new(Document::new("Saved model")); session.execute("solid.box", &json!({"length":10,"width":20,"height":30})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); let bytes = session.design_container(solidcraft_io::DesignCompression::Fast, false, true).unwrap(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none()), "saving the model must not triangulate"); @@ -1230,7 +1234,7 @@ mod tests { let target = std::env::var_os("CARGO_TARGET_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| std::path::PathBuf::from("target")); let input = std::env::var_os("SOLIDCRAFT_BENCH_FILE").map(std::path::PathBuf::from).unwrap_or_else(|| target.join("issue303-step.json")); let mut session = Session::new(solidcraft_io::read_design(&std::fs::read(input).unwrap()).unwrap()); - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } let modes = [("json", false, "fast"), ("container", false, "fast"), ("container", true, "fast"), ("container", true, "compact")]; @@ -1272,7 +1276,7 @@ mod tests { assert_eq!(result["errors"], 0); let reconstructed = start.elapsed().as_secs_f64() * 1000.; let mut triangles = 0; - let world = session.world_state(); + let world = session.world_state().unwrap(); for body in &world.bodies { triangles += body.mesh().triangles.len(); } @@ -1410,14 +1414,14 @@ mod tests { let mut opened = Session::default(); watch(progress.clone(), || opened.execute("doc.open", &json!({"path":path}))).unwrap(); assert_eq!(progress.features(), (3, 3)); - assert_eq!(opened.world_state().bodies.len(), 3); + assert_eq!(opened.world_state().unwrap().bodies.len(), 3); let progress = Arc::new(Progress::default()); progress.cancel(); let mut stopped = Session::default(); watch(progress, || stopped.execute("doc.open", &json!({"path":path}))).unwrap(); assert!(stopped.model.results.iter().all(|r| r.skipped), "no feature was rebuilt after Cancel"); - assert!(stopped.world_state().bodies.is_empty()); + assert!(stopped.world_state().unwrap().bodies.is_empty()); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/src/cmd/file_thumbnail.rs b/crates/engine/src/cmd/file_thumbnail.rs index bc3c4ff95..10eb92710 100644 --- a/crates/engine/src/cmd/file_thumbnail.rs +++ b/crates/engine/src/cmd/file_thumbnail.rs @@ -62,7 +62,7 @@ mod tests { session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30,"body_name":"Visible"})).unwrap(); session.execute("solid.box", &serde_json::json!({"length":100,"width":100,"height":100,"body_name":"Hidden"})).unwrap(); session.execute("browser.visibility", &serde_json::json!({"items":["Hidden"],"visible":false})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); for body in &world.bodies { body.mesh(); } @@ -85,7 +85,7 @@ mod tests { crate::capture::install_test_renderer(); let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); - let world = session.world_state(); + let world = session.world_state().unwrap(); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); assert!(saved(&session).is_none()); assert!(world.bodies.iter().all(|b| b.cached_mesh().is_none())); @@ -106,7 +106,7 @@ mod tests { fn without_a_renderer_a_save_has_no_thumbnail() { let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } let (scene, camera) = scene(&session).unwrap(); diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 288c13ed4..189e7e681 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -104,7 +104,7 @@ fn measure(s: &mut Session, p: &Value) -> Result { return super::measure_sel::measure_items(s, items); } let want = string_list(p, "bodies"); - let st = s.world_state(); + let st = s.world_state()?; let selected: Vec<_> = st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).collect(); // Each body is measured on its own: on all cores, in body order. let mut bodies: Vec = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_json(b)) @@ -168,11 +168,10 @@ fn measure(s: &mut Session, p: &Value) -> Result { ) } -fn sketch_json(s: &Session, id: u64) -> Option { +/// Sketch `id`, placed where the placed model `world` has it (its component's placement). +fn sketch_json(s: &Session, world: &solidcraft_doc::ModelState, id: u64) -> Option { let state = s.model.state(); let ss = state.sketch(id)?; - // Where the sketch is in the world (its component's placement). - let world = s.world_state(); let plane = world.sketch(id).map(|w| w.plane).unwrap_or(ss.plane); let sk = &ss.sketch; let curves: Vec = sk @@ -250,7 +249,7 @@ fn sketch_inspect(s: &mut Session, p: &Value) -> Result { _ => s.active_sketch, } .ok_or_else(|| bad("sketch.inspect", "no such sketch (and none is active)"))?; - sketch_json(s, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into())) + sketch_json(s, &*s.world_state()?, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into())) } /// Revisions of every design of this run (#6646). @@ -369,7 +368,7 @@ fn body_of<'a>(st: &'a solidcraft_doc::ModelState, p: &Value, cmd: &str) -> Resu } fn model_edges(s: &mut Session, p: &Value) -> Result { - let st = s.world_state(); + let st = s.world_state()?; let b = body_of(&st, p, "model.edges")?; let tol = (b.body.size() * 2e-3).max(1e-3); let names = solidcraft_doc::naming::edge_names(b); @@ -383,7 +382,7 @@ fn model_edges(s: &mut Session, p: &Value) -> Result { } fn model_faces(s: &mut Session, p: &Value) -> Result { - let st = s.world_state(); + let st = s.world_state()?; let b = body_of(&st, p, "model.faces")?; let names = solidcraft_doc::naming::face_names(b); let tol = (b.body.size() * 2e-3).max(1e-3); @@ -436,7 +435,7 @@ fn commands(s: &mut Session, _p: &Value) -> Result { } fn model_threads(s: &mut Session, _p: &Value) -> Result { - let st = s.world_state(); + let st = s.world_state()?; Ok(json!({ "threads": st.threads })) } diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rs index 8cdff4992..117d59fc6 100644 --- a/crates/engine/src/cmd/interference.rs +++ b/crates/engine/src/cmd/interference.rs @@ -72,7 +72,7 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { }; let budget = std::time::Duration::from_secs_f64(budget_s); let want = string_list(p, "bodies"); - let st = s.world_state(); + let st = s.world_state()?; let (meshes_left, bodies): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).partition(|b| b.body.is_mesh()); diff --git a/crates/engine/src/cmd/interference_tests.rs b/crates/engine/src/cmd/interference_tests.rs index 2be9c0383..09feb1c93 100644 --- a/crates/engine/src/cmd/interference_tests.rs +++ b/crates/engine/src/cmd/interference_tests.rs @@ -70,7 +70,7 @@ fn a_piece_of_a_body_inside_another_is_still_found() { run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Block"})); run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [5, 5, 5], "operation": "new", "body_name": "Pieces"})); run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [30, 5, 5], "operation": "join", "targets": ["Pieces"]})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let pieces = st.bodies.iter().find(|b| b.name == "Pieces").map(|b| b.body.shell_count()); assert_eq!(pieces, Some(2), "the two cubes are one body in two pieces"); let i = run(&mut s, "inspect.interference", json!({})); @@ -122,7 +122,7 @@ pub(super) fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); } let _ = std::fs::remove_dir_all(&dir); - s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() + s.world_state().unwrap().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() } /// #3249: mesh bodies (STL, 3MF, OBJ imports) are not intersected, but they used to vanish from diff --git a/crates/engine/src/cmd/loft_rails_tests.rs b/crates/engine/src/cmd/loft_rails_tests.rs index eca940d01..45a33464f 100644 --- a/crates/engine/src/cmd/loft_rails_tests.rs +++ b/crates/engine/src/cmd/loft_rails_tests.rs @@ -56,7 +56,7 @@ fn setup() -> Session { } fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { - solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() + solidcraft_kernel::measure(&s.world_state().unwrap().body(body).unwrap().body).unwrap() } fn loft(s: &mut Session, body: &str, extra: Value) -> Result { diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rs index 97665bb43..7121885d7 100644 --- a/crates/engine/src/cmd/measure_sel.rs +++ b/crates/engine/src/cmd/measure_sel.rs @@ -269,8 +269,8 @@ fn face_slot(b: &solidcraft_doc::ModelBody, m: &Mesh, shape: &Shape, pts: &[Vec3 super::measure_shape::slot_from_faces(shape, pts, &surfaces) } -fn describe(s: &Session, sel: &Sel) -> Option { - let st = s.world_state(); +/// `sel` in the placed model `st`. +fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option { let plain = |geo, dir, json| Some(Item { geo, dir, json, shape: Shape::Other, slot: None }); match sel { Sel::Vertex { point, .. } => Some(Item { @@ -342,8 +342,8 @@ fn describe(s: &Session, sel: &Sel) -> Option { let v = m.measure().volume; plain(Geo::Tris(tris), None, json!({"type": "body", "name": name, "closed": closed, "volume_mm3": closed.then_some(v)})) } - Sel::SketchCurve { id, sketch } => sketch_curve(sketch_of(s, &st, *sketch, |sk| sk.curve_index(id).is_some())?, id), - Sel::ExternalSketchCurve { sketch, id } => sketch_curve(sketch_of(s, &st, Some(*sketch), |_| true)?, id), + Sel::SketchCurve { id, sketch } => sketch_curve(sketch_of(s, st, *sketch, |sk| sk.curve_index(id).is_some())?, id), + Sel::ExternalSketchCurve { sketch, id } => sketch_curve(sketch_of(s, st, Some(*sketch), |_| true)?, id), Sel::SketchPoint { id } | Sel::ExternalSketchPoint { id, .. } => { let given = match sel { Sel::ExternalSketchPoint { sketch, .. } => Some(*sketch), @@ -354,7 +354,7 @@ fn describe(s: &Session, sel: &Sel) -> Option { Some((k, p)) if given.is_none() => (Some(k), p), _ => (given, id.as_str()), }; - let ss = sketch_of(s, &st, given, |sk| sk.point_index(id).is_some())?; + let ss = sketch_of(s, st, given, |sk| sk.point_index(id).is_some())?; let p = ss.plane.to_world(ss.sketch.points.get(ss.sketch.point_index(id)?)?.pos); Some(Item { geo: Geo::Points(vec![p]), @@ -479,7 +479,7 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result { if list.is_empty() || list.len() > 1000 { return Err(bad(cmd, "measure one or two items")); } - let st = s.world_state(); + let st = s.world_state()?; let mut sels = Vec::new(); for value in list { let sel = match value.get("type").and_then(Value::as_str) { @@ -498,10 +498,12 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result { return Err(bad(cmd, "measure one or two items")); } } + let world = s.world_state()?; let mut described = Vec::new(); for x in &sels { described.push( - describe(s, x).ok_or_else(|| bad(cmd, "an item can't be measured (pick vertices, edges, faces, bodies, sketch curves or profiles)"))?, + describe(s, &world, x) + .ok_or_else(|| bad(cmd, "an item can't be measured (pick vertices, edges, faces, bodies, sketch curves or profiles)"))?, ); } let mut out = json!({"items": described.iter().map(|d| d.json.clone()).collect::>()}); diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index 4c2a1c603..0800dd11d 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -1066,7 +1066,11 @@ fn explode_show(s: &mut Session, p: &Value) -> Result { } let i = view_index(s, p, cmd)?; let v = s.doc.assembly.exploded.get(i).cloned().ok_or_else(|| bad(cmd, "view"))?; - s.pending_moves = exploded_at(&explode_moves(s, &v), 1.0); + let moves = exploded_at(&explode_moves(s, &v), 1.0); + if !moves.values().all(solidcraft_doc::is_placement) { + return Err(bad(cmd, format!("exploded view `{}` moves an occurrence out of range", v.name))); + } + s.pending_moves = moves; s.revision += 1; Ok(json!({"view": v.id, "name": v.name})) } diff --git a/crates/engine/src/cmd/motion_animation.rs b/crates/engine/src/cmd/motion_animation.rs index 4c820a433..a1b58f0ef 100644 --- a/crates/engine/src/cmd/motion_animation.rs +++ b/crates/engine/src/cmd/motion_animation.rs @@ -98,11 +98,11 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - Motion::Explode(moves, _) => { let mut t = s.scratch(); t.pending_moves.clear(); - let assembled = crate::view::bounds(&t); + let assembled = crate::view::bounds(&t)?; t.pending_moves = exploded_at(moves, 1.0); - let mut c = crate::view::home_camera(&t); - c.fit(&assembled.union(&crate::view::bounds(&t))); - c + let mut c = crate::view::home_camera(&t)?; + c.fit(&assembled.union(&crate::view::bounds(&t)?)); + Ok(c) } Motion::Drive(..) => crate::view::home_camera(s), }; @@ -144,7 +144,7 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - t.pending_moves = exploded_at(moves, if *back { 1.0 - (2.0 * u - 1.0).abs() } else { u }); } } - let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides); + let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides)?; let picture = capture::rgba_with(Some(renderer), &scene, &cam, width, height).map_err(|e| bad(cmd, e))?; drawn_by = picture.renderer; if gif { @@ -178,8 +178,11 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) - /// The camera the frames are drawn from: the session's (`view.apply`), or `home` framing the /// model, with the fields `given` sets (`ui.camera`'s reply sets them all). -fn camera(s: &Session, home: impl FnOnce() -> Camera, given: Option<&Value>, cmd: &str) -> Result { - let base = s.camera.unwrap_or_else(home); +fn camera(s: &Session, home: impl FnOnce() -> Result, given: Option<&Value>, cmd: &str) -> Result { + let base = match s.camera { + Some(c) => c, + None => home()?, + }; let Some(given) = given else { return Ok(base) }; let fields = given.as_object().ok_or_else(|| bad(cmd, "`camera` must be an object, such as ui.camera's reply"))?; let mut v = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?; diff --git a/crates/engine/src/cmd/motion_tests.rs b/crates/engine/src/cmd/motion_tests.rs index f4e88fb36..bdae0d4b4 100644 --- a/crates/engine/src/cmd/motion_tests.rs +++ b/crates/engine/src/cmd/motion_tests.rs @@ -648,7 +648,7 @@ fn exploded_views_show_without_changing_the_design() { run(&mut s, "explode.show", json!({"view": "Apart"})); // Centres at x 5 and 25 → middle 15: each moves 10 mm further out. let bb = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["bodies"][0]["bbox"]["min"][0].as_f64().unwrap_or(f64::NAN); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); assert!((bb(&mut s, &names[0]) + 10.0).abs() < 1e-6, "{names:?}"); assert!((bb(&mut s, &names[1]) - 30.0).abs() < 1e-6); assert_eq!(s.doc.occurrences, before, "shown only"); diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index 5b3c2df45..363487c8c 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -248,7 +248,7 @@ fn instance_selection_delete_removes_only_selected_instance() { run(&mut s, "selection.delete", json!({"items": items})); assert!(s.doc.occurrences.iter().any(|o| o.id == first)); assert!(!s.doc.occurrences.iter().any(|o| o.id == second)); - assert_eq!(s.world_state().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); assert!(s.doc.components.iter().any(|c| c.id == component)); } @@ -343,7 +343,7 @@ fn synthesized_name_collision_keeps_source_and_instance_separate() { let instance = s.occurrence_bodies(&[second], false).unwrap()[0].clone(); assert_ne!(instance, candidate); let frames = s.doc.body_frames(&s.model.state()); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(frames.iter().all(|(name, _, _, _)| world.body(name).is_some())); assert_eq!(world.bodies.len(), world.bodies.iter().map(|b| &b.name).collect::>().len()); run(&mut s, "browser.visibility", json!({"visible":false,"paths":[[second]]})); @@ -556,10 +556,10 @@ fn instance_styles_follow_source_identity_after_collision_rename_and_pending_mov let instance = s.occurrence_bodies(&[second], false).unwrap()[0].clone(); let source = s.occurrence_placement(&[second]).unwrap().bodies[0].source.clone(); run(&mut s, "material.assign", json!({"bodies":[instance],"material":"Brass"})); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(s.doc.body_color(world.body(&instance).unwrap()), s.doc.body_color(world.body(&source).unwrap())); run(&mut s, "appearance.assign", json!({"components":[component.to_string()],"color":"#0000ff","opacity":0.7})); - assert_eq!(s.doc.body_color(s.world_state().body(&instance).unwrap()), Some([0.0, 0.0, 1.0])); + assert_eq!(s.doc.body_color(s.world_state().unwrap().body(&instance).unwrap()), Some([0.0, 0.0, 1.0])); run(&mut s, "appearance.assign", json!({"bodies":[instance],"color":"#ff0000","opacity":0.5})); run(&mut s, "appearance.assign", json!({"faces":[{"body":instance,"point":[21,1,2]}],"color":"#00ff00","opacity":0.4})); // Exercise the point-based face fallback as well as persistent face-name matching. @@ -568,7 +568,7 @@ fn instance_styles_follow_source_identity_after_collision_rename_and_pending_mov } run(&mut s, "body.rename", json!({"body":source,"name":"Shared Renamed"})); run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0],"capture":false})); - let world = s.world_state(); + let world = s.world_state().unwrap(); for id in [first, second] { let bodyname = s.occurrence_bodies(&[id], false).unwrap()[0].clone(); let body = world.body(&bodyname).unwrap(); diff --git a/crates/engine/src/cmd/offset_edit_guard_tests.rs b/crates/engine/src/cmd/offset_edit_guard_tests.rs index 87187cb67..dea069997 100644 --- a/crates/engine/src/cmd/offset_edit_guard_tests.rs +++ b/crates/engine/src/cmd/offset_edit_guard_tests.rs @@ -100,10 +100,10 @@ fn offset_guard_live_child_follows_radius_then_retirement_is_honest() { } Ok(_) => { assert!(s.model.results.iter().any(|r| r.error.is_some()), "retired parent must not keep a stale successful child"); - assert!(s.world_state().body("Child").is_none()); + assert!(s.world_state().unwrap().body("Child").is_none()); let reopened = Session::new(Document::from_json(&s.doc.to_json()).unwrap()); assert!(reopened.model.results.iter().any(|r| r.error.is_some())); - assert!(reopened.world_state().body("Child").is_none()); + assert!(reopened.world_state().unwrap().body("Child").is_none()); } } } @@ -174,7 +174,7 @@ fn offset_guard_complete_delete_keeps_dangling_profile_loadable_without_circle_r let check = |s: &Session| { assert!(solved(s, sketch).curve_index("Unrelated").is_some()); assert!(s.model.results.iter().find(|r| r.id == s.doc.find_feature("OffsetBody").unwrap().id).unwrap().error.is_some()); - assert!(s.world_state().body("Selected").is_none(), "dangling selection must never adopt the unrelated circle"); + assert!(s.world_state().unwrap().body("Selected").is_none(), "dangling selection must never adopt the unrelated circle"); }; check(&s); let reopened = Session::new(Document::from_json(&saved).unwrap()); diff --git a/crates/engine/src/cmd/offset_identity_tests.rs b/crates/engine/src/cmd/offset_identity_tests.rs index df7aba63f..7ceb6e55a 100644 --- a/crates/engine/src/cmd/offset_identity_tests.rs +++ b/crates/engine/src/cmd/offset_identity_tests.rs @@ -129,7 +129,7 @@ fn pasted_offset_boundary_has_scoped_identity_and_independent_dimensions_and_mat healthy(&reopened); assert!((volume(&reopened, extrusion) - sharp).abs() < 1e-6); assert!((volume(&reopened, copied_extrusion) - rounded).abs() < 0.002); - let state = reopened.world_state(); + let state = reopened.world_state().unwrap(); let bounds = state.body(&copied_body).unwrap().mesh().bounds(); assert!((bounds.min.x - (100. - 37.6)).abs() < 1e-6); assert!((bounds.max.x - (100. + 37.6)).abs() < 1e-6); diff --git a/crates/engine/src/cmd/offset_topology_tests.rs b/crates/engine/src/cmd/offset_topology_tests.rs index 1d418e1fa..25cf917e5 100644 --- a/crates/engine/src/cmd/offset_topology_tests.rs +++ b/crates/engine/src/cmd/offset_topology_tests.rs @@ -18,7 +18,7 @@ fn breaking_offset_preserves_downstream_material_history_and_source_independence let curves = session.model.state().sketch(sketch).unwrap().sketch.offset_boundary(&association).unwrap(); run(&mut session, "sketch.finish", json!({})); run(&mut session, "solid.extrude", json!({"sketch":sketch,"profiles":{"offset_boundaries":[association]},"distance":2,"operation":"new"})); - let before_volume = session.world_state().bodies.last().unwrap().mesh().measure().volume.abs(); + let before_volume = session.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs(); run(&mut session, "sketch.edit", json!({"sketch":sketch})); let before = session.doc.to_json(); let history = session.undo.len(); @@ -29,17 +29,17 @@ fn breaking_offset_preserves_downstream_material_history_and_source_independence matches!(&session.doc.features.last().unwrap().kind, FeatureKind::Extrude { profiles: ProfileSel::Curves { loops }, .. } if loops == &vec![curves.clone()]) ); let frozen = session.doc.to_json(); - assert!((session.world_state().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); + assert!((session.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); run(&mut session, "edit.undo", json!({})); assert_eq!(session.doc.to_json(), before); run(&mut session, "edit.redo", json!({})); assert_eq!(session.doc.to_json(), frozen); run(&mut session, "parameters.change", json!({"name":radius,"expression":"2 mm"})); assert!(session.model.results.iter().all(|result| result.error.is_none())); - assert!((session.world_state().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); + assert!((session.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); let reopened = Session::new(solidcraft_doc::Document::from_json(&session.doc.to_json()).unwrap()); assert!(reopened.model.results.iter().all(|result| result.error.is_none())); - assert!((reopened.world_state().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); + assert!((reopened.world_state().unwrap().bodies.last().unwrap().mesh().measure().volume.abs() - before_volume).abs() < 1e-6); } } @@ -76,7 +76,7 @@ fn inset_past_corner_radius_creates_a_real_boundary_and_saved_profile_identity() assert!(matches!(&feature.kind, FeatureKind::Extrude { profiles: ProfileSel::OffsetBoundaries { associations }, .. } if associations.len() == 1)); let check = |session: &Session| { assert!(session.model.results.iter().all(|result| result.error.is_none())); - let state = session.world_state(); + let state = session.world_state().unwrap(); let body = state.bodies.last().unwrap(); // The exact inward parallel set is a sharp 73.2 by 63.2 rectangle. let mesh = body.mesh(); diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index 32c6f1afe..8b232798b 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -466,6 +466,9 @@ fn insert(s: &mut Session, p: &Value) -> Result { ); let mut m = m; m[3] = [pt.x, pt.y, pt.z, 1.0]; + if !solidcraft_doc::is_placement(&m) { + return Err(bad(cmd, "`point` must be within 1e9 mm and `direction` finite")); + } if let Some(o) = s.doc_mut().occurrences.iter_mut().find(|o| o.id == occ) { o.transform = m; } @@ -564,7 +567,7 @@ mod tests { } fn bbox(s: &Session, prefix: &str) -> (solidcraft_geom::Vec3, solidcraft_geom::Vec3) { - let st = s.world_state(); + let st = s.world_state().unwrap(); let comp = s.doc.components.iter().find(|c| c.name.starts_with(prefix)).map(|c| c.id).unwrap_or(0); let b = st .bodies diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs index dfe7a459d..1740a09f7 100644 --- a/crates/engine/src/cmd/patterns_tests.rs +++ b/crates/engine/src/cmd/patterns_tests.rs @@ -116,7 +116,7 @@ fn feature_rectangular_center_flip_and_oblique_direction_keep_source_and_recompu }), ); let sign = if flipped { -1.0 } else { 1.0 }; - let st = s.world_state(); + let st = s.world_state().unwrap(); let body = &st.bodies[0].body; // Analytic slots: the source, +1, -1, +2. The second direction is independent. for i in [0.0, 1.0, -1.0, 2.0] { @@ -155,7 +155,7 @@ fn feature_circular_center_flip_uses_partial_arc_endpoints_and_full_circle_spaci }), ); let step = total / if total == 360.0 { 6.0 } else { 5.0 }; - let st = s.world_state(); + let st = s.world_state().unwrap(); for slot in [0.0, 1.0, -1.0, 2.0, -2.0, 3.0] { let a = (step * slot * if flipped { -1.0 } else { 1.0 }).to_radians(); let p = Vec3::new(40.0 + 20.0 * a.cos(), 60.0 + 20.0 * a.sin(), 2.5); diff --git a/crates/engine/src/cmd/render/settings_tests.rs b/crates/engine/src/cmd/render/settings_tests.rs index e55cc49a7..2a0417d64 100644 --- a/crates/engine/src/cmd/render/settings_tests.rs +++ b/crates/engine/src/cmd/render/settings_tests.rs @@ -221,7 +221,7 @@ fn settings_history_preserves_geometry_cache_and_dirty_state() { s.execute("occurrence.move", &json!({"occurrence":component["occurrence"],"translate":[30,0,0]})).unwrap(); s.mark_saved(); let model = s.model.state(); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(!Arc::ptr_eq(&model, &world), "exercise the prepared occurrence cache"); let mesh = model.bodies[0].mesh(); let undo = s.undo.len(); @@ -254,7 +254,7 @@ fn settings_history_preserves_geometry_cache_and_dirty_state() { assert_eq!(s.doc.render.setups["Studio"].width, 1024); assert!(Arc::ptr_eq(&model, &s.model.state())); assert!(Arc::ptr_eq(&mesh, &s.model.state().bodies[0].mesh())); - assert!(Arc::ptr_eq(&world, &s.world_state())); + assert!(Arc::ptr_eq(&world, &s.world_state().unwrap())); assert_eq!(s.evaluations, 0); // A geometry change and its history still require normal evaluation. s.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap(); diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 78fcbe136..94e1f81d4 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -396,7 +396,7 @@ fn deleting_sheet_material_prunes_cosmetic_threads_and_undo_restores_them() { assert!(s.model.state().bodies.is_empty()); assert!(s.model.state().sheets.is_empty()); assert!(s.model.state().threads.is_empty()); - assert!(solidcraft_doc::world_state(&s.doc, &s.model.state()).threads.is_empty()); + assert!(solidcraft_doc::world_state(&s.doc, &s.model.state()).unwrap().threads.is_empty()); run(&mut s, "edit.undo", json!({})); assert_eq!(s.model.state().threads.len(), 1); } @@ -419,7 +419,7 @@ fn sheet_pocket_transfer_keeps_local_depth_world_pose_and_history() { let floor = sh.frame.to_world(solidcraft_geom::Vec2::new(25.0, 25.0)) + sh.frame.normal() * 1.5; assert!(!mb.body.contains(cut)); assert!(mb.body.contains(floor)); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = &world.body(name).unwrap().body; let bounds = body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap().bounds(); assert!(bounds.min.dist(Vec3::ZERO) < 1e-6, "{bounds:?}"); @@ -2629,7 +2629,7 @@ fn partial_depth_intersect_flipped_tool_and_transferred_sheet_keep_depth_side_an base(&mut s, 100.0, 60.0); rectangle_tool(&mut s, "RetainDepth", [20.0, 20.0], [30.0, 30.0]); run(&mut s, "solid.extrude", json!({"sketch":"RetainDepth","distance":1,"start_offset":0.5,"operation":"intersect","name":"RetainSlab"})); - let before = s.world_state().bodies[0].mesh().bounds(); + let before = s.world_state().unwrap().bodies[0].mesh().bounds(); let name = s.model.state().sheets[0].body.clone(); let destination = run(&mut s, "component.create", json!({"name":"Destination","parent":0,"grounded":false})); let owner = destination["component"].as_u64().unwrap(); @@ -2648,7 +2648,7 @@ fn partial_depth_intersect_flipped_tool_and_transferred_sheet_keep_depth_side_an assert_eq!(sh.pockets.len(), 2); assert_eq!(state.body(&name).unwrap().component, owner); assert!(state.body(&name).unwrap().transferred); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = &world.body(&name).unwrap().body; assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); assert!(!body.contains(Vec3::new(25.0, 25.0, 0.25))); @@ -2658,12 +2658,12 @@ fn partial_depth_intersect_flipped_tool_and_transferred_sheet_keep_depth_side_an assert!((solidcraft_kernel::measure(body).unwrap().volume - 100.0).abs() < 1e-6); } let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - let reopened_world = reopened.world_state(); + let reopened_world = reopened.world_state().unwrap(); let body = &reopened_world.body(&name).unwrap().body; assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); assert!((solidcraft_kernel::measure(body).unwrap().volume - 100.0).abs() < 1e-6); run(&mut reopened, "timeline.edit", json!({"feature":"RetainSlab","set":{"extent":{"distance":"1.5"}}})); - let world = reopened.world_state(); + let world = reopened.world_state().unwrap(); let body = &world.body(&name).unwrap().body; assert!((solidcraft_kernel::measure(body).unwrap().volume - 150.0).abs() < 1e-6); assert!(body.contains(Vec3::new(25.0, 25.0, 1.75))); @@ -2715,7 +2715,7 @@ fn partial_depth_intersect_full_gauge_in_rotated_frames_does_not_invent_pockets( run(&mut s, command, json!({})); } assert!(s.model.state().sheets[0].pockets.is_empty(), "full gauge must not acquire roundoff-depth pockets"); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = &world.body(&name).unwrap().body; assert!((solidcraft_kernel::measure(body).unwrap().volume - 250.0).abs() < 1e-5); assert!(body.contains(Vec3::new(25.0, 25.0, 0.1))); @@ -2731,7 +2731,7 @@ fn partial_depth_intersect_full_gauge_in_rotated_frames_does_not_invent_pockets( run(&mut s, command, json!({})); } assert_eq!(s.model.state().sheets[0].pockets.len(), 2); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = &world.body(&name).unwrap().body; let measured = solidcraft_kernel::measure(body).unwrap().volume; assert!((measured - 100.0).abs() < 1e-5, "retained volume {measured}"); @@ -2740,7 +2740,7 @@ fn partial_depth_intersect_full_gauge_in_rotated_frames_does_not_invent_pockets( assert!(!body.contains(Vec3::new(25.0, 25.0, 2.4))); } let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - let world = cold.world_state(); + let world = cold.world_state().unwrap(); let body = &world.body(&name).unwrap().body; assert!((solidcraft_kernel::measure(body).unwrap().volume - 100.0).abs() < 1e-5); assert!(body.contains(Vec3::new(25.0, 25.0, 1.0))); @@ -2875,7 +2875,7 @@ fn partial_depth_intersect_sub_extrusion_resolution_layers_refuse_atomically() { assert!(error.contains("resolution") || error.contains("distance is zero") || error.contains("sheet machining"), "{error}"); assert_eq!(s.doc.to_json(), before); assert!(s.model.state().sheets[0].pockets.is_empty()); - assert!((solidcraft_kernel::measure(&s.world_state().body(&name).unwrap().body).unwrap().volume - 15000.0).abs() < 1e-5); + assert!((solidcraft_kernel::measure(&s.world_state().unwrap().body(&name).unwrap().body).unwrap().volume - 15000.0).abs() < 1e-5); } } diff --git a/crates/engine/src/cmd/silhouette.rs b/crates/engine/src/cmd/silhouette.rs index f44a9f02f..a989677de 100644 --- a/crates/engine/src/cmd/silhouette.rs +++ b/crates/engine/src/cmd/silhouette.rs @@ -20,7 +20,7 @@ fn run(s: &mut Session, p: &Value) -> Result { let camera = camera(p)?; let rows = rows(p)?; let wanted = body_names(p)?; - let state = s.world_state(); + let state = s.world_state()?; if let Some(names) = &wanted { for name in names { if !state.bodies.iter().any(|b| b.name == *name) { diff --git a/crates/engine/src/cmd/sketch_3d_frame_tests.rs b/crates/engine/src/cmd/sketch_3d_frame_tests.rs index 34ddee7b1..a7c00e35b 100644 --- a/crates/engine/src/cmd/sketch_3d_frame_tests.rs +++ b/crates/engine/src/cmd/sketch_3d_frame_tests.rs @@ -40,7 +40,7 @@ fn wire_frame_second_occurrence_world_inputs_move_and_reopen() { } near(sk.wires[sk.wire_index(&a).unwrap()].fit[0], Vec3::new(2.0, 3.0, 5.0)); near(sk.wires[sk.wire_index(&point).unwrap()].fit[0], Vec3::new(2.0, 3.0, 5.0)); - let world = s.world_state(); + let world = s.world_state().unwrap(); let ws = &world.sketch(sketch).unwrap().sketch; let sw = &ws.wires[ws.wire_index(&spline).unwrap()]; near(sw.fit[0], Vec3::new(14.0, 32.0, 55.0)); @@ -61,9 +61,9 @@ fn wire_frame_second_occurrence_world_inputs_move_and_reopen() { assert_eq!(restored.sketch(sketch).unwrap().wires, s.doc.sketch(sketch).unwrap().wires); // Same definition at the first placement has the local geometry; selected second is exact. run(&mut s, "component.activate", json!({"component":component,"occurrence":first,"path":[first]})); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(3.0, 2.0, 6.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(3.0, 2.0, 6.0)); run(&mut s, "component.activate", json!({"component":component,"occurrence":second,"path":[second]})); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(18.0, 33.0, 46.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(18.0, 33.0, 46.0)); } #[test] @@ -77,10 +77,10 @@ fn wire_frame_pending_moves_other_owner_and_legacy_world_do_not_join() { run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0],"capture":false})); let point = run(&mut s, "sketch.point3d", json!({"point":[22,32,45]}))["point"].as_str().unwrap().to_string(); near(s.doc.sketch(sketch).unwrap().wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(2.0, 3.0, 5.0)); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == legacy).unwrap().fit[0], Vec3::new(2.0, 3.0, 5.0)); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == legacy).unwrap().fit[0], Vec3::new(2.0, 3.0, 5.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); run(&mut s, "component.capture_position", json!({})); - near(s.world_state().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); + near(s.world_state().unwrap().sketch(sketch).unwrap().sketch.wires.iter().find(|w| w.id == point).unwrap().fit[0], Vec3::new(22.0, 32.0, 45.0)); // Explicit target in root must not inherit the unrelated active component frame. run(&mut s, "sketch.finish", json!({})); run(&mut s, "component.activate", json!({"component":0})); @@ -138,7 +138,7 @@ fn wire_frame_include_other_component_refresh_break_lost_and_reopen() { let sk = s.doc.sketch(sketch).unwrap(); assert_eq!(sk.wires[0], initial); assert!(!sk.link(&link).unwrap().lost); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert!(world.sketch(sketch).unwrap().sketch.wires[0].pts.iter().all(|p| (p.x - 10.0).abs() < 1e-7)); let before = s.doc.to_json(); run(&mut s, "sketch.break_link", json!({"link":link})); @@ -179,7 +179,7 @@ fn wire_frame_pipe_component_and_world_paths_have_analytic_volume_and_position() }; run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.pipe", json!({"path_sketch":sketch,"path":[wire],"diameter":4})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); // Property measurement uses fine adaptive tessellation; the viewport mesh alone // undershoots a small circular profile by about 0.64% at its display chord tolerance. @@ -188,7 +188,7 @@ fn wire_frame_pipe_component_and_world_paths_have_analytic_volume_and_position() let bounds = body.mesh().bounds(); near((bounds.min + bounds.max) / 2.0, Vec3::new(17.0, 32.0, 50.0)); run(&mut s, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0]})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); let bounds = body.mesh().bounds(); near((bounds.min + bounds.max) / 2.0, Vec3::new(if space == WireSpace::Component { 22.0 } else { 17.0 }, 32.0, 50.0)); @@ -242,7 +242,7 @@ fn wire_frame_cross_owner_sweep_follows_world_path_edit_undo_and_reopen() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.sweep", json!({"sketch":profile,"path_sketch":path_sketch,"path":[wire],"operation":"new"})); let check = |s: &Session, length: f64| { - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.bodies.last().unwrap(); let measure = solidcraft_kernel::measure(&body.body).unwrap(); assert!((measure.volume - 4.0 * std::f64::consts::PI * length).abs() < 0.05, "{}", measure.volume); @@ -284,7 +284,7 @@ fn wire_frame_three_owner_sweep_profile_move_invalidates_warm_cache() { run(&mut s, "occurrence.move", json!({"occurrence":consumer_occurrence,"axis":[0,0,1],"angle":"90 deg","translate":[100,-30,20]})); run(&mut s, "solid.sweep", json!({"sketch":profile,"path_sketch":path_sketch,"path":[wire],"operation":"new"})); let measure = |session: &Session, x: f64| { - let state = session.world_state(); + let state = session.world_state().unwrap(); let body = state.bodies.last().unwrap(); assert_eq!(body.component, consumer["component"].as_u64().unwrap()); let result = solidcraft_kernel::measure(&body.body).unwrap(); diff --git a/crates/engine/src/cmd/sketch_clipboard_tests.rs b/crates/engine/src/cmd/sketch_clipboard_tests.rs index 7d1e919e9..fdf89f3ae 100644 --- a/crates/engine/src/cmd/sketch_clipboard_tests.rs +++ b/crates/engine/src/cmd/sketch_clipboard_tests.rs @@ -188,7 +188,7 @@ fn paste_into_another_sketch_lands_on_its_plane() { assert!(p[0].dist(Vec2::new(0.0, 0.0)) < 1e-6 && p[1].dist(Vec2::new(20.0, 0.0)) < 1e-6, "{p:?}"); assert_eq!(sk.constraints.iter().filter(|c| c.kind.is_dimension()).count(), 3); assert!(!sk.constraints.iter().any(|c| c.kind.refers_to_point(0))); - let st = s.world_state(); + let st = s.world_state().unwrap(); let ss = st.sketch(b).unwrap(); let w = ss.plane.to_world(Vec2::new(20.0, 10.0)); assert!(w.y.abs() < 1e-9 && (w.x - 20.0).abs() < 1e-9, "{w:?}"); diff --git a/crates/engine/src/cmd/sketch_dimensioned_tests.rs b/crates/engine/src/cmd/sketch_dimensioned_tests.rs index 3ff5e84a8..930548cb7 100644 --- a/crates/engine/src/cmd/sketch_dimensioned_tests.rs +++ b/crates/engine/src/cmd/sketch_dimensioned_tests.rs @@ -216,7 +216,7 @@ fn dimensioned_authoring_uses_selected_occurrence_and_keeps_local_geometry() { let local = model.sketch(s.active_sketch.unwrap()).unwrap(); close(local.plane.origin.x, 0.0); close(local.plane.origin.z, 2.0); - let world = s.world_state(); + let world = s.world_state().unwrap(); let displayed = world.sketch(s.active_sketch.unwrap()).unwrap(); close(displayed.plane.origin.x, 20.0); close(displayed.plane.origin.z, 2.0); diff --git a/crates/engine/src/cmd/sketch_drag_live_tests.rs b/crates/engine/src/cmd/sketch_drag_live_tests.rs index 2e46b658d..bb1c7d795 100644 --- a/crates/engine/src/cmd/sketch_drag_live_tests.rs +++ b/crates/engine/src/cmd/sketch_drag_live_tests.rs @@ -103,7 +103,7 @@ fn pt(s: &Session, id: &str) -> solidcraft_geom::Vec2 { fn corner(s: &Session) -> solidcraft_geom::Vec2 { let id = s.active_sketch.expect("sketch mode"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let sk = &st.sketch(id).expect("the shown sketch").sketch; sk.resolve_point("l1.start").and_then(|i| sk.point(i)).expect("the corner") } diff --git a/crates/engine/src/cmd/sketch_face_tests.rs b/crates/engine/src/cmd/sketch_face_tests.rs index 323711de7..31602ad32 100644 --- a/crates/engine/src/cmd/sketch_face_tests.rs +++ b/crates/engine/src/cmd/sketch_face_tests.rs @@ -6,7 +6,7 @@ fn run(s: &mut Session, command: &str, params: Value) -> Value { s.execute(command, ¶ms).unwrap_or_else(|error| panic!("{command} {params}: {error}")) } fn top_pick(s: &Session, body: &str) -> Value { - let world = s.world_state(); + let world = s.world_state().unwrap(); let body = world.body(body).unwrap(); let face = body .body @@ -35,11 +35,11 @@ fn exact_selected_base_follows_height_and_never_retargets_control() { let height = s.doc.find_feature("BaseFeature").unwrap().param_names[2].clone(); run(&mut s, "parameters.change", json!({"name":height,"expression":"20 mm"})); assert!((s.model.state().sketch(sketch).unwrap().plane.origin.z - 20.).abs() < 1e-6); - assert!((s.world_state().body("Badge").unwrap().mesh().bounds().max.z - 22.).abs() < 1e-6); + assert!((s.world_state().unwrap().body("Badge").unwrap().mesh().bounds().max.z - 22.).abs() < 1e-6); run(&mut s, "timeline.delete", json!({"features":["BaseFeature"]})); assert!(s.model.result(sketch).unwrap().error.is_some()); assert!(s.model.state().body("Badge").is_none()); - assert!((s.world_state().body("Control").unwrap().mesh().bounds().max.z - 30.).abs() < 1e-6); + assert!((s.world_state().unwrap().body("Control").unwrap().mesh().bounds().max.z - 30.).abs() < 1e-6); let before = s.doc.to_json(); let reopened = Session::new(solidcraft_doc::Document::from_json(&before).unwrap()); assert!(reopened.model.result(sketch).unwrap().error.is_some()); @@ -163,7 +163,7 @@ fn exact_nested_source_and_cross_owner_pending_paths_capture_only_involved_posit run(&mut s, "occurrence.move", json!({"occurrence":unrelated["occurrence"],"translate":[300,0,0],"capture":false})); let author = run(&mut s, "component.create", json!({"name":"Author","parent":0})); run(&mut s, "occurrence.move", json!({"occurrence":author["occurrence"],"translate":[100,0,0],"angle":"90 deg","capture":false})); - let world = s.world_state(); + let world = s.world_state().unwrap(); let key = s .placed_document() .body_frames_with_source(&s.model.state()) @@ -592,7 +592,7 @@ fn offset_rectangle_pocket_has_one_logical_outer_wall_and_closed_face_projection /// Every flat face of every body: (body, face index, a point well inside it, its normal). The /// middle of the face's largest triangle, so an L-shaped face is picked on itself. fn flat_faces(s: &Session) -> Vec<(String, usize, Vec3, Vec3)> { - let world = s.world_state(); + let world = s.world_state().unwrap(); let mut out = Vec::new(); for body in &world.bodies { let mesh = body.mesh(); @@ -673,7 +673,7 @@ fn every_flat_face_of_one_sketch_extruded_up_and_down_takes_an_attached_sketch() let script: Value = serde_json::from_str(&std::fs::read_to_string(root.join("up-down-join.json")).unwrap()).unwrap(); let mut s = Session::default(); s.run_script(&script).unwrap(); - assert_eq!(s.world_state().bodies.len(), 1, "the two extrudes join into one body"); + assert_eq!(s.world_state().unwrap().bodies.len(), 1, "the two extrudes join into one body"); assert_eq!(sketch_and_extrude_on_every_flat_face(&s, &dir, "synthetic"), 12, "8 side walls, top, bottom, 2 at the sketch plane"); let reopened = save_and_reopen(&mut s, &dir, "synthetic.solidcraft"); assert_eq!(sketch_and_extrude_on_every_flat_face(&reopened, &dir, "synthetic-reopened"), 12); diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index a3e27e654..f9e1578be 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1496,7 +1496,7 @@ fn irregular_closed_spline_offset_certificate_edits_undoes_and_reopens() { let parameter = result["param"].as_str().unwrap().to_string(); let point_ids = sketch(&s).curves[1].kind.point_ids(); let verify = |s: &Session, distance: f64| { - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; assert_eq!(sk.curves[0], original.curves[0]); assert_eq!(&sk.points[..original.points.len()], &original.points); @@ -1686,7 +1686,7 @@ fn periodic_closed_offset_chain_break_drag_reopen_and_material_volume() { let sketch_id = s.active_sketch.unwrap(); run(&mut s, "sketch.finish", json!({})); run(&mut s, "solid.extrude", json!({"sketch":sketch_id,"profiles":[selected.0],"distance":3,"operation":"new"})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let volume = solidcraft_kernel::measure(&state.bodies.last().unwrap().body).unwrap().volume; assert!((volume - expected).abs() < 0.05, "{volume} vs {expected}"); } @@ -1764,7 +1764,7 @@ fn periodic_offset_extrusion_survives_post_extrude_span_changes_and_cold_reopen( let initial_doc = s.doc.to_json(); for major in [12.0, 16.0, 20.0] { run(&mut s, "parameters.change", json!({"name":"d1","expression":major})); - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = state.sketch(sk_id).unwrap(); let ring = sk.profiles.iter().find(|p| p.whole_curve_boundaries().as_ref() == Some(&boundary)).unwrap(); assert_ne!(ring.outer_curves.len(), initial_count, "the repro must actually change graph span multiplicity"); @@ -1819,7 +1819,7 @@ fn periodic_offset_extrusion_survives_post_extrude_span_changes_and_cold_reopen( assert!((volume - expected).abs() < 0.05, "{major}: {volume} vs independent {expected}"); let mut cold = Session { doc: solidcraft_doc::format::read(&s.doc.to_json()).unwrap().into(), ..Default::default() }; cold.refresh(); - let cold_state = cold.world_state(); + let cold_state = cold.world_state().unwrap(); assert_eq!(cold_state.bodies.len(), 1); let cold_volume = solidcraft_kernel::measure(&cold_state.bodies[0].body).unwrap().volume; assert!((cold_volume - volume).abs() < 1e-8); @@ -2024,7 +2024,7 @@ fn offset_driver_edits_reopens_and_undoes_without_moving_sources() { let param = result["param"].as_str().unwrap().to_string(); let outputs = ids(&result["curves"]); let check = |s: &Session, distance: f64| { - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; assert!((sk.offset_distance(&outputs[0]).unwrap().abs() - distance).abs() < 1e-8); let constraint = sk.constraints.iter().find(|c| c.param.as_deref() == Some(¶m)).unwrap(); @@ -2200,7 +2200,7 @@ fn offset_driver_uses_design_units_and_dimension_delete_freezes_current_distance assert!((sketch(&s).offsets[0].distance - 5.08).abs() < 1e-8); assert!(s.doc.param(param).is_none()); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert!((reopened.world_state().sketch(1).unwrap().sketch.offsets[0].distance - 5.08).abs() < 1e-8); + assert!((reopened.world_state().unwrap().sketch(1).unwrap().sketch.offsets[0].distance - 5.08).abs() < 1e-8); } #[test] @@ -2227,7 +2227,7 @@ fn offset_driver_arc_first_retires_breaks_undoes_and_reopens() { assert!(sketch(&s).offsets.is_empty()); assert_eq!(sketch(&s).segs(sketch(&s).curve_index(&survivor).unwrap()), before); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert!(reopened.world_state().sketch(1).unwrap().sketch.offsets.is_empty()); + assert!(reopened.world_state().unwrap().sketch(1).unwrap().sketch.offsets.is_empty()); run(&mut s, "edit.undo", json!({})); assert!(s.doc.param(param).is_some()); run(&mut s, "edit.redo", json!({})); diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index 5749b9431..c0e16df1f 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -144,7 +144,7 @@ fn state_for_sketch<'a>( }); match attachment { Some(anchor) => solidcraft_doc::state_in_face_anchor_frame(doc, st, anchor, comp), - None => Ok(solidcraft_doc::state_in_frame_at(doc, st, comp, owner_frame(s, doc, comp))), + None => solidcraft_doc::state_in_frame_at(doc, st, comp, owner_frame(s, doc, comp)), } } @@ -655,7 +655,7 @@ pub(super) fn project_internal_faces(s: &mut Session, id: u64, body: &str, indic let mut doc = (*s.doc).clone(); let raw = s.model.state_before(id); let component = doc.feature(id).map(|feature| feature.component).unwrap_or(0); - let state = solidcraft_doc::state_in_frame_at(&doc, &raw, component, owner_frame(s, &doc, component)); + let state = solidcraft_doc::state_in_frame_at(&doc, &raw, component, owner_frame(s, &doc, component))?; let plane = sketch_plane(&doc, id, &state)?; let names = state.body(body).map(solidcraft_doc::naming::face_names).unwrap_or_default(); diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index ab5cea0aa..0f5a9e451 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -36,7 +36,7 @@ fn manual_projection_captures_the_requested_coincident_body_producer() { assert!(matches!(&sk.links[0].source,solidcraft_sketch::LinkSource::Face{body,at} if body=="Target" && (at.z-20.).abs()<1e-6)); assert!(sk.points.iter().any(|point| point.pos.x > 19.)); assert!(sk.points.iter().any(|point| point.pos.y > 19.)); - assert!((session.world_state().body("Control").unwrap().mesh().bounds().max.z - 10.).abs() < 1e-6); + assert!((session.world_state().unwrap().body("Control").unwrap().mesh().bounds().max.z - 10.).abs() < 1e-6); }; verify(&s); verify(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap())); diff --git a/crates/engine/src/cmd/sketch_text_move_tests.rs b/crates/engine/src/cmd/sketch_text_move_tests.rs index 188cb73fa..000bdd891 100644 --- a/crates/engine/src/cmd/sketch_text_move_tests.rs +++ b/crates/engine/src/cmd/sketch_text_move_tests.rs @@ -87,7 +87,7 @@ fn live_text_resize_follows_each_frame_and_rebuilds_downstream_on_release() { assert!((*angle + 10_f64.to_radians()).abs() < 1e-12); // Same letters, same outlines: what references them keeps working. assert_eq!(sk.link_curves(&link).len(), curves); - let shown = s.world_state(); + let shown = s.world_state().unwrap(); assert!(shown.sketch(1).unwrap().profiles.len() >= 2, "the sketch shown follows the frame"); } run(&mut s, "sketch.drag_end", json!({})); @@ -122,13 +122,13 @@ fn text_move_in_a_rotated_component_preserves_font_and_local_coordinates() { let sid = created["sketch"].as_u64().unwrap(); let result = run(&mut s, "sketch.text", json!({"text":"I","at":[0,0],"height":10,"font":solidcraft_sketch::DEFAULT_FONT_FAMILY})); let link = result["link"].as_str().unwrap(); - let before = s.world_state().sketch(sid).unwrap().plane; + let before = s.world_state().unwrap().sketch(sid).unwrap().plane; run(&mut s, "sketch.move", json!({"entities":[result["curves"][0]],"translate":[5,2]})); let sk = s.doc.sketch(sid).unwrap(); let LinkSource::Text { at, font, .. } = &sk.link(link).unwrap().source else { panic!() }; assert!(at.dist(Vec2::new(5.0, 2.0)) < 1e-9); assert_eq!(font.as_deref(), Some(solidcraft_sketch::DEFAULT_FONT_FAMILY)); - let state = s.world_state(); + let state = s.world_state().unwrap(); assert!(state.sketch(sid).unwrap().plane.to_world(*at).dist(before.to_world(Vec2::new(5.0, 2.0))) < 1e-9); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert_eq!(reopened.doc.sketch(sid).unwrap().link(link).unwrap().source, sk.link(link).unwrap().source); @@ -153,7 +153,7 @@ fn text_move_rejects_malformed_values_without_changing_history() { /// The box around the solved outlines of text `link` in sketch 1: (min, max). fn text_box(s: &Session, link: &str) -> (Vec2, Vec2) { - let state = s.world_state(); + let state = s.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; let pts: Vec = sk.link_curves(link).into_iter().flat_map(|ci| sk.polyline(ci)).collect(); let lo = pts.iter().fold(Vec2::new(f64::MAX, f64::MAX), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y))); @@ -384,7 +384,7 @@ fn a_text_on_a_spline_turns_its_path_into_a_guide() { let t = run(&mut s, "sketch.text", json!({"text":"Phago","at":[0,0],"height":10,"path":spline})); assert_eq!(t["guide"], json!(spline)); assert!(construction(&s)); - let state = s.world_state(); + let state = s.world_state().unwrap(); let ss = state.sketch(s.active_sketch.unwrap()).unwrap(); for (i, p) in ss.profiles.iter().enumerate() { let alone = p.curve_ids().iter().all(|id| ss.sketch.curves.iter().any(|c| &c.id == id && c.link.is_some())); diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 995542dd4..1e66925d7 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -773,12 +773,12 @@ mod tests { s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")) } fn volume(s: &Session, name: &str) -> f64 { - let st = s.world_state(); + let st = s.world_state().unwrap(); solidcraft_kernel::measure(&st.body(name).unwrap().body).unwrap().volume } fn area(s: &Session, name: &str) -> f64 { - solidcraft_kernel::measure(&s.world_state().body(name).unwrap().body).unwrap().area + solidcraft_kernel::measure(&s.world_state().unwrap().body(name).unwrap().body).unwrap().area } /// Surface Extrude of open curves: a line and an arc joined end to end (listed in either @@ -795,19 +795,19 @@ mod tests { .to_string(); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": [arc, "l1"], "distance": 4, "body_name": "Wall"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let wall = &st.body("Wall").unwrap().body; assert!(wall.is_surface() && wall.face_count() == 2); // The line's wall and the half circle's (radius 5): length × height. let want = (10.0 + std::f64::consts::PI * 5.0) * 4.0; assert!((area(&s, "Wall") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Wall")); run(&mut s, "surface.extrude", json!({"sketch": "S", "curves": ["l1"], "distance": 2, "direction": "symmetric", "body_name": "Both"})); - let bb = solidcraft_kernel::measure(&s.world_state().body("Both").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Both").unwrap().body).unwrap().bbox; assert!((bb.min.z + 2.0).abs() < 1e-9 && (bb.max.z - 2.0).abs() < 1e-9, "{bb:?}"); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Both").is_none()); + assert!(s.world_state().unwrap().body("Both").is_none()); run(&mut s, "edit.redo", json!({})); - assert!(s.world_state().body("Both").is_some()); + assert!(s.world_state().unwrap().body("Both").is_some()); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Wall") - area(&s, "Wall")).abs() < 1e-9); // Refused: no such curve, a zero distance, and an extent a sheet does not take yet. @@ -825,7 +825,7 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 6]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.extrude", json!({"sketch": "R", "distance": 3, "body_name": "Walls"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let walls = &st.body("Walls").unwrap().body; assert!(walls.is_surface() && walls.face_count() == 4); assert!((area(&s, "Walls") - 96.0).abs() < 1e-9); @@ -833,7 +833,7 @@ mod tests { run(&mut s, "surface.patch", json!({"edges": edges(0.0), "body": "Walls", "body_name": "Bottom"})); run(&mut s, "surface.patch", json!({"edges": edges(3.0), "body": "Walls", "body_name": "Top"})); run(&mut s, "surface.stitch", json!({"bodies": ["Walls", "Bottom", "Top"]})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(!st.body("Walls").unwrap().body.is_surface()); run(&mut s, "solid.extrude", json!({"sketch": "R", "distance": 3, "body_name": "Solid"})); assert!((volume(&s, "Walls") - volume(&s, "Solid")).abs() < 1e-9); @@ -849,7 +849,7 @@ mod tests { run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); let names_before: Vec = solidcraft_doc::naming::face_names(s.model.state().body("Box").unwrap()).to_vec(); run(&mut s, "surface.unstitch", json!({"body": "Box"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Box").is_none()); let pieces: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); assert_eq!(pieces.len(), 6); @@ -864,19 +864,19 @@ mod tests { b.sort(); assert_eq!(a, b, "the faces keep their names"); run(&mut s, "surface.stitch", json!({"bodies": pieces})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let back = st.bodies.first().unwrap(); assert!(!back.body.is_surface()); assert!((solidcraft_kernel::measure(&back.body).unwrap().volume - 1000.0).abs() < 1e-9); run(&mut s, "edit.undo", json!({})); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Box").is_some()); + assert!(s.world_state().unwrap().body("Box").is_some()); run(&mut s, "surface.unstitch", json!({"body": "Box", "faces": [[5, 5, 10], [5, 5, 0]]})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 3); assert_eq!(st.body("Box").unwrap().body.face_count(), 4); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); - assert_eq!(cold.world_state().bodies.len(), 3); + assert_eq!(cold.world_state().unwrap().bodies.len(), 3); assert!(s.execute("surface.unstitch", &json!({"body": "Nope"})).is_err()); assert!(s.execute("surface.unstitch", &json!({})).is_err()); } @@ -890,11 +890,11 @@ mod tests { run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.patch", json!({"sketch": "S", "body_name": "Sheet"})); run(&mut s, "surface.thicken", json!({"bodies": ["Sheet"], "thickness": 2, "body_name": "Up"})); - let up = solidcraft_kernel::measure(&s.world_state().body("Up").unwrap().body).unwrap().bbox; + let up = solidcraft_kernel::measure(&s.world_state().unwrap().body("Up").unwrap().body).unwrap().bbox; run(&mut s, "edit.undo", json!({})); run(&mut s, "surface.reverse_normal", json!({"body": "Sheet"})); run(&mut s, "surface.thicken", json!({"bodies": ["Sheet"], "thickness": 2, "body_name": "Down"})); - let down = solidcraft_kernel::measure(&s.world_state().body("Down").unwrap().body).unwrap().bbox; + let down = solidcraft_kernel::measure(&s.world_state().unwrap().body("Down").unwrap().body).unwrap().bbox; assert!((up.max.z - down.max.z - 2.0).abs() < 1e-9 && (up.min.z - down.min.z - 2.0).abs() < 1e-9, "{up:?} vs {down:?}"); run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "corner": [20, 0, 0], "body_name": "Cube"})); assert!(s.execute("surface.reverse_normal", &json!({"body": "Cube"})).is_err()); @@ -908,20 +908,20 @@ mod tests { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})); run(&mut s, "face.delete", json!({"faces": [[5, 5, 10]], "heal": false})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let open = &st.body("Box").unwrap().body; assert!(open.is_surface() && open.face_count() == 5); let rim = json!([[5, 0, 10], [10, 5, 10], [5, 10, 10], [0, 5, 10]]); run(&mut s, "surface.patch", json!({"edges": rim, "body": "Box", "body_name": "Lid"})); run(&mut s, "surface.stitch", json!({"bodies": ["Box", "Lid"]})); - assert!(!s.world_state().body("Box").unwrap().body.is_surface()); + assert!(!s.world_state().unwrap().body("Box").unwrap().body.is_surface()); assert!((volume(&s, "Box") - 1000.0).abs() < 1e-9); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((volume(&cold, "Box") - 1000.0).abs() < 1e-9); // By default the gap heals, and a box's sides can't close its top: refused, the box kept. run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "body_name": "Healed"})); assert!(s.execute("face.delete", &json!({"faces": [[25, 5, 10]], "body": "Healed"})).is_err()); - assert!(!s.world_state().body("Healed").unwrap().body.is_surface()); + assert!(!s.world_state().unwrap().body("Healed").unwrap().body.is_surface()); let all = json!([[25, 5, 10], [25, 5, 0], [25, 0, 5], [25, 10, 5], [20, 5, 5], [30, 5, 5]]); assert!(s.execute("face.delete", &json!({"faces": all, "body": "Healed", "heal": false})).is_err()); } @@ -947,14 +947,14 @@ mod tests { "surface.revolve", json!({"sketch": "S", "curves": ["side"], "axis": "y", "angle": "90 deg", "symmetric": true, "body_name": "Both"}), ); - let bb = solidcraft_kernel::measure(&s.world_state().body("Both").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Both").unwrap().body).unwrap().bbox; let z = 3.0 * (PI / 4.0).sin(); assert!((bb.min.z + z).abs() < 1e-3 && (bb.max.z - z).abs() < 1e-3, "{bb:?}"); run(&mut s, "surface.revolve", json!({"sketch": "S", "curves": ["slant"], "axis": "y", "body_name": "Cone"})); close(area(&s, "Cone"), PI * 3.0 * 5.0); - assert!(s.world_state().body("Cone").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Cone").unwrap().body.is_surface()); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Cone").is_none()); + assert!(s.world_state().unwrap().body("Cone").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Cone") - area(&s, "Cone")).abs() < 1e-9); @@ -964,7 +964,7 @@ mod tests { run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.revolve", json!({"sketch": "R", "axis": "y", "body_name": "Ring"})); run(&mut s, "solid.revolve", json!({"sketch": "R", "axis": "y", "body_name": "Solid"})); - assert!(!s.world_state().body("Ring").unwrap().body.is_surface()); + assert!(!s.world_state().unwrap().body("Ring").unwrap().body.is_surface()); close(volume(&s, "Ring"), volume(&s, "Solid")); // Refused: a curve across the axis, no axis, and a turn of more than 360°. assert!(s.execute("surface.revolve", &json!({"sketch": "S", "curves": ["side"], "axis": {"origin": [3, 2, 0], "dir": [1, 0, 0]}})).is_err()); @@ -996,7 +996,7 @@ mod tests { run(&mut s, "sketch.finish", json!({})); let close = |a: f64, want: f64| assert!((a - want).abs() < want * 2e-3, "{a} vs {want}"); // (measured on meshes) run(&mut s, "surface.sweep", json!({"sketch": "S", "curves": ["l"], "path_sketch": "P", "path": ["up", arc], "body_name": "Bend"})); - assert!(s.world_state().body("Bend").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Bend").unwrap().body.is_surface()); close(area(&s, "Bend"), 10.0 * (5.0 + 5.0 * FRAC_PI_2)); run(&mut s, "surface.sweep", json!({"sketch": "S", "curves": ["l"], "path_sketch": "P", "path": ["up", "over"], "body_name": "Corner"})); close(area(&s, "Corner"), 100.0); @@ -1004,11 +1004,11 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-1, -1], "p1": [1, 2]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.sweep", json!({"sketch": "R", "path_sketch": "P", "path": ["up"], "body_name": "Walls"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Walls").unwrap().body.is_surface() && st.body("Walls").unwrap().body.face_count() == 4); close(area(&s, "Walls"), 10.0 * 5.0); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Walls").is_none()); + assert!(s.world_state().unwrap().body("Walls").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Bend") - area(&s, "Bend")).abs() < 1e-9); @@ -1034,15 +1034,15 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [20, 0], "p1": [30, 6]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.loft", json!({"sections": [{"sketch": "A", "curves": ["a"]}, {"sketch": "B", "curves": ["b"]}], "body_name": "Strip"})); - assert!(s.world_state().body("Strip").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Strip").unwrap().body.is_surface()); assert!((area(&s, "Strip") - 50.0).abs() < 1e-6, "{}", area(&s, "Strip")); run(&mut s, "surface.loft", json!({"sections": [{"sketch": "A", "profiles": [0]}, {"sketch": "B", "profiles": [0]}], "body_name": "Walls"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let walls = &st.body("Walls").unwrap().body; assert!(walls.is_surface() && walls.face_count() == 4); assert!((area(&s, "Walls") - 160.0).abs() < 1e-6, "{}", area(&s, "Walls")); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Walls").is_none()); + assert!(s.world_state().unwrap().body("Walls").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Walls") - area(&s, "Walls")).abs() < 1e-9); @@ -1102,7 +1102,7 @@ mod tests { let mut s = Session::default(); run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20, "body_name": "Can"})); run(&mut s, "surface.offset", json!({"faces": [[10, 0, 10]], "chain": true, "distance": 2, "body": "Can", "body_name": "Sleeve"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let sleeve = &st.body("Sleeve").unwrap().body; assert!(sleeve.is_surface() && sleeve.face_count() == 2); let want = 2.0 * std::f64::consts::PI * 12.0 * 20.0; @@ -1110,7 +1110,7 @@ mod tests { assert!(st.body("Can").is_some(), "the source body stays"); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0], "body_name": "Box"})); run(&mut s, "surface.offset", json!({"faces": [[35, 5, 10]], "distance": "5 mm", "body_name": "Lid"})); - let bb = solidcraft_kernel::measure(&s.world_state().body("Lid").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Lid").unwrap().body).unwrap().bbox; assert!((bb.min.z - 15.0).abs() < 1e-9 && (area(&s, "Lid") - 100.0).abs() < 1e-9); run(&mut s, "surface.offset", json!({"faces": [[35, 5, 10]], "distance": 0, "body_name": "Copy"})); assert!((area(&s, "Copy") - 100.0).abs() < 1e-9); @@ -1118,7 +1118,7 @@ mod tests { assert!(s.execute("surface.offset", &json!({"faces": [[10, 0, 10]], "chain": true, "distance": -11, "body": "Can"})).is_err()); assert_eq!(s.doc.features.len(), before); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Copy").is_none()); + assert!(s.world_state().unwrap().body("Copy").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Sleeve") - area(&s, "Sleeve")).abs() < 1e-9); @@ -1138,7 +1138,7 @@ mod tests { let top = json!([5, 5, 10]); run(&mut s, "surface.ruled", json!({"body": "Box", "edges": rim, "distance": "2 mm", "mode": "tangent", "face": top, "body_name": "Flange"})); assert!((area(&s, "Flange") - 96.0).abs() < 1e-9, "{}", area(&s, "Flange")); - assert!(s.world_state().body("Flange").unwrap().body.is_surface() && s.world_state().body("Box").is_some()); + assert!(s.world_state().unwrap().body("Flange").unwrap().body.is_surface() && s.world_state().unwrap().body("Box").is_some()); run(&mut s, "surface.ruled", json!({"body": "Box", "edges": rim, "distance": 2, "face": top, "body_name": "Wall"})); assert!((area(&s, "Wall") - 80.0).abs() < 1e-9); run( @@ -1153,9 +1153,9 @@ mod tests { "surface.ruled", json!({"body": "Box", "edges": [[5, 0, 10]], "distance": 2, "mode": "direction", "direction": [0, -1, 0], "body_name": "Lip"}), ); - let bb = solidcraft_kernel::measure(&s.world_state().body("Lip").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Lip").unwrap().body).unwrap().bbox; assert!((area(&s, "Lip") - 20.0).abs() < 1e-9 && (bb.min.y + 2.0).abs() < 1e-9); - let st = s.world_state(); + let st = s.world_state().unwrap(); let names = solidcraft_doc::naming::face_names(st.body("Flange").unwrap()); assert!(names.len() == 4 && names.iter().all(|n| !n.is_empty()), "{names:?}"); let before = s.doc.features.len(); @@ -1172,7 +1172,7 @@ mod tests { } assert_eq!(s.doc.features.len(), before); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Lip").is_none()); + assert!(s.world_state().unwrap().body("Lip").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Draft") - area(&s, "Draft")).abs() < 1e-9); @@ -1187,7 +1187,7 @@ mod tests { } fn edge_count(s: &Session, name: &str) -> usize { - s.world_state().body(name).unwrap().body.edge_count() + s.world_state().unwrap().body(name).unwrap().body.edge_count() } /// Untrim the plate's top: every hole taken away gives one face of the whole 40 × 20 @@ -1201,7 +1201,7 @@ mod tests { let name = solidcraft_doc::naming::face_name_at_body(s.model.state().body("Plate").unwrap(), solidcraft_geom::Vec3::new(5.0, 5.0, 2.0)).unwrap(); run(&mut s, "surface.untrim", json!({"face": {"body": "Plate", "point": top}, "body_name": "Top"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let made = &st.body("Top").unwrap().body; assert!(made.is_surface() && made.face_count() == 1); assert_eq!(edge_count(&s, "Top"), 4, "the rectangle alone"); @@ -1209,7 +1209,7 @@ mod tests { assert_eq!(solidcraft_doc::naming::face_names(s.model.state().body("Top").unwrap()).first(), Some(&name), "the face keeps its name"); assert!(st.body("Plate").is_some(), "the solid stays"); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Top").is_none()); + assert!(s.world_state().unwrap().body("Top").is_none()); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!((area(&cold, "Top") - 800.0).abs() < 1e-9); @@ -1256,7 +1256,7 @@ mod tests { let on = [10.0 * 2.5f64.cos(), 10.0 * 2.5f64.sin(), 5.0]; assert!(s.execute("surface.untrim", &json!({"face": {"body": "Half", "point": on}})).is_err(), "no holes, outer kept"); run(&mut s, "surface.untrim", json!({"face": {"body": "Half", "point": on}, "outer": true, "in_place": true})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 1, "untrimmed where it is"); assert!((area(&s, "Half") - 150.0 * pi).abs() < 150.0 * pi * 1e-3, "{}", area(&s, "Half")); // (measured on meshes) let bb = solidcraft_kernel::measure(&st.body("Half").unwrap().body).unwrap().bbox; @@ -1270,13 +1270,13 @@ mod tests { fn untrim_an_imported_step_face() { let mut s = Session::default(); plate_with_three_holes(&mut s); - let step = solidcraft_kernel::step_export(&[&s.world_state().body("Plate").unwrap().body], "untrim test").unwrap(); + let step = solidcraft_kernel::step_export(&[&s.world_state().unwrap().body("Plate").unwrap().body], "untrim test").unwrap(); let path = std::env::temp_dir().join(format!("solidcraft-untrim-{}.step", std::process::id())); std::fs::write(&path, step).unwrap(); let mut s = Session::default(); run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy()})); let _ = std::fs::remove_file(&path); - let body = s.world_state().bodies.first().unwrap().name.clone(); + let body = s.world_state().unwrap().bodies.first().unwrap().name.clone(); run(&mut s, "surface.untrim", json!({"face": {"body": body, "point": [5, 5, 2]}, "holes": "all", "outer": true, "body_name": "Top"})); assert_eq!(edge_count(&s, "Top"), 4, "the rectangle alone"); assert!((area(&s, "Top") - 800.0).abs() < 1e-9, "{}", area(&s, "Top")); @@ -1308,7 +1308,7 @@ mod tests { run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [top], "distance": "5 mm", "name": "Up"})); let want = 10.0 * pi / 2.0 * 25.0; assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Strip")); // (measured on meshes) - assert_eq!(s.world_state().body("Strip").unwrap().body.face_count(), 1); + assert_eq!(s.world_state().unwrap().body("Strip").unwrap().body.face_count(), 1); let saved = s.doc.to_json(); assert!(!saved.contains("\"mode\"") && !saved.contains("\"up_to\"") && !saved.contains("\"neighbours\""), "the default saves as before"); run(&mut s, "edit.undo", json!({})); @@ -1328,7 +1328,7 @@ mod tests { let parabola = 2.5 * (1.0 + 25.0 * k * k).sqrt() + (5.0 * k).asinh() / (2.0 * k); for (mode, run_off) in [("tangent", 5.0), ("curvature", parabola)] { run(&mut s, "surface.extend", json!({"body": "Strip", "edges": [side], "distance": 5, "mode": mode})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.body("Strip").unwrap().body.face_count(), 2, "{mode}"); let want = 10.0 * pi / 2.0 * 20.0 + run_off * 20.0; assert!((area(&s, "Strip") - want).abs() < want * 1e-3, "{mode}: {} vs {want}", area(&s, "Strip")); // (measured on meshes) @@ -1432,7 +1432,7 @@ mod tests { // (A patch's face is named from geometry; its pieces inherit that, no surer.) let sure = exact(&s, "Floor", 0); run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [5, 5, 0], "with": "Wall", "keep_with": [0, 5, 5], "stitch": true})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Wall").is_none(), "sewn into the floor"); let l = &st.body("Floor").unwrap().body; assert!(l.is_surface()); @@ -1448,15 +1448,15 @@ mod tests { assert!(exact(&s, "Floor", 0) == sure && exact(&s, "Floor", 1) == sure); let saved = s.doc.to_json(); run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Wall").is_some() && (area(&s, "Floor") - 200.0).abs() < 1e-9); + assert!(s.world_state().unwrap().body("Wall").is_some() && (area(&s, "Floor") - 200.0).abs() < 1e-9); run(&mut s, "edit.redo", json!({})); let cold = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); - assert!((area(&cold, "Floor") - 200.0).abs() < 1e-9 && cold.world_state().body("Wall").is_none()); + assert!((area(&cold, "Floor") - 200.0).abs() < 1e-9 && cold.world_state().unwrap().body("Wall").is_none()); // Without stitching, each keeps its half under its own name. run(&mut s, "edit.undo", json!({})); run(&mut s, "surface.trim", json!({"body": "Floor", "keep": [-5, 5, 0], "with": "Wall", "keep_with": [0, 5, -5]})); assert!((area(&s, "Floor") - 100.0).abs() < 1e-9 && (area(&s, "Wall") - 100.0).abs() < 1e-9); - let bb = solidcraft_kernel::measure(&s.world_state().body("Wall").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Wall").unwrap().body).unwrap().bbox; assert!((bb.max.z).abs() < 1e-9, "the wall's lower half: {bb:?}"); } @@ -1473,7 +1473,7 @@ mod tests { let mut asked = mutual.clone(); asked["extend"] = json!(true); run(&mut s, "surface.trim", asked); - let st = s.world_state(); + let st = s.world_state().unwrap(); let l = &st.body("Floor").unwrap().body; assert_eq!((l.face_count(), l.edge_count()), (2, 7)); assert!((area(&s, "Floor") - 200.0).abs() < 1e-6, "{}", area(&s, "Floor")); @@ -1618,7 +1618,7 @@ mod tests { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); run(&mut s, "sketch.finish", json!({})); run(&mut s, "surface.patch", json!({"sketch": "S", "body_name": "Sheet"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Sheet").unwrap().body.is_surface()); run(&mut s, "surface.trim", json!({"body": "Sheet", "plane": {"origin": [3, 0, 0], "normal": [1, 0, 0]}, "keep": [8, 5, 0]})); run(&mut s, "surface.extend", json!({"body": "Sheet", "edges": [[10, 5, 0]], "distance": 5})); @@ -1628,7 +1628,7 @@ mod tests { // Stitch the patch of a box's open top back on. run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "body_name": "Cup"})); run(&mut s, "surface.patch", json!({"edges": [[25, 0, 10], [30, 5, 10], [25, 10, 10], [20, 5, 10]], "body": "Cup", "body_name": "Lid"})); - assert!(s.world_state().body("Lid").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Lid").unwrap().body.is_surface()); // A rim that is not planar: a box with its top cut away by a sideways cylinder. run(&mut s, "solid.box", json!({"length": 28, "width": 28, "height": 20, "corner": [-14, -14, 0], "body_name": "Saddle"})); run( @@ -1639,7 +1639,7 @@ mod tests { let z = |x: f64| 50.0 - (1600.0 - x * x).sqrt(); let rim = json!([[14, 0, z(14.0)], [0, 14, z(0.0)], [-14, 0, z(-14.0)], [0, -14, z(0.0)]]); run(&mut s, "surface.patch", json!({"edges": rim, "body": "Saddle", "body_name": "Cover"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let cover = &st.body("Cover").unwrap().body; assert!(cover.is_surface() && cover.face_count() == 1); // The cover is a smooth surface on the rim, close to the cylinder that cut it (its area @@ -1676,10 +1676,10 @@ mod tests { /// always was. Hostile crowns are refused. #[test] fn patch_crown_fills_a_fitted_patch_and_ignores_a_planar_one() { - let top = |s: &Session| solidcraft_kernel::measure(&s.world_state().body("Cover").unwrap().body).unwrap().bbox.max.z; + let top = |s: &Session| solidcraft_kernel::measure(&s.world_state().unwrap().body("Cover").unwrap().body).unwrap().bbox.max.z; let (plain, reply) = saddle_cover(None); assert_eq!(reply["crown"], json!(0.0), "the crown is reported, 0 by default: {reply}"); - let plain_cover = plain.world_state().body("Cover").unwrap().body.clone(); + let plain_cover = plain.world_state().unwrap().body("Cover").unwrap().body.clone(); // The middle of the loop's box (28 × 28 + 1%, so a 39.9 mm diagonal) rises by crown × 39.9. let (small, reply) = saddle_cover(Some(0.05)); assert_eq!(reply["crown"], json!(0.05), "{reply}"); @@ -1690,7 +1690,7 @@ mod tests { // Crown 0 is the body the default makes, and stitching still closes on the rim (the // crowned patch adds material, so the sealed cup holds more). let (zero, _) = saddle_cover(Some(0.0)); - let zero_area = solidcraft_kernel::measure(&zero.world_state().body("Cover").unwrap().body).unwrap().area; + let zero_area = solidcraft_kernel::measure(&zero.world_state().unwrap().body("Cover").unwrap().body).unwrap().area; assert_eq!(zero_area, solidcraft_kernel::measure(&plain_cover).unwrap().area, "crown 0 is the plain patch"); let sealed = |mut s: Session| { run(&mut s, "surface.stitch", json!({"bodies": ["Saddle", "Cover"], "body_name": "Sealed"})); @@ -1699,7 +1699,7 @@ mod tests { let (sealed_plain, sealed_small, sealed_big) = (sealed(plain), sealed(small), sealed(big)); // The stitch sews the cover onto the cup: one body is left, under the cup's name. let only = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 1, "the cover still meets the rim: {:?}", st.bodies.iter().map(|b| b.name.clone()).collect::>()); st.bodies.first().map(|b| b.name.clone()).unwrap_or_default() }; @@ -1717,7 +1717,7 @@ mod tests { "surface.patch", json!({"edges": [[25, 0, 10], [30, 5, 10], [25, 10, 10], [20, 5, 10]], "body": "Cup", "body_name": "Lid", "crown": 1.0}), ); - let lid = s.world_state().body("Lid").unwrap().body.clone(); + let lid = s.world_state().unwrap().body("Lid").unwrap().body.clone(); let bb = solidcraft_kernel::measure(&lid).unwrap().bbox; assert!((bb.max.z - 10.0).abs() < 1e-9, "a planar rim stays the plane: {bb:?}"); // Hostile crowns. @@ -1758,7 +1758,7 @@ mod tests { s }; let only = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(st.bodies.len(), 1, "the blend sews onto both boxes: {:?}", st.bodies.iter().map(|b| b.name.clone()).collect::>()); st.bodies.first().map(|b| b.name.clone()).unwrap_or_default() }; @@ -1774,7 +1774,7 @@ mod tests { // measurable effect in this fixture (the volumes agree to 2e-5 mm³) — the blend's crown // wiring is item 2/4's to check; this item only owns the patch's crown. for (bulge, s, name) in [(0.0, &plain, &plain_name), (0.6, &full, &full_name)] { - let bb = solidcraft_kernel::measure(&s.world_state().body(name).unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body(name).unwrap().body).unwrap().bbox; assert!(bb.min.z.abs() < 1e-9 && (bb.max.z - 15.0).abs() < 1e-9, "the rims stay the boxes' tops at bulge {bulge}: {bb:?}"); } } @@ -1799,12 +1799,12 @@ mod tests { assert_eq!(r["warning"], json!(null), "{r}"); // The flat sheet between the two top faces: 40 x 10, at z = 10. assert!((area(&s, "Bridge") - 400.0).abs() < 1e-6, "{}", area(&s, "Bridge")); - let bb = solidcraft_kernel::measure(&s.world_state().body("Bridge").unwrap().body).unwrap().bbox; + let bb = solidcraft_kernel::measure(&s.world_state().unwrap().body("Bridge").unwrap().body).unwrap().bbox; assert!((bb.min.z - 10.0).abs() < 1e-9 && (bb.max.z - 10.0).abs() < 1e-9, "{bb:?}"); - assert!(s.world_state().body("Bridge").unwrap().body.is_surface()); + assert!(s.world_state().unwrap().body("Bridge").unwrap().body.is_surface()); // Undo, redo and a cold reopen keep it and its bodies. run(&mut s, "edit.undo", json!({})); - assert!(s.world_state().body("Bridge").is_none()); + assert!(s.world_state().unwrap().body("Bridge").is_none()); run(&mut s, "edit.redo", json!({})); assert!((area(&s, "Bridge") - 400.0).abs() < 1e-6); let cold = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); @@ -1815,7 +1815,7 @@ mod tests { sewn["body_name"] = json!("Seam"); let stitched = run(&mut s, "surface.blend", sewn); assert_eq!(stitched["removed_bodies"], json!(["A", "B"]), "{stitched}"); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("A").is_none() && st.body("B").is_none() && st.body("Seam").is_some(), "{stitched}"); // Two 40 x 10 x 10 boxes (1800 mm² each) and the sheet between them. let want = 2.0 * 1800.0 + 400.0; @@ -1851,7 +1851,7 @@ mod tests { let want = 2.0 * std::f64::consts::PI * 100.0; assert!((area(&s, "Neck") - want).abs() < want * 1e-3, "{} vs {want}", area(&s, "Neck")); let turn = |s: &Session, name: &str| { - let grid = solidcraft_kernel::sample_grid(&s.world_state().body(name).unwrap().body, 17, 5).unwrap(); + let grid = solidcraft_kernel::sample_grid(&s.world_state().unwrap().body(name).unwrap().body, 17, 5).unwrap(); grid.iter() .map(|row| { let (a, b) = (row[0], row[row.len() - 1]); @@ -1897,7 +1897,8 @@ mod tests { fn patch_continuity_and_points_cap_a_tube() { // A coarse mesh is enough to tell the patches apart (measuring a fitted face's area // exactly tessellates it finely). - let mesh = |s: &Session, name: &str| s.world_state().body(name).unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap(); + let mesh = + |s: &Session, name: &str| s.world_state().unwrap().body(name).unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.05)).unwrap(); let (mut s, rim) = open_tube(); let reply = run(&mut s, "surface.patch", json!({"edges": rim, "body": "Tube", "continuity": "g1", "body_name": "Cap"})); assert_eq!(reply["continuity"], json!({"all": "g1"}), "{reply}"); @@ -1966,7 +1967,7 @@ mod tests { run(&mut s, "solid.sphere", json!({"radius": 20, "body_name": "Ball"})); // A sphere is neither a plane nor a cylinder, so its offset is a fitted B-spline face. run(&mut s, "surface.offset", json!({"faces": [[0, 0, 20]], "body": "Ball", "distance": 2, "body_name": "Shell"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Shell").unwrap().body.is_surface(), "an offset sphere face is a sheet"); let before: Vec = st.body("Shell").unwrap().body.edges(0.1).unwrap().iter().flat_map(|e| e.points.clone()).collect(); assert!(!before.is_empty()); @@ -2026,7 +2027,7 @@ mod tests { "body_name": "Blend" }), ); - let body = s.world_state().body("Blend").unwrap().body.clone(); + let body = s.world_state().unwrap().body("Blend").unwrap().body.clone(); // A fine grid in the run direction: the seams sit at u = 0, 1/2 and 1, and the first step // off each one is the tangent there (a thousandth of the run, so it is the tangent). let grid = solidcraft_kernel::sample_grid(&body, 1001, 9).unwrap(); diff --git a/crates/engine/src/cmd/surface_analysis.rs b/crates/engine/src/cmd/surface_analysis.rs index 9753f8d92..451562dd4 100644 --- a/crates/engine/src/cmd/surface_analysis.rs +++ b/crates/engine/src/cmd/surface_analysis.rs @@ -133,7 +133,7 @@ fn continuity(s: &mut Session, p: &Value) -> Result { curvature_per_mm: tolerance(p, "curvature_tolerance_per_mm", DEFAULT_CURVATURE_PER_MM)?, }; let picks = edge_picks(p)?; - let st = s.world_state(); + let st = s.world_state()?; let named = str_(p, "body"); let candidates: Vec<&solidcraft_doc::ModelBody> = match named { Some(name) => vec![st.body(name).ok_or_else(|| bad(cmd, format!("no body `{name}`")))?], diff --git a/crates/engine/src/cmd/surface_boundary_tests.rs b/crates/engine/src/cmd/surface_boundary_tests.rs index e48205eb3..18d1ea907 100644 --- a/crates/engine/src/cmd/surface_boundary_tests.rs +++ b/crates/engine/src/cmd/surface_boundary_tests.rs @@ -114,7 +114,7 @@ fn a_network_of_3d_lines_is_a_hyperbolic_paraboloid() { // The face's own area comes from the coarse reference mesh (a chord of a fiftieth of a per // cent of the body); the measuring mesh is refined onto the surface. assert!((face - want).abs() < 1e-2 * want && (total - want).abs() < 1e-3 * want, "{face} / {total} vs {want}"); - let st = s.world_state(); + let st = s.world_state().unwrap(); let mesh = st.body(&body).map(|b| b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01))).and_then(Result::ok).unwrap_or_default(); assert!(!mesh.positions.is_empty()); for p in &mesh.positions { @@ -194,13 +194,13 @@ fn hostile_networks_are_refused() { let mut s = Session::default(); let (sheet, top) = cylinder_and_line(&mut s); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 40, 0]})); - let boxed = s.world_state().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); + let boxed = s.world_state().unwrap().bodies.last().map(|b| b.name.clone()).unwrap_or_default(); run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Flat"})); let a = line(&mut s, [0.0, 0.0], [10.0, 0.0]); let b = line(&mut s, [0.0, 5.0], [10.0, 5.0]); let far = line(&mut s, [0.0, 20.0], [10.0, 20.0]); let ring = first(&run(&mut s, "sketch.circle.center", json!({"center": [50, 50], "radius": 3}))["created"]["curves"]); - let bodies = s.world_state().bodies.len(); + let bodies = s.world_state().unwrap().bodies.len(); let edge = |g: &str| json!({"body": sheet, "edges": [[5.0, 10.0, 0.0]], "continuity": g}); let many: Vec = (0..33).map(|_| json!(a)).collect(); let cases: Vec<(Value, &str)> = vec![ @@ -240,7 +240,7 @@ fn hostile_networks_are_refused() { assert!(!matches!(e, crate::EngineError::Internal(..)), "{params}: {e}"); assert!(e.to_string().contains(want), "{params}: {e}"); } - assert_eq!(s.world_state().bodies.len(), bodies, "a refused network left a body behind"); + assert_eq!(s.world_state().unwrap().bodies.len(), bodies, "a refused network left a body behind"); } /// An edit (`timeline.redefine`) may turn a loop of sketch curves into the network of the same @@ -259,7 +259,7 @@ fn an_edit_turns_a_loop_into_a_network_and_back() { run(&mut s, "timeline.redefine", json!({"feature": "Patch", "command": "surface.boundary", "params": network})); let kind = |s: &Session| s.doc.find_feature("Patch").map(|f| f.kind.clone()); assert!(matches!(kind(&s), Some(solidcraft_doc::FeatureKind::SurfaceNetwork { .. })), "{:?}", kind(&s)); - let body = s.world_state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let body = s.world_state().unwrap().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); assert!((areas(&mut s, &body).0 - 100.0).abs() < 1e-6); run(&mut s, "timeline.redefine", json!({"feature": "Patch", "command": "surface.boundary", "params": {"sketch": "Square", "curves": sides}})); assert!(matches!(kind(&s), Some(solidcraft_doc::FeatureKind::SurfaceBoundary { .. })), "{:?}", kind(&s)); diff --git a/crates/engine/src/cmd/surface_match.rs b/crates/engine/src/cmd/surface_match.rs index 78f5b8ec8..4121d0fe9 100644 --- a/crates/engine/src/cmd/surface_match.rs +++ b/crates/engine/src/cmd/surface_match.rs @@ -73,7 +73,7 @@ mod tests { /// at either end. The seam is where `solid.extrude` starts the circle, so it is read off the /// body rather than assumed. fn picks(s: &Session) -> Vec { - let boss = s.world_state().body("Boss").unwrap().body.clone(); + let boss = s.world_state().unwrap().body("Boss").unwrap().body.clone(); let e = boss .edges(boss.size() * 1e-2) .unwrap() @@ -109,7 +109,7 @@ mod tests { /// is from the picked seam line, the angle between the two surfaces' normals across it, and /// the continuity it holds. fn seam(s: &Session) -> (f64, f64, Continuity) { - let st = s.world_state(); + let st = s.world_state().unwrap(); let made = st.body("Skirt").unwrap().body.clone(); let target = st.body("Boss").unwrap().body.clone(); solidcraft_kernel::seam_continuity(&made, &target, &picks(s)).unwrap() @@ -127,7 +127,7 @@ mod tests { assert!((gap - 1.0).abs() < 0.05, "the skirt starts a millimetre off the seam: {gap}"); let chain = picks(&s); run(&mut s, "surface.match", json!({"body": "Skirt", "target": "Boss", "edges": chain, "order": "g2"})); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert!(st.body("Skirt").is_some(), "the matched body keeps its name"); assert!(st.body("Boss").is_some(), "the body it was matched to stays too"); assert!(st.body("Skirt").unwrap().body.is_surface(), "a match stays a surface"); diff --git a/crates/engine/src/cmd/sweep_options_tests.rs b/crates/engine/src/cmd/sweep_options_tests.rs index 797955a79..330dd08f7 100644 --- a/crates/engine/src/cmd/sweep_options_tests.rs +++ b/crates/engine/src/cmd/sweep_options_tests.rs @@ -31,7 +31,7 @@ fn setup() -> Session { } fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { - solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() + solidcraft_kernel::measure(&s.world_state().unwrap().body(body).unwrap().body).unwrap() } fn sweep(s: &mut Session, sketch: &str, body: &str, extra: Value) -> Result { @@ -92,7 +92,7 @@ fn twisted_sweep_faces_follow_the_profile_curves() { // The end cap turns with the twist: at 90 deg a square's corners are back where they were, // at 45 deg its top reaches out to the corner radius along the axes. let reach = |s: &Session| { - let mesh = s.world_state().body("Twisted").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); + let mesh = s.world_state().unwrap().body("Twisted").unwrap().body.mesh(&solidcraft_kernel::MeshTolerance::chord(0.01)).unwrap(); mesh.positions.iter().filter(|p| (p.z - 40.0).abs() < 1e-6).map(|p| p.x).fold(f64::MIN, f64::max) }; assert!((reach(&s) - 5.0).abs() < 1e-3, "{}", reach(&s)); diff --git a/crates/engine/src/cmd/sweep_rails_tests.rs b/crates/engine/src/cmd/sweep_rails_tests.rs index badeffc69..e6600633f 100644 --- a/crates/engine/src/cmd/sweep_rails_tests.rs +++ b/crates/engine/src/cmd/sweep_rails_tests.rs @@ -39,7 +39,7 @@ fn setup() -> Session { } fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { - solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() + solidcraft_kernel::measure(&s.world_state().unwrap().body(body).unwrap().body).unwrap() } fn sweep(s: &mut Session, body: &str, extra: Value) -> Result { diff --git a/crates/engine/src/cmd/view_dxf_meshes.rs b/crates/engine/src/cmd/view_dxf_meshes.rs index 0c6a40496..d40704586 100644 --- a/crates/engine/src/cmd/view_dxf_meshes.rs +++ b/crates/engine/src/cmd/view_dxf_meshes.rs @@ -90,7 +90,7 @@ fn rigid(m: &Mat) -> bool { } pub(super) fn prepare(s: &Session, tolerance: f64) -> Result { - let world = s.world_state(); + let world = s.world_state()?; let state = s.model.state(); let mut definitions = BTreeMap::new(); for body in &state.bodies { diff --git a/crates/engine/src/display_mesh_tests.rs b/crates/engine/src/display_mesh_tests.rs index 10625ca5b..003cb79a5 100644 --- a/crates/engine/src/display_mesh_tests.rs +++ b/crates/engine/src/display_mesh_tests.rs @@ -64,7 +64,7 @@ fn steps_around(m: &Mesh, face: usize, origin: Vec3, axis: Vec3) -> (usize, f64) #[test] fn a_large_sheet_shows_its_small_bends_and_holes_round() { let s = large_sheet(); - let st = s.world_state(); + let st = s.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); assert!(b.body.size() * 1e-3 > 3.0, "the chord tolerance is more than any radius here"); @@ -97,7 +97,7 @@ fn a_large_sheet_shows_its_small_bends_and_holes_round() { } } // And the scene the renderers take draws those same polylines. - let scene = crate::view::scene(&s, &crate::view::home_camera(&s)); + let scene = crate::view::scene(&s, &crate::view::home_camera(&s).unwrap()).unwrap(); let drawn: usize = scene.lines.iter().filter(|l| l.points.iter().all(|p| ((p.x - 30.0).hypot(p.y - 20.0) - 2.0).abs() < 1e-6)).map(|l| l.points.len() - 1).sum(); assert!(drawn >= 2 * (TAU / DISPLAY_ANGLE).ceil() as usize, "{drawn} rim segments in the scene"); @@ -106,7 +106,7 @@ fn a_large_sheet_shows_its_small_bends_and_holes_round() { #[test] fn what_reads_the_display_mesh_of_a_large_sheet_answers_as_before() { let s = large_sheet(); - let st = s.world_state(); + let st = s.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); let coarse = b.body.mesh(&solidcraft_kernel::MeshTolerance::chord((b.body.size() * 1e-3).max(1e-3))).unwrap(); diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index e55b6eaca..247c860e2 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -143,13 +143,12 @@ fn pt(p: Vec3) -> Value { } /// The frame of the body a world point lies on (the nearest), or of the named body. -fn frame_at(s: &Session, f: &Frames, p: Vec3, body: Option<&str>) -> Option { +fn frame_at(world: &solidcraft_doc::ModelState, f: &Frames, p: Vec3, body: Option<&str>) -> Option { if let Some(b) = body && let Some((_, _, m)) = f.bodies(s).iter().find(|(w, _, _)| w == b) { return Some(*m); } - let world = s.world_state(); let mut best: Option<(f64, Mat)> = None; for wb in &world.bodies { let Some((_, _, m)) = f.bodies(s).iter().find(|(w, _, _)| *w == wb.name) else { continue }; @@ -183,7 +182,8 @@ fn tri_dist(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 { } struct Mapper<'a> { - s: &'a Session, + /// The placed model the picks are on. + world: &'a solidcraft_doc::ModelState, f: Frames, /// The frame of the command's first pick (its directions turn with it). first: Option, @@ -195,7 +195,7 @@ struct Mapper<'a> { impl Mapper<'_> { fn pick(&mut self, v: &Value, body: Option<&str>) -> Option { let p = vec3(v)?; - let m = if self.here { self.f.sketch } else { frame_at(self.s, &self.f, p, body).unwrap_or(self.f.active) }; + let m = if self.here { self.f.sketch } else { frame_at(self.world, &self.f, p, body).unwrap_or(self.f.active) }; self.first.get_or_insert(m); self.local_point(&m, p) } @@ -362,8 +362,18 @@ impl Drop for Nested { } } -/// `params` with world picks mapped into component frames (`None`: nothing to change). -pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { +/// `params` with world picks mapped into component frames (`None`: nothing to change). A model +/// that cannot be placed is the error. +pub fn to_local(s: &Session, id: &str, params: &Value) -> crate::Result> { + if !placed(s) { + return Ok(None); + } + let world = s.world_state()?; + Ok(map_local(s, &world, id, params)) +} + +/// [`to_local`] on the placed model `world`. +fn map_local(s: &Session, world: &solidcraft_doc::ModelState, id: &str, params: &Value) -> Option { if id == "library.apply" { // Library targets are the same world selections as appearance.assign, // nested one level down. Convert at the outer boundary exactly once; @@ -389,7 +399,7 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { if let solidcraft_doc::FeatureKind::Emboss { face: Some(face), .. } = &feature.kind { context.active_occurrence_path = (!face.author_path.is_empty()).then(|| face.author_path.clone()); } - let mut inner = to_local(&context, cmd, params.get("params")?)?; + let mut inner = map_local(&context, world, cmd, params.get("params")?)?; // An untouched explicit axis is displayed in world coordinates by Edit // Feature. Keep its exact saved values instead of an affine round trip. if cmd == "solid.revolve" @@ -434,7 +444,7 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { return None; } let keys = table(id); - if keys.is_empty() || !placed(s) { + if keys.is_empty() { return None; } let obj = params.as_object()?; @@ -459,7 +469,7 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> Option { obj.insert("origin".into(), serde_json::json!([0.0, 0.0, 0.0])); } let obj = &obj; - let mut m = Mapper { s, f: command_frames, first, changed: false, here: false }; + let mut m = Mapper { world, f: command_frames, first, changed: false, here: false }; let body = obj.get("body").or_else(|| obj.get("face_body")).and_then(Value::as_str).map(str::to_string); let mut out: Map = obj.clone(); // Picks first: their frame turns the directions. diff --git a/crates/engine/src/frames_tests.rs b/crates/engine/src/frames_tests.rs index fcd11c457..4003c90d1 100644 --- a/crates/engine/src/frames_tests.rs +++ b/crates/engine/src/frames_tests.rs @@ -18,7 +18,7 @@ fn near(a: Vec3, b: Vec3) -> bool { } fn world_bbox(s: &Session, body: &str) -> (Vec3, Vec3) { - let w = s.world_state(); + let w = s.world_state().unwrap(); let b = w.body(body).unwrap_or_else(|| panic!("no body {body}")).mesh().bounds(); (b.min, b.max) } diff --git a/crates/engine/src/large_assembly_tests.rs b/crates/engine/src/large_assembly_tests.rs index 3fc50e339..8e4b75256 100644 --- a/crates/engine/src/large_assembly_tests.rs +++ b/crates/engine/src/large_assembly_tests.rs @@ -69,7 +69,7 @@ fn generated_assembly_opens_with_every_body_in_place() { let doc = generated_assembly(parts); let mut s = Session::new(doc.clone()); assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results.iter().find(|r| r.error.is_some())); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), parts * 4); assert!(world.bodies.iter().all(|b| b.component != 0 && b.transferred)); world.warm_meshes(|| true); @@ -109,7 +109,7 @@ fn bench_generated_assembly() { let evaluate = ms(t); let features: f64 = s.model.results.iter().map(|r| r.ms).sum(); let t = std::time::Instant::now(); - let world = s.world_state(); + let world = s.world_state().unwrap(); world.warm_meshes(|| true); let mesh = ms(t); let t = std::time::Instant::now(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a80d69d2a..b4afb4b9c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -261,7 +261,9 @@ struct WorldCache { pending_moves: std::collections::BTreeMap, active_component: u64, active_occurrence_path: Option>, - world: Arc, + /// The placed model, or why it could not be placed (kept too, so a model that cannot be + /// placed is not placed again on every read). + world: std::result::Result, String>, /// The moved components' bodies as placed for `world`, reused by the next world state. placed: Arc>, /// Every placed body's world name, own name and frame for `world` ([`Session::body_frames`]), @@ -730,29 +732,30 @@ impl Session { if self.doc.occurrences.is_empty() { return Some(state); } - self.world_cache.lock().ok()?.as_ref().filter(|cache| cache.matches(self, &state)).map(|cache| cache.world.clone()) + self.world_cache.lock().ok()?.as_ref().filter(|cache| cache.matches(self, &state)).and_then(|cache| cache.world.clone().ok()) } /// Re-evaluate the model after a document change. /// The model placed in the world through component occurrences (and uncaptured moves): what /// to display, measure, pick and export. The same as `model.state()` without components. - pub fn world_state(&self) -> Arc { + /// An error when the model cannot be placed (see [`solidcraft_doc::world_state`]). + pub fn world_state(&self) -> Result> { let st = self.model.state(); if self.doc.occurrences.is_empty() { - return st; + return Ok(st); } if let Ok(c) = self.world_cache.lock() && let Some(cached) = c.as_ref() && cached.matches(self, &st) { - return cached.world.clone(); + return cached.world.clone().map_err(EngineError::Other); } // The bodies the last world state placed: unchanged ones are not transformed and meshed // again (a design built command by command changed one body at a time). let placed = self.world_cache.lock().ok().and_then(|c| c.as_ref().map(|c| c.placed.clone())).unwrap_or_default(); // Taken out while placing, so a scratch copy of the session sharing it never waits. let mut reuse = placed.lock().map(|mut p| std::mem::take(&mut *p)).unwrap_or_default(); - let mut w = { + let w = { if self.pending_moves.is_empty() { solidcraft_doc::world_state_reusing(&self.doc, &st, &mut reuse) } else { @@ -768,21 +771,40 @@ impl Session { if let Ok(mut p) = placed.lock() { *p = reuse; } + let w = w.map_err(EngineError::from).and_then(|w| self.authored_sketches(w)).map(Arc::new); + if let Ok(mut c) = self.world_cache.lock() { + *c = Some(WorldCache { + doc: self.doc.clone(), + model: st, + pending_moves: self.pending_moves.clone(), + active_component: self.active_component, + active_occurrence_path: self.active_occurrence_path.clone(), + world: w.as_ref().map(Arc::clone).map_err(ToString::to_string), + placed, + frames: Arc::default(), + }); + } + w + } + + /// `w` with the active component's sketches shown at the placement being authored. + fn authored_sketches(&self, mut w: solidcraft_doc::ModelState) -> Result { // Sketch definitions are displayed once, at the placement currently being authored. if self.active_occurrence_path.is_some() && self.active_component != 0 { let first = self.occurrence_placement(&self.doc.first_path(self.active_component)).map(|p| p.world).unwrap_or(solidcraft_doc::IDENTITY); - if let Some(inverse) = solidcraft_doc::mat_inverse(&first) { + let inverse = solidcraft_doc::mat_inverse(&first) + .ok_or_else(|| EngineError::Other(format!("the placement of component {} cannot be inverted", self.active_component)))?; + { let delta = solidcraft_doc::mat_mul(&self.active_component_frame(), &inverse); for sketch in w.sketches.iter_mut().filter(|sk| self.doc.feature(sk.feature).is_some_and(|f| f.component == self.active_component)) { let sketch = Arc::make_mut(sketch); let plane = sketch.plane; - if let Some(mapped) = solidcraft_geom::Plane::new( + sketch.plane = solidcraft_geom::Plane::new( solidcraft_doc::apply_point(&delta, plane.origin), solidcraft_doc::apply_vector(&delta, plane.x), solidcraft_doc::apply_vector(&delta, plane.y), - ) { - sketch.plane = mapped; - } + ) + .ok_or_else(|| EngineError::Other("a sketch plane cannot be placed at the authored placement".into()))?; for wire in &mut sketch.sketch.wires { if wire.space == solidcraft_doc::sketch::WireSpace::Component { solidcraft_doc::map_wire(wire, &delta); @@ -791,20 +813,7 @@ impl Session { } } } - let w = Arc::new(w); - if let Ok(mut c) = self.world_cache.lock() { - *c = Some(WorldCache { - doc: self.doc.clone(), - model: st, - pending_moves: self.pending_moves.clone(), - active_component: self.active_component, - active_occurrence_path: self.active_occurrence_path.clone(), - world: w.clone(), - placed, - frames: Arc::default(), - }); - } - w + Ok(w) } /// Every placed body's world name, own name and frame. Kept with the world state while it is @@ -1134,7 +1143,7 @@ impl Session { // Picks in the world go into their component's frame (once: commands run by commands // already have them there). let (_nested, outermost) = frames::Nested::enter(spec.id); - let mapped = if outermost { frames::to_local(self, spec.id, params) } else { None }; + let mapped = if outermost { frames::to_local(self, spec.id, params)? } else { None }; let params = mapped.as_ref().unwrap_or(params); if outermost { crash::command_begin(self, spec.id, given); @@ -1542,22 +1551,20 @@ impl Session { /// The same evaluated preview in occurrence coordinates, including uncaptured moves. pub fn preview_world(&self, commands: &[(String, Value)]) -> Result { - self.scratch().preview_in_place(commands, None).map(|(after, replies)| Preview { - before: self.world_state(), - after: after.world_state(), - replies, - }) + let (after, replies) = self.scratch().preview_in_place(commands, None)?; + Ok(Preview { before: self.world_state()?, after: after.world_state()?, replies }) } /// World preview with each session's visibility applied, including new body placements. pub fn preview_visible_world(&self, commands: &[(String, Value)]) -> Result { - let visible = |session: &Session| { - let world = session.world_state(); + let visible = |session: &Session| -> Result> { + let world = session.world_state()?; let mut shown = (*world).clone(); shown.bodies.retain(|body| session.body_visible(&body.name)); - Arc::new(shown) + Ok(Arc::new(shown)) }; - self.scratch().preview_in_place(commands, None).map(|(after, replies)| Preview { before: visible(self), after: visible(&after), replies }) + let (after, replies) = self.scratch().preview_in_place(commands, None)?; + Ok(Preview { before: visible(self)?, after: visible(&after)?, replies }) } /// Run `commands` on a [`Session::scratch`] copy that keeps the undo and redo stacks: what diff --git a/crates/engine/src/pattern_suppress_tests.rs b/crates/engine/src/pattern_suppress_tests.rs index 4c9b88c32..fee44fcd3 100644 --- a/crates/engine/src/pattern_suppress_tests.rs +++ b/crates/engine/src/pattern_suppress_tests.rs @@ -52,7 +52,7 @@ fn enclosure_datums_follow_wall_height_and_board_depth_with_material_proofs() { s.doc.features.iter().find(|feature| feature.name == "USB" && matches!(feature.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap(); assert!((s.model.state().sketch(usb.id).unwrap().plane.origin.y + 35.5).abs() < 1e-6); let assert_material = |session: &Session| { - let state = session.world_state(); + let state = session.world_state().unwrap(); let case = state.body("Case").unwrap().mesh(); let lid = state.body("Lid").unwrap().mesh(); assert!(case.contains(solidcraft_geom::Vec3::new(-24.5, -21.5, 7.))); diff --git a/crates/engine/src/product_scene.rs b/crates/engine/src/product_scene.rs index 05473cd0c..6441de40d 100644 --- a/crates/engine/src/product_scene.rs +++ b/crates/engine/src/product_scene.rs @@ -12,7 +12,7 @@ pub fn extract(s: &Session) -> Result { if s.model.is_stale() { return Err(EngineError::Other("render scene is stale; finish the modelling gesture before previewing".into())); } - let world = s.world_state(); + let world = s.world_state()?; let mut scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; for body in world.bodies.iter().filter(|b| s.body_visible(&b.name)) { if scene.meshes.len() >= MAX_PRODUCT_BODIES { @@ -80,7 +80,7 @@ mod tests { assert_eq!(m.color, [32, 160, 128]); assert_eq!(m.opacity, 0.4); assert!(m.faces.iter().any(|f| f.color == [255, 0, 0] && f.opacity == 0.7)); - assert!(Arc::ptr_eq(&m.mesh, &s.world_state().body(&m.name).unwrap().mesh())); + assert!(Arc::ptr_eq(&m.mesh, &s.world_state().unwrap().body(&m.name).unwrap().mesh())); } s.selection = vec![Sel::Body { name: first.meshes[0].name.clone() }]; s.section = Some((Vec3::ZERO, Vec3::X)); diff --git a/crates/engine/src/profile_refs_tests.rs b/crates/engine/src/profile_refs_tests.rs index 8c6c37f6a..72e06f4a9 100644 --- a/crates/engine/src/profile_refs_tests.rs +++ b/crates/engine/src/profile_refs_tests.rs @@ -66,13 +66,13 @@ fn a_port_picked_by_index_stays_a_cut_after_a_width_change() { assert!(s.model.result(id).is_some_and(|r| r.error.is_none()), "{:?}", s.model.result(id)); let port = s.doc.find_feature("USB port").unwrap().id; assert!((s.model.state().sketch(port).unwrap().plane.origin.x - 50.).abs() < 1e-6); - let world = s.world_state(); + let world = s.world_state().unwrap(); let mesh = world.body("Enclosure").unwrap().mesh(); assert!(!mesh.contains(solidcraft_geom::Vec3::new(49., 0., 12.))); assert!(mesh.contains(solidcraft_geom::Vec3::new(49., 0., 20.))); let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); assert!(reopened.model.result(id).unwrap().error.is_none()); - let world = reopened.world_state(); + let world = reopened.world_state().unwrap(); let mesh = world.body("Enclosure").unwrap().mesh(); assert!(!mesh.contains(solidcraft_geom::Vec3::new(49., 0., 12.))); assert!(mesh.contains(solidcraft_geom::Vec3::new(49., 0., 20.))); diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 1bec6eb25..033e81583 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -161,7 +161,7 @@ mod tests { assert!(session.model.results.iter().all(|result| result.error.is_none())); assert!((session.model.state().sketch(boss).unwrap().plane.origin.z - 12.).abs() < 1e-6); assert!((session.model.state().sketch(bore).unwrap().plane.origin.z - 26.).abs() < 1e-6); - let world = session.world_state(); + let world = session.world_state().unwrap(); let plate = world.body("Plate").unwrap().mesh(); assert!((plate.bounds().max.z - 26.).abs() < 1e-6); assert!(plate.contains(solidcraft_geom::Vec3::new(5., 25., 10.))); @@ -171,7 +171,7 @@ mod tests { assert!(plate.contains(solidcraft_geom::Vec3::new(40., 35., 2.))); let reopened = crate::Session::new(solidcraft_doc::Document::from_json(&session.doc.to_json()).unwrap()); assert!((reopened.model.state().sketch(bore).unwrap().plane.origin.z - 26.).abs() < 1e-6); - let reopened_world = reopened.world_state(); + let reopened_world = reopened.world_state().unwrap(); let reopened_plate = reopened_world.body("Plate").unwrap().mesh(); assert!(!reopened_plate.contains(solidcraft_geom::Vec3::new(40., 25., 2.))); assert!(reopened_plate.contains(solidcraft_geom::Vec3::new(40., 35., 2.))); diff --git a/crates/engine/src/sketch_edit_removed_tests.rs b/crates/engine/src/sketch_edit_removed_tests.rs index 297331056..44b92c07e 100644 --- a/crates/engine/src/sketch_edit_removed_tests.rs +++ b/crates/engine/src/sketch_edit_removed_tests.rs @@ -110,7 +110,7 @@ fn a_body_the_sketch_sits_on_stays_shown() { let mut s = Session::default(); block(&mut s, "Gone", 0.0); let top = { - let world = s.world_state(); + let world = s.world_state().unwrap(); let face = world .body("Gone") .and_then(|body| body.body.faces(0.01).ok()) @@ -143,7 +143,7 @@ fn every_placement_of_a_component_body_is_left_out() { run(&mut s, "occurrence.copy", json!({"component": component, "translate": [50, 0, 0]})); run(&mut s, "timeline.roll_to", json!({"feature": "Edited"})); run(&mut s, "sketch.edit", json!({"sketch": "Edited"})); - let world = s.world_state(); + let world = s.world_state().unwrap(); assert_eq!(world.bodies.len(), 2, "one body, placed twice"); for body in &world.bodies { assert!(!s.body_visible(&body.name), "{} is deleted later", body.name); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 42e186e63..e3eb5a41e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1386,14 +1386,14 @@ fn extrude_auto_operation() { run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); // A face pushed in (negative distance) cuts. let p = json!({"face": [20, 15, 20], "distance": -5, "operation": "auto"}); - assert_eq!(auto_operation(&s, &p), Some("cut")); + assert_eq!(auto_operation(&s, &p).unwrap(), Some("cut")); run(&mut s, "solid.extrude", p); assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0) < 1e-6); // Pulled out, it joins. - assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 5})), Some("join")); + assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 5})).unwrap(), Some("join")); // Pushed in far past the bottom (halfway is below the box), it still cuts (#1257). - assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": -50})), Some("cut")); - assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 50, "direction": "negative"})), Some("cut")); + assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": -50})).unwrap(), Some("cut")); + assert_eq!(auto_operation(&s, &json!({"face": [20, 15, 15], "distance": 50, "direction": "negative"})).unwrap(), Some("cut")); // A sketch on XY under the box: up goes into it (cut), down grows out of it (join), and a // profile beside the box still defaults to Join (New Body remains explicit). run(&mut s, "sketch.create", json!({"plane": "XY"})); @@ -1401,9 +1401,9 @@ fn extrude_auto_operation() { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [60, 5], "p1": [70, 15]})); run(&mut s, "sketch.finish", json!({})); let at = |x: f64, d: f64| json!({"profiles": [{"point": [x, 10]}], "distance": d}); - assert_eq!(auto_operation(&s, &at(10.0, 8.0)), Some("cut")); - assert_eq!(auto_operation(&s, &at(10.0, -8.0)), Some("join")); - assert_eq!(auto_operation(&s, &at(65.0, 8.0)), Some("join")); + assert_eq!(auto_operation(&s, &at(10.0, 8.0)).unwrap(), Some("cut")); + assert_eq!(auto_operation(&s, &at(10.0, -8.0)).unwrap(), Some("join")); + assert_eq!(auto_operation(&s, &at(65.0, 8.0)).unwrap(), Some("join")); run(&mut s, "solid.extrude", json!({"profiles": [{"point": [10, 10]}], "distance": 8, "operation": "auto"})); assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0 - 100.0 * 8.0) < 1e-6); } @@ -1480,11 +1480,11 @@ fn extrude_auto_operation_follows_the_to_object() { // From the top face to the bottom face: through the body. let down = json!({"face": [20, 15, 20], "to": [10, 10, 0], "distance": 19, "direction": direction}); assert!(extrude_reach(&s, &down).is_some_and(|h| (h + 20.0).abs() < 1e-6), "{down}"); - assert_eq!(auto_operation(&s, &down), Some("cut"), "{down}"); + assert_eq!(auto_operation(&s, &down).unwrap(), Some("cut"), "{down}"); // From the top face up to the box above: out of the body. let up = json!({"face": [20, 15, 20], "to": [10, 10, 50], "distance": 19, "direction": direction}); assert!(extrude_reach(&s, &up).is_some_and(|h| (h - 30.0).abs() < 1e-6), "{up}"); - assert_eq!(auto_operation(&s, &up), Some("join"), "{up}"); + assert_eq!(auto_operation(&s, &up).unwrap(), Some("join"), "{up}"); } // Without a To object the direction still counts. assert_eq!(extrude_reach(&s, &json!({"face": [20, 15, 20], "distance": 5, "direction": "negative"})), Some(-5.0)); @@ -1537,7 +1537,7 @@ fn auto_extrude_joins_side_contact_elbow_and_keeps_new_body_explicit() { // The profile centre is outside the vertical arm. Contact is along its // y=10 side, not behind the centre along the extrusion's X direction. let p = json!({"distance": 10, "to": [0, 15, 25], "operation": operation}); - assert_eq!(auto_operation(&s, &p), Some("join")); + assert_eq!(auto_operation(&s, &p).unwrap(), Some("join")); run(&mut s, "solid.extrude", p); assert!((volume(&mut s) - 5000.0).abs() < 1e-6); let st = s.model.state(); @@ -1561,7 +1561,7 @@ fn auto_extrude_joins_corner_screw_boss() { run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 1})); run(&mut s, "sketch.finish", json!({})); let p = json!({"profiles": [{"point": [12, 10]}], "distance": 5, "operation": "auto"}); - assert_eq!(auto_operation(&s, &p), Some("join")); + assert_eq!(auto_operation(&s, &p).unwrap(), Some("join")); run(&mut s, "solid.extrude", p); assert!(rel(volume(&mut s), 3000.0 + PI * 15.0 * 5.0) < 1e-3); let st = s.model.state(); @@ -1580,8 +1580,8 @@ fn auto_extrude_starts_new_body_in_empty_component() { run(&mut s, "sketch.create", json!({"plane": "XY"})); run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 2})); run(&mut s, "sketch.finish", json!({})); - assert_eq!(auto_operation(&s, &json!({"distance": 5})), Some("new")); - assert_eq!(auto_operation(&s, &json!({"distance": 5, "participants": ["missing"]})), Some("new")); + assert_eq!(auto_operation(&s, &json!({"distance": 5})).unwrap(), Some("new")); + assert_eq!(auto_operation(&s, &json!({"distance": 5, "participants": ["missing"]})).unwrap(), Some("new")); } /// Measuring picked geometry: distance between faces, angle, edge length. @@ -1817,7 +1817,7 @@ fn holes_at_sketch_points_threads_and_components() { ); let reopened = Session::new(back); assert_eq!(reopened.model.state().body("Shaft").unwrap().component, assigned); - assert_eq!(reopened.world_state().threads.len(), s.world_state().threads.len()); + assert_eq!(reopened.world_state().unwrap().threads.len(), s.world_state().unwrap().threads.len()); } #[test] @@ -1938,11 +1938,11 @@ fn components_occurrences_and_world_placement() { run(&mut s, "component.activate", json!({"component": 0})); // Instances share the contents; a copy is independent. run(&mut s, "occurrence.copy", json!({"component": cid, "translate": [0, 20, 0]})); - let w = s.world_state(); + let w = s.world_state().unwrap(); assert_eq!(w.bodies.len(), 3, "{:?}", w.bodies.iter().map(|b| &b.name).collect::>()); let pn = run(&mut s, "component.paste_new", json!({"component": cid, "translate": [0, -30, 0]})); assert_eq!(pn["features"].as_array().map(|a| a.len()), Some(2)); - assert_eq!(s.world_state().bodies.len(), 4); + assert_eq!(s.world_state().unwrap().bodies.len(), 4); // Ground stops moves; pending moves show until captured or reverted. run(&mut s, "occurrence.ground", json!({"occurrence": occ})); assert!(s.execute("occurrence.move", &json!({"occurrence": occ, "translate": [1, 0, 0]})).is_err()); @@ -1988,8 +1988,8 @@ fn components_occurrences_and_world_placement() { run(&mut s, "edit.redo", json!({})); run(&mut s, "timeline.roll_to", json!({"position": 1})); // The ownership boundary is later: before it Base remains the sole root body. - assert_eq!(s.world_state().bodies.len(), 1); - assert_eq!(s.world_state().body("Base").unwrap().component, 0); + assert_eq!(s.world_state().unwrap().bodies.len(), 1); + assert_eq!(s.world_state().unwrap().body("Base").unwrap().component, 0); run(&mut s, "timeline.roll_to", json!({})); // Saved and loaded; older designs get occurrences. let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); @@ -2071,7 +2071,7 @@ fn sample_plate_step_round_trip() { let mut s = Session::default(); s.run_script(&crate::sample::script()).unwrap(); let imp = step_round_trip(&mut s, "sample"); - let st = s.world_state(); + let st = s.world_state().unwrap(); assert_eq!(imp.bodies.len(), st.bodies.len()); for (a, b) in st.bodies.iter().zip(&imp.bodies) { assert_eq!(a.name, b.name); @@ -2142,7 +2142,7 @@ fn face_colours_and_opacity_export() { let mut s2 = Session::default(); run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()})); let _ = std::fs::remove_file(&p); - let st = s2.world_state(); + let st = s2.world_state().unwrap(); let looks = s2.doc.face_colors(&st.bodies[0]); assert_eq!(looks.len(), 1); assert_eq!(looks[0].1.color, [255, 0, 0]); @@ -2156,13 +2156,13 @@ fn iges_export_and_open() { run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "body_name": "Plate"})); run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "base": [10, 10, 5], "body_name": "Pin"})); run(&mut s, "appearance.assign", json!({"bodies": ["Pin"], "color": "#ff0000"})); - let want: Vec = s.world_state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); + let want: Vec = s.world_state().unwrap().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); let p = std::env::temp_dir().join(format!("solidcraft-iges-{}.igs", std::process::id())); run(&mut s, "file.export", json!({"path": p.to_string_lossy()})); let mut s2 = Session::default(); run(&mut s2, "doc.open", json!({"path": p.to_string_lossy()})); let _ = std::fs::remove_file(&p); - let st = s2.world_state(); + let st = s2.world_state().unwrap(); let names: Vec<&str> = st.bodies.iter().map(|b| b.name.as_str()).collect(); assert_eq!(names, ["Plate", "Pin"]); for (b, v) in st.bodies.iter().zip(&want) { @@ -2179,7 +2179,7 @@ fn split_body_by_a_face() { run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"})); run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 40, "base": [5, 10, -5], "body_name": "Tool"})); run(&mut s, "solid.split_body", json!({"body": "Block", "tool": {"body": "Tool", "point": [9, 10, 10]}})); - let st = s.world_state(); + let st = s.world_state().unwrap(); let mut v: Vec = st.bodies.iter().filter(|b| b.name.starts_with("Block")).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); v.sort_by(f64::total_cmp); @@ -2200,7 +2200,7 @@ fn split_body_by_a_sketch_line() { run(&mut s, "sketch.circle.center", json!({"center": [50, 50], "radius": 2, "id": "c"})); run(&mut s, "sketch.finish", json!({})); let volumes = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); let mut v: Vec = st.bodies.iter().filter(|b| b.name.starts_with("Block")).map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect(); v.sort_by(f64::total_cmp); @@ -2237,12 +2237,12 @@ fn chord_and_variable_fillets() { run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"})); run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 4, "type": "chord"})); let r = 4.0 / 2f64.sqrt(); - let v = solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; assert!(rel(v, 6000.0 - (1.0 - PI / 4.0) * r * r * 20.0) < 1e-4, "{v}"); let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"})); run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable", "radius2": 5, "start": [10, 0, 30]})); - let v = solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; let removed = (1.0 - PI / 4.0) * 20.0 * (4.0 + 10.0 + 25.0) / 3.0; assert!(rel(v, 6000.0 - removed) < 1e-4, "{v}"); assert!(s.execute("solid.fillet", &json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable"})).is_err()); @@ -2250,7 +2250,7 @@ fn chord_and_variable_fillets() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "B"})); run(&mut s, "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 4, "type": "variable", "radius2": 0, "start": [10, 0, 30]})); - let v = solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let v = solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; assert!(rel(v, 6000.0 - (1.0 - PI / 4.0) * 20.0 * 16.0 / 3.0) < 1e-4, "{v}"); // A radius through a middle point (a user parameter), straight between: 2 → 4 → 2. let mut s = Session::default(); @@ -2261,7 +2261,7 @@ fn chord_and_variable_fillets() { "solid.fillet", json!({"edges": [[10, 10, 30]], "radius": 2, "type": "variable", "radius2": 2, "start": [10, 0, 30], "mid": [[0.5, "waist"]]}), ); - let vol = |s: &Session| solidcraft_kernel::measure(&s.world_state().body("B").unwrap().body).unwrap().volume; + let vol = |s: &Session| solidcraft_kernel::measure(&s.world_state().unwrap().body("B").unwrap().body).unwrap().volume; let removed = 2.0 * (1.0 - PI / 4.0) * 10.0 * (4.0 + 8.0 + 16.0) / 3.0; assert!(rel(vol(&s), 6000.0 - removed) < 1e-4, "{}", vol(&s)); // The middle radius follows its parameter. @@ -2285,7 +2285,7 @@ fn components_export_as_step_assembly() { run(&mut s, "component.create", json!({"name": "Pin"})); run(&mut s, "solid.cylinder", json!({"radius": 2, "height": 10, "base": [5, 5, 5]})); run(&mut s, "occurrence.copy", json!({"component": "Pin", "translate": [20, 0, 0]})); - let want: f64 = s.world_state().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); + let want: f64 = s.world_state().unwrap().bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); let imp = step_round_trip(&mut s, "asm"); assert_eq!(imp.bodies.len(), 3, "{:?}", imp.bodies.iter().map(|b| &b.name).collect::>()); let got: f64 = imp.bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); @@ -2783,7 +2783,7 @@ fn booleans_stay_in_their_component() { run(&mut s, "sketch.rectangle.two_point", json!({"p0": [8, 2], "p1": [28, 8]})); run(&mut s, "sketch.finish", json!({})); let vol = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["total"]["volume_mm3"].as_f64().unwrap_or(0.0); - assert_eq!(auto_operation(&s, &json!({"sketch": "Slot", "distance": 10})), Some("cut")); + assert_eq!(auto_operation(&s, &json!({"sketch": "Slot", "distance": 10})).unwrap(), Some("cut")); run(&mut s, "solid.extrude", json!({"sketch": "Slot", "distance": 10, "operation": "cut", "name": "Cut"})); assert!((vol(&mut s, "ABox") - (2000.0 - 12.0 * 6.0 * 10.0)).abs() < 1e-6, "{}", vol(&mut s, "ABox")); assert!((vol(&mut s, "BBox") - 2000.0).abs() < 1e-6, "B untouched: {}", vol(&mut s, "BBox")); @@ -3408,14 +3408,14 @@ fn adopting_a_computed_component_keeps_its_warm_world_geometry() { run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10})); let mut computed = s.scratch(); run(&mut computed, "solid.box", json!({"length":5,"width":5,"height":5,"corner":[30,0,0]})); - let prepared = computed.world_state(); + let prepared = computed.world_state().unwrap(); for b in &prepared.bodies { let _ = b.mesh(); } s.accept_computed(computed); - assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state())); + assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state().unwrap())); s.invalidate_view(100); - assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state())); + assert!(std::sync::Arc::ptr_eq(&prepared, &s.world_state().unwrap())); } /// Every file command checked the size with the metadata and then read to the end. A character diff --git a/crates/engine/src/tests/component_frames.rs b/crates/engine/src/tests/component_frames.rs index 75d1d3794..48d3ca62c 100644 --- a/crates/engine/src/tests/component_frames.rs +++ b/crates/engine/src/tests/component_frames.rs @@ -19,7 +19,7 @@ fn moved_component_picks_and_frames() { run(&mut s, "solid.box", json!({"corner": [20, 0, 0], "length": 10, "width": 4, "height": 4, "body_name": "ArmBody"})); run(&mut s, "component.activate", json!({"component": 0})); run(&mut s, "occurrence.move", json!({"occurrence": occ, "translate": [0, 50, 0]})); - let wbox = |s: &Session, b: &str| s.world_state().body(b).unwrap().mesh().bounds(); + let wbox = |s: &Session, b: &str| s.world_state().unwrap().body(b).unwrap().mesh().bounds(); let vol = |s: &mut Session, b: &str| run(s, "inspect.measure", json!({"bodies": [b]}))["total"]["volume_mm3"].as_f64().unwrap(); // Root active: a fillet picked at the moved edge in the world. run(&mut s, "solid.fillet", json!({"edges": [[25, 54, 4]], "radius": 1})); @@ -40,7 +40,7 @@ fn moved_component_picks_and_frames() { // A pasted instance: a pick on it lands on the shared definition. run(&mut s, "occurrence.copy", json!({"component": cid, "translate": [0, 20, 0]})); let v0 = vol(&mut s, "ArmBody"); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); let inst = names.iter().find(|n| n.starts_with("ArmBody (")).cloned().unwrap(); let ib = wbox(&s, &inst); // Its bottom edge along x at the far side (y max, z 0). @@ -71,7 +71,7 @@ fn extrude_in_a_moved_component_from_a_root_sketch() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "component.activate", json!({"component": jaw})); run(&mut s, "solid.extrude", json!({"sketch": "Tab", "distance": 10, "operation": "join", "targets": ["Jaw"]})); - let b = s.world_state().body("Jaw").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Jaw").unwrap().mesh().bounds(); let near = |a: f64, e: f64| (a - e).abs() < 1e-6; assert!(near(b.min.x, 0.0) && near(b.max.x, 40.0) && near(b.min.y, -5.0) && near(b.max.y, 7.0), "{b:?}"); let v = run(&mut s, "inspect.measure", json!({"bodies": ["Jaw"]}))["total"]["volume_mm3"].as_f64().unwrap(); @@ -101,7 +101,7 @@ fn extrude_to_a_face_in_a_moved_component() { run(&mut s, "component.activate", json!({"component": jaw})); // Up to the jaw's top face, picked in the world at its middle: the tab rises from z 0 to 15. run(&mut s, "solid.extrude", json!({"sketch": "Tab", "to": [20, 0, 15], "operation": "join", "targets": ["Jaw"]})); - let b = s.world_state().body("Jaw").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Jaw").unwrap().mesh().bounds(); let near = |a: f64, e: f64| (a - e).abs() < 1e-6; assert!( near(b.min.x, 0.0) && near(b.max.x, 40.0) && near(b.min.y, -5.0) && near(b.max.y, 7.0) && near(b.min.z, 0.0) && near(b.max.z, 15.0), @@ -175,7 +175,7 @@ fn extrude_from_a_slanted_face_in_another_moved_component() { "solid.extrude", json!({"sketch": "Pad", "from": [0, 5, -20], "distance": 4, "direction": "negative", "operation": "new", "body_name": "Leg"}), ); - let b = s.world_state().body("Leg").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Leg").unwrap().mesh().bounds(); assert!((b.max.z + 22.5).abs() < 1e-6 && (b.min.z + 26.5).abs() < 1e-6, "{b:?}"); } @@ -220,7 +220,7 @@ fn revolve_to_a_cylinder_in_another_moved_component() { "solid.revolve", json!({"sketch": "Profile", "axis": {"origin": [0, 0, 0], "dir": [0, 0, 1]}, "to": to, "operation": "new", "body_name": "Arc"}), ); - let world = s.world_state(); + let world = s.world_state().unwrap(); let arc = &world.body("Arc").unwrap().body; let post = &world.body("PostBody").unwrap().body; let overlap = solidcraft_kernel::boolean(arc, post, solidcraft_kernel::BoolOp::Intersect).unwrap(); @@ -255,7 +255,7 @@ fn extrude_to_names_the_face_it_is_on() { "solid.extrude", json!({"sketch": "Pad", "distance": "1 mm", "direction": "negative", "to": [5, 5, -20], "operation": "new", "body_name": "Leg"}), ); - let b = s.world_state().body("Leg").unwrap().mesh().bounds(); + let b = s.world_state().unwrap().body("Leg").unwrap().mesh().bounds(); assert!((b.min.z + 20.0).abs() < 1e-9 && b.max.z.abs() < 1e-9, "moved {moved}: {b:?}"); } } diff --git a/crates/engine/src/tests/gltf_import.rs b/crates/engine/src/tests/gltf_import.rs index 16c3ecc41..7951aa63a 100644 --- a/crates/engine/src/tests/gltf_import.rs +++ b/crates/engine/src/tests/gltf_import.rs @@ -62,6 +62,7 @@ impl Cube { fn shown_boxes(s: &Session) -> Vec<[i64; 6]> { let mut out: Vec<[i64; 6]> = s .world_state() + .unwrap() .bodies .iter() .map(|b| { diff --git a/crates/engine/src/tests/import_component.rs b/crates/engine/src/tests/import_component.rs index 826cb92fe..de5d14167 100644 --- a/crates/engine/src/tests/import_component.rs +++ b/crates/engine/src/tests/import_component.rs @@ -80,7 +80,7 @@ fn key(b: solidcraft_geom::Aabb3) -> [i64; 6] { /// Where the design shows its bodies, sorted. fn shown_boxes(s: &Session) -> Vec<[i64; 6]> { - let mut out: Vec<[i64; 6]> = s.world_state().bodies.iter().map(|b| key(solidcraft_kernel::measure(&b.body).unwrap().bbox)).collect(); + let mut out: Vec<[i64; 6]> = s.world_state().unwrap().bodies.iter().map(|b| key(solidcraft_kernel::measure(&b.body).unwrap().bbox)).collect(); out.sort(); out } @@ -112,7 +112,7 @@ fn corner_of(s: &Session, occurrence: &str) -> Vec3 { }; let names = s.occurrence_bodies(&path, true).unwrap(); assert!(!names.is_empty()); - let world = s.world_state(); + let world = s.world_state().unwrap(); world.bodies.iter().filter(|b| names.contains(&b.name)).fold(Aabb3::EMPTY, |a, b| a.union(&solidcraft_kernel::measure(&b.body).unwrap().bbox)).min } @@ -288,7 +288,7 @@ fn undo_takes_the_whole_import_away() { run(&mut s, "edit.undo", json!({})); assert!(s.doc.features.is_empty() && s.doc.components.is_empty() && s.doc.occurrences.is_empty(), "nothing left"); assert!(s.doc.assembly.joints.is_empty() && s.doc.body_components.is_empty() && s.doc.body_offsets.is_empty()); - assert!(s.world_state().bodies.is_empty()); + assert!(s.world_state().unwrap().bodies.is_empty()); run(&mut s, "edit.redo", json!({})); assert_eq!(shown_boxes(&s), file_boxes(&path)); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/tests/mirror_placed.rs b/crates/engine/src/tests/mirror_placed.rs index 68ee1a398..a16c33b70 100644 --- a/crates/engine/src/tests/mirror_placed.rs +++ b/crates/engine/src/tests/mirror_placed.rs @@ -9,7 +9,7 @@ use super::run; use crate::*; fn world_box(s: &Session, body: &str) -> (Vec3, Vec3) { - let b = s.world_state().body(body).unwrap_or_else(|| panic!("no body `{body}`")).mesh().bounds(); + let b = s.world_state().unwrap().body(body).unwrap_or_else(|| panic!("no body `{body}`")).mesh().bounds(); (b.min, b.max) } @@ -56,7 +56,7 @@ fn a_further_instance_is_mirrored_at_its_own_placement() { let mut s = Session::default(); let (component, _) = moved_arm(&mut s); run(&mut s, "occurrence.copy", json!({"component": component, "translate": [0, 0, 40]})); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); let instance = names.iter().find(|n| n.starts_with("ArmBody (")).cloned().unwrap(); let r = run(&mut s, "solid.mirror", json!({"bodies": ["ArmBody", instance], "plane": "YZ"})); let copies: Vec = r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect(); diff --git a/crates/engine/src/tests/native_cad_import.rs b/crates/engine/src/tests/native_cad_import.rs index 0e0b2ce41..d313fccf1 100644 --- a/crates/engine/src/tests/native_cad_import.rs +++ b/crates/engine/src/tests/native_cad_import.rs @@ -19,7 +19,7 @@ fn file(tag: &str, name: &str, bytes: &[u8]) -> (std::path::PathBuf, String) { } fn extent(s: &Session) -> ([f64; 3], [f64; 3]) { - let b = crate::view::bounds(s); + let b = crate::view::bounds(s).unwrap(); ([b.min.x, b.min.y, b.min.z], [b.max.x, b.max.y, b.max.z]) } diff --git a/crates/engine/src/tests/primitive_points.rs b/crates/engine/src/tests/primitive_points.rs index b499b61ea..d37b5c353 100644 --- a/crates/engine/src/tests/primitive_points.rs +++ b/crates/engine/src/tests/primitive_points.rs @@ -112,7 +112,7 @@ fn point_expressions_in_a_moved_component() { run(&mut s, "occurrence.move", json!({"occurrence": occ, "translate": [0, 50, 0]})); run(&mut s, "component.activate", json!({"component": cid})); run(&mut s, "solid.cylinder", json!({"radius": 1, "height": 2, "base": ["x0", 60, 0], "body_name": "Pin"})); - let wlo = |s: &Session| s.world_state().body("Pin").unwrap().mesh().bounds().min; + let wlo = |s: &Session| s.world_state().unwrap().body("Pin").unwrap().mesh().bounds().min; let lo = wlo(&s); assert!((lo.x - 9.0).abs() < 1e-3 && (lo.y - 59.0).abs() < 1e-3, "{lo:?}"); run(&mut s, "parameters.change", json!({"name": "x0", "expression": "20 mm"})); diff --git a/crates/engine/src/tests/step_import_options.rs b/crates/engine/src/tests/step_import_options.rs index fd8cbab47..397d17bbc 100644 --- a/crates/engine/src/tests/step_import_options.rs +++ b/crates/engine/src/tests/step_import_options.rs @@ -44,7 +44,7 @@ fn frame_file(tag: &str) -> String { /// The lowest and highest corner of everything the design shows. fn extent(s: &Session) -> ([f64; 3], [f64; 3]) { - let b = crate::view::bounds(s); + let b = crate::view::bounds(s).unwrap(); ([b.min.x, b.min.y, b.min.z], [b.max.x, b.max.y, b.max.z]) } diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index 58eba1f15..e22441493 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -8,7 +8,7 @@ use solidcraft_geom::{Aabb3, Plane, Vec3}; use solidcraft_render::{AnalysisColors, Camera, Rgb, Scene, SceneAnalysis, SceneLine, SceneMesh}; use solidcraft_sketch::Sketch; -use crate::{Sel, Session}; +use crate::{Result, Sel, Session}; /// Colours (shared with the GPU viewport). pub mod colors { @@ -105,20 +105,21 @@ impl Default for Palette { /// Bounds of everything visible now, in world space: shown bodies where their occurrences, /// joints and moves place them, and the sketches the view draws (not ones used by a feature, -/// hidden ones, or ones in hidden components). What Home, Fit and the orbit pivot frame. -pub fn bounds(s: &Session) -> Aabb3 { +/// hidden ones, or ones in hidden components). What Home, Fit and the orbit pivot frame. A model +/// that cannot be placed is the error. +pub fn bounds(s: &Session) -> Result { bounds_by(s, |body| body.mesh_bounds()) } /// [`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) -> Aabb3 { +pub fn unmeshed_bounds(s: &Session) -> Result { bounds_by(s, |body| body.cached_mesh().map(|m| m.bounds()).unwrap_or_else(|| body.outline_bounds())) } -fn bounds_by(s: &Session, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> Aabb3 { - let st = s.world_state(); +fn bounds_by(s: &Session, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> Result { + 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(&of(body)); @@ -136,7 +137,7 @@ fn bounds_by(s: &Session, of: impl Fn(&solidcraft_doc::ModelBody) -> Aabb3) -> A } } } - b + Ok(b) } /// The origin plane a grid lies on. @@ -464,23 +465,24 @@ pub fn component_color(s: &Session, component: u64) -> Option<[u8; 3]> { Some(s.doc.component_identification_color(component)) } -/// The scene for a headless render, cut by the session's section. -pub fn scene(s: &Session, cam: &Camera) -> Scene { +/// The scene for a headless render, cut by the session's section. A model that cannot be placed +/// is the error. +pub fn scene(s: &Session, cam: &Camera) -> Result { scene_with_section(s, cam, s.section) } /// The scene for a headless render, cut by `section` (origin, normal) instead of the session's: /// the app passes the cut its viewport shows (an open Section Analysis dialog's preview, a /// sketch's Slice), so model renders match the window. -pub fn scene_with_section(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>) -> Scene { +pub fn scene_with_section(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>) -> Result { scene_with_guides(s, cam, section, Guides::default()) } /// The plane of the sketch that is open, if any: it always shows a grid, whatever the Grid switch /// says (outside a sketch the grid is the user's choice). -pub fn open_sketch_plane(s: &Session) -> Option { - let id = s.active_sketch?; - s.world_state().sketch(id).map(|ss| ss.plane) +pub fn open_sketch_plane(s: &Session) -> Result> { + let Some(id) = s.active_sketch else { return Ok(None) }; + Ok(s.world_state()?.sketch(id).map(|ss| ss.plane)) } /// The grid on a sketch plane: its centre (the view target's foot on the plane, snapped to the @@ -508,14 +510,14 @@ impl Default for Guides { } /// [`scene_with_section`] with the grid and the axes shown or left out. -pub fn scene_with_guides(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>, guides: Guides) -> Scene { +pub fn scene_with_guides(s: &Session, cam: &Camera, section: Option<(Vec3, Vec3)>, guides: Guides) -> Result { scene_with_palette_and_guides(s, cam, section, world_curve_parts, &Palette::DEFAULT, guides) } /// A headless scene using supplied display paths for its visible sketch curves. /// Callers can use the same pixel sampler as a GPU viewport without changing the /// body, grid, appearance, section or sketch styling policies of [`scene`]. -pub fn scene_with_sketch_sampler(s: &Session, cam: &Camera, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>) -> Scene { +pub fn scene_with_sketch_sampler(s: &Session, cam: &Camera, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>) -> Result { scene_with_section_and_sketch_sampler(s, cam, s.section, sampler) } @@ -525,7 +527,7 @@ pub fn scene_with_section_and_sketch_sampler( cam: &Camera, section: Option<(Vec3, Vec3)>, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, -) -> Scene { +) -> Result { scene_with_palette(s, cam, section, sampler, &Palette::DEFAULT) } @@ -536,7 +538,7 @@ pub fn scene_with_palette( section: Option<(Vec3, Vec3)>, sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, p: &Palette, -) -> Scene { +) -> Result { build_scene(s, cam, section, Guides::default(), sampler, p, false) } @@ -548,7 +550,7 @@ pub fn scene_with_palette_and_guides( sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, p: &Palette, guides: Guides, -) -> Scene { +) -> Result { build_scene(s, cam, section, guides, sampler, p, false) } @@ -574,8 +576,8 @@ fn build_scene( mut sampler: impl FnMut(&Sketch, usize, &Plane) -> Vec>, p: &Palette, cosmetic_threads: bool, -) -> Scene { - let st = s.world_state(); +) -> Result { + let st = s.world_state()?; let section = section.filter(|(o, n)| o.is_finite() && n.is_finite() && n.len() > 1e-9); let mut sc = Scene { background: Some(p.background), @@ -585,14 +587,14 @@ fn build_scene( analysis: s.analysis.map(|a| SceneAnalysis { mode: a.mode(), colors: p.analysis }), ..Default::default() }; - let b = bounds(s); + let b = bounds(s)?; sc.radius = (b.diagonal() * 0.5).max(cam.half_height()).max(10.0) + b.center().dist(cam.target); // Grid on the ground plane (XY with Z up, XZ with Y up), drawn under the model as in the viewport. if guides.grid { let (minor, major) = grid_step(cam.half_height()); // Headless pictures keep the grid on the ground, the viewport's default; an open sketch // has its own plane's grid (world coordinates, no camera frame). - let (c, u, v, slant, w): (Vec3, Vec3, Vec3, f64, Box Vec3>) = if let Some(pl) = open_sketch_plane(s) { + let (c, u, v, slant, w): (Vec3, Vec3, Vec3, f64, Box Vec3>) = if let Some(pl) = open_sketch_plane(s)? { let (c, u, v) = sketch_grid_frame(&pl, cam.target, major); let n = u.cross(v); (c, u, v, cam.back().dot(n), Box::new(|p| p)) @@ -701,7 +703,7 @@ fn build_scene( sc.lines.push(SceneLine { points: pts, color: col, alpha: 1.0, width: if cons { 1.0 } else { 1.6 }, on_top: active }); } } - sc + Ok(sc) } /// Where the plane through `o` with normal `n` cuts a mesh: one segment per crossed triangle, @@ -855,15 +857,15 @@ pub fn sketch_consumed(s: &Session, id: u64) -> bool { } /// Camera framing the model (iso view). -pub fn home_camera(s: &Session) -> Camera { +pub fn home_camera(s: &Session) -> Result { let mut c = Camera::default(); - let b = bounds(s); + let b = bounds(s)?; if !b.is_empty() { c.fit(&b); } else { c.distance = 150.0; } - c + Ok(c) } /// Construction planes of the timeline, as evaluated: (feature id, name, plane). @@ -937,8 +939,8 @@ mod tests { s.execute("solid.cylinder", &json!({"diameter": 14, "height": 30, "base": [50, 15, 0], "operation": "new"})).unwrap(); s.execute("appearance.assign", &json!({"bodies": ["Body2"], "color": [220, 60, 40]})).unwrap(); s.execute("appearance.assign", &json!({"faces": [[20, 15, 20]], "body": "Body1", "color": [40, 170, 80]})).unwrap(); - let cam = home_camera(&s); - let sc = scene(&s, &cam); + let cam = home_camera(&s).unwrap(); + let sc = scene(&s, &cam).unwrap(); assert!(sc.meshes.iter().any(|m| m.color == Rgb(220, 60, 40))); assert!(sc.meshes.iter().any(|m| m.face_colors.iter().any(|(_, c)| *c == Rgb(40, 170, 80)))); } @@ -949,16 +951,16 @@ mod tests { fn guides_leave_the_grid_and_the_axes_out() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20, "corner": [10, -15, -10]})).unwrap(); - let cam = home_camera(&s); + let cam = home_camera(&s).unwrap(); let grid = [colors::GRID, colors::GRID_MAJOR]; let axes = [colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z]; let count = |sc: &Scene, colours: &[Rgb]| sc.grid.iter().chain(&sc.lines).filter(|l| colours.contains(&l.color)).count(); - let all = scene(&s, &cam); + let all = scene(&s, &cam).unwrap(); let (grid_lines, edges) = (count(&all, &grid), count(&all, &[colors::EDGE])); assert!(grid_lines > 20 && edges >= 12, "{grid_lines} grid lines, {edges} edges"); assert_eq!(count(&all, &axes), 3); - assert_eq!(all.lines.len(), scene_with_guides(&s, &cam, s.section, Guides::default()).lines.len()); - let render = |g: Guides| scene_with_guides(&s, &cam, s.section, g); + assert_eq!(all.lines.len(), scene_with_guides(&s, &cam, s.section, Guides::default()).unwrap().lines.len()); + let render = |g: Guides| scene_with_guides(&s, &cam, s.section, g).unwrap(); let no_grid = render(Guides { grid: false, axes: true }); assert_eq!((count(&no_grid, &grid), count(&no_grid, &axes), count(&no_grid, &[colors::EDGE])), (0, 3, edges)); let no_axes = render(Guides { grid: true, axes: false }); @@ -973,10 +975,10 @@ mod tests { fn hidden_origin_axes_stay_out_of_renders() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); + let cam = home_camera(&s).unwrap(); let axes = [colors::AXIS_X, colors::AXIS_Y, colors::AXIS_Z]; let shown = |s: &Session| -> Vec { - let sc = scene(s, &cam); + let sc = scene(s, &cam).unwrap(); axes.into_iter().filter(|c| sc.lines.iter().any(|l| l.color == *c)).collect() }; assert_eq!(shown(&s), axes); @@ -984,7 +986,7 @@ mod tests { assert_eq!(shown(&s), [colors::AXIS_X, colors::AXIS_Z]); s.execute("browser.visibility", &json!({"folder": "origin", "visible": false})).unwrap(); assert!(shown(&s).is_empty()); - let sc = scene_with_guides(&s, &cam, None, Guides { grid: true, axes: true }); + let sc = scene_with_guides(&s, &cam, None, Guides { grid: true, axes: true }).unwrap(); assert!(sc.grid.iter().any(|l| l.color == colors::GRID), "the grid is not part of the origin"); s.execute("browser.visibility", &json!({"folder": "origin", "visible": true})).unwrap(); assert_eq!(shown(&s), axes); @@ -996,14 +998,14 @@ mod tests { fn the_section_cuts_the_scene() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); - assert!(scene(&s, &cam).clip.is_none()); + let cam = home_camera(&s).unwrap(); + assert!(scene(&s, &cam).unwrap().clip.is_none()); s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); - let sc = scene(&s, &cam); + let sc = scene(&s, &cam).unwrap(); let (n, d) = sc.clip.unwrap(); assert!((n - Vec3::new(0.0, -1.0, 0.0)).len() < 1e-12 && (d + 15.0).abs() < 1e-12, "{n:?} {d}"); assert_eq!(sc.cap, Some(colors::SECTION_CAP)); - assert!(!section_segments(&s.world_state().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); + assert!(!section_segments(&s.world_state().unwrap().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); } /// The surface analysis shades the headless scene too, in the palette's colours. @@ -1011,10 +1013,10 @@ mod tests { fn the_surface_analysis_shades_the_scene() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); - assert!(scene(&s, &cam).analysis.is_none()); + let cam = home_camera(&s).unwrap(); + assert!(scene(&s, &cam).unwrap().analysis.is_none()); s.analysis = Some(crate::SurfaceAnalysis::Curvature { radius: 5.0 }); - let a = scene(&s, &cam).analysis.unwrap(); + let a = scene(&s, &cam).unwrap().analysis.unwrap(); assert_eq!((a.mode, a.colors), (solidcraft_render::AnalysisMode::Curvature { radius: 5.0 }, Palette::DEFAULT.analysis)); } @@ -1024,8 +1026,8 @@ mod tests { fn cpu_pictures_draw_silhouettes_on_curved_surfaces() { let mut s = Session::default(); s.execute("solid.sphere", &json!({"diameter": 20})).unwrap(); - let cam = home_camera(&s); - let img = solidcraft_render::render(&scene(&s, &cam), &cam, 400, 400); + let cam = home_camera(&s).unwrap(); + let img = solidcraft_render::render(&scene(&s, &cam).unwrap(), &cam, 400, 400); let dark = img.rgba.chunks(4).filter(|p| p[0] < 70 && p[1] < 70 && p[2] < 75).count(); assert!(dark > 40, "silhouette pixels: {dark}"); } @@ -1035,10 +1037,10 @@ mod tests { fn cpu_pictures_show_the_section() { let mut s = Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); - let cam = home_camera(&s); - let whole = solidcraft_render::render(&scene(&s, &cam), &cam, 200, 140).rgba; + let cam = home_camera(&s).unwrap(); + let whole = solidcraft_render::render(&scene(&s, &cam).unwrap(), &cam, 200, 140).rgba; s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); - let sc = scene(&s, &cam); + let sc = scene(&s, &cam).unwrap(); assert!(sc.clip.is_some()); let cut = solidcraft_render::render(&sc, &cam, 200, 140).rgba; let changed = whole.chunks(4).zip(cut.chunks(4)).filter(|(a, b)| a != b).count(); @@ -1055,10 +1057,10 @@ mod tests { // Cut away the front half (y < 15), so the iso camera looks into the cut. s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); for fov in [0.0, 0.6] { - let mut cam = home_camera(&s); + let mut cam = home_camera(&s).unwrap(); cam.fov = fov; - let mut sc = scene(&s, &cam); - assert!(!section_segments(&s.world_state().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); + let mut sc = scene(&s, &cam).unwrap(); + assert!(!section_segments(&s.world_state().unwrap().bodies[0].mesh(), Vec3::new(0.0, 15.0, 0.0), -Vec3::Y).is_empty()); // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); sc.lines.push(SceneLine { diff --git a/crates/engine/src/view_bounds_tests.rs b/crates/engine/src/view_bounds_tests.rs index ccad6f97b..f8eced1b7 100644 --- a/crates/engine/src/view_bounds_tests.rs +++ b/crates/engine/src/view_bounds_tests.rs @@ -15,7 +15,7 @@ fn run(s: &mut Session, id: &str, p: Value) -> Value { /// What the viewport draws: visible bodies' meshes and the sketches it shows, from the scene. fn drawn(s: &Session) -> Aabb3 { let cam = solidcraft_render::Camera { distance: 1e5, ..Default::default() }; - let scene = crate::view::scene(s, &cam); + let scene = crate::view::scene(s, &cam).unwrap(); let mut b = Aabb3::EMPTY; for m in &scene.meshes { b = b.union(&m.mesh.bounds()); @@ -51,11 +51,11 @@ fn block(s: &mut Session) { fn moved_body_leaves_its_used_sketch_out() { let mut s = Session::default(); block(&mut s); - near(crate::view::bounds(&s), [0., 0., 0.], [10., 10., 5.]); - let body = s.world_state().bodies[0].name.clone(); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [10., 10., 5.]); + let body = s.world_state().unwrap().bodies[0].name.clone(); run(&mut s, "solid.move", json!({"bodies": [body], "translate": [500, 0, 0]})); - near(crate::view::bounds(&s), [500., 0., 0.], [510., 10., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [500., 0., 0.], [510., 10., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } #[test] @@ -68,14 +68,14 @@ fn moved_component_frames_where_it_is_now() { block(&mut s); run(&mut s, "component.activate", json!({"component": "root"})); run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [800, 0, 0]})); - near(crate::view::bounds(&s), [0., 0., 0.], [810., 10., 5.]); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [810., 10., 5.]); run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [-780, 0, 0]})); - near(crate::view::bounds(&s), [0., 0., 0.], [30., 10., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [30., 10., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); // Pending (not captured) moves too. run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [0, 300, 0], "capture": false})); - near(crate::view::bounds(&s), [0., 0., 0.], [30., 310., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [30., 310., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } #[test] @@ -83,11 +83,11 @@ fn body_consumed_by_a_join_or_cut_is_not_framed() { let mut s = Session::default(); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [200, 0, 0], "operation": "new"})); - let names: Vec = s.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let names: Vec = s.world_state().unwrap().bodies.iter().map(|b| b.name.clone()).collect(); run(&mut s, "solid.move", json!({"bodies": [names[1].clone()], "translate": [-195, 0, 0]})); run(&mut s, "solid.combine", json!({"target": names[0].clone(), "tools": [names[1].clone()], "operation": "cut"})); - near(crate::view::bounds(&s), [0., 0., 0.], [5., 10., 10.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [5., 10., 10.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } #[test] @@ -107,11 +107,11 @@ fn hidden_component_is_not_framed() { run(&mut s, "sketch.finish", json!({})); run(&mut s, "component.activate", json!({"component": "root"})); run(&mut s, "occurrence.move", json!({"occurrence": b, "translate": [400, 0, 0]})); - near(crate::view::bounds(&s), [0., 0., 0.], [440., 40., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [440., 40., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); run(&mut s, "browser.visibility", json!({"visible": false, "paths": [[b]]})); - near(crate::view::bounds(&s), [0., 0., 0.], [10., 10., 5.]); - same(crate::view::bounds(&s), drawn(&s)); + near(crate::view::bounds(&s).unwrap(), [0., 0., 0.], [10., 10., 5.]); + same(crate::view::bounds(&s).unwrap(), drawn(&s)); } /// Two leaves joined by a hinge (as in the joint tests). @@ -147,16 +147,16 @@ fn block_leaf(s: &mut Session) { fn joint_and_drive_frame_the_joined_place() { let mut s = Session::default(); hinge(&mut s); - let b = crate::view::bounds(&s); + let b = crate::view::bounds(&s).unwrap(); assert!(b.max.x < 50.0, "the joint brought B onto A: {b:?}"); same(b, drawn(&s)); run(&mut s, "joint.drive", json!({"joint": "Hinge", "value": 90})); - let b = crate::view::bounds(&s); + let b = crate::view::bounds(&s).unwrap(); assert!(b.max.x < 50.0 && b.max.z > 30.0, "{b:?}"); same(b, drawn(&s)); run(&mut s, "motion.study", json!({"name": "Swing", "steps": 10, "keys": [{"joint": "Hinge", "points": [[0, 0], [10, 180]]}]})); run(&mut s, "motion.play", json!({"study": "Swing", "step": 10})); - let b = crate::view::bounds(&s); + let b = crate::view::bounds(&s).unwrap(); assert!(b.max.x < 50.0 && b.max.y > 60.0, "{b:?}"); same(b, drawn(&s)); } diff --git a/crates/engine/src/view_display_tests.rs b/crates/engine/src/view_display_tests.rs index 118386b05..d30fc8d3f 100644 --- a/crates/engine/src/view_display_tests.rs +++ b/crates/engine/src/view_display_tests.rs @@ -154,8 +154,8 @@ fn scene_sampler_uses_exact_active_occurrence_plane_and_preserves_other_scene_co s.execute("sketch.circle.center", &json!({"center":[2,3],"radius":1})).unwrap(); s.section = Some((Vec3::new(0., 0., 3.), Vec3::Z)); let cam = Camera::default(); - let old = scene(&s, &cam); - let default = scene_with_sketch_sampler(&s, &cam, world_curve_parts); + let old = scene(&s, &cam).unwrap(); + let default = scene_with_sketch_sampler(&s, &cam, world_curve_parts).unwrap(); assert_eq!(old.lines.len(), default.lines.len()); for (a, b) in old.lines.iter().zip(&default.lines) { assert_eq!((&a.points, a.color, a.width, a.on_top), (&b.points, b.color, b.width, b.on_top)); @@ -165,7 +165,8 @@ fn scene_sampler_uses_exact_active_occurrence_plane_and_preserves_other_scene_co let sampled = scene_with_sketch_sampler(&s, &cam, |_, _, plane| { planes.push(*plane); parts.clone() - }); + }) + .unwrap(); assert_eq!(planes.len(), 1); assert!(planes[0].origin.dist(Vec3::new(20., 30., 40.)) < 1e-9); assert!(planes[0].x.dist(Vec3::X) < 1e-9); @@ -186,7 +187,7 @@ fn scene_sampler_uses_exact_active_occurrence_plane_and_preserves_other_scene_co let active = s.active_sketch.unwrap(); s.execute("sketch.finish", &json!({})).unwrap(); s.visibility.hidden_sketches.push(active); - let hidden = scene_with_sketch_sampler(&s, &cam, |_, _, _| panic!("hidden sketch sampled")); + let hidden = scene_with_sketch_sampler(&s, &cam, |_, _, _| panic!("hidden sketch sampled")).unwrap(); assert!(hidden.lines.iter().all(|line| !line.on_top)); } diff --git a/crates/engine/src/view_palette_tests.rs b/crates/engine/src/view_palette_tests.rs index 4b991e325..6e8451ba5 100644 --- a/crates/engine/src/view_palette_tests.rs +++ b/crates/engine/src/view_palette_tests.rs @@ -206,13 +206,13 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { s.execute("sketch.finish", &json!({})).unwrap(); s.selection = vec![Sel::Body { name: "Picked".into() }]; s.section = Some((Vec3::new(0., 0., 5.), Vec3::Z)); - let cam = home_camera(&s); - let names: Vec = s.world_state().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); + let cam = home_camera(&s).unwrap(); + let names: Vec = s.world_state().unwrap().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); let mesh = |sc: &Scene, name: &str| { names.iter().position(|n| n == name).and_then(|i| sc.meshes.get(i)).map(|m| (m.color, m.face_colors.clone())).unwrap() }; - let marked = scene_with_palette(&s, &cam, s.section, world_curve_parts, &MARK); + let marked = scene_with_palette(&s, &cam, s.section, world_curve_parts, &MARK).unwrap(); assert_eq!((marked.background, marked.cap), (Some(MARK.background), Some(MARK.cap))); let allowed = [ MARK.grid, @@ -244,8 +244,8 @@ fn every_scene_colour_comes_from_its_palette_and_appearances_stay() { assert!(!faces.is_empty() && faces.iter().all(|(_, c)| *c == Rgb(0, 255, 0)), "face colours are the design's: {faces:?}"); // The default palette is the scene everyone else gets, line for line. - let default = scene_with_palette(&s, &cam, s.section, world_curve_parts, &Palette::DEFAULT); - let plain_scene = scene(&s, &cam); + let default = scene_with_palette(&s, &cam, s.section, world_curve_parts, &Palette::DEFAULT).unwrap(); + let plain_scene = scene(&s, &cam).unwrap(); assert_eq!( (default.background, default.cap, default.clip, default.radius), (plain_scene.background, plain_scene.cap, plain_scene.clip, plain_scene.radius) @@ -274,9 +274,9 @@ fn a_see_through_appearance_reaches_the_scene() { s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": "#b0bac6", "opacity": 0.3})).unwrap(); s.execute("appearance.assign", &json!({"bodies": ["Picked"], "color": "#b0bac6", "opacity": 0.3})).unwrap(); s.selection = vec![Sel::Body { name: "Picked".into() }]; - let cam = home_camera(&s); - let sc = scene(&s, &cam); - let names: Vec = s.world_state().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); + let cam = home_camera(&s).unwrap(); + let sc = scene(&s, &cam).unwrap(); + let names: Vec = s.world_state().unwrap().bodies.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect(); let opacity = |name: &str| names.iter().position(|n| n == name).and_then(|i| sc.meshes.get(i)).map(|m| (m.opacity, m.glass())).unwrap(); assert_eq!(opacity("Target"), (0.3, true), "the design's opacity is the one the renderers draw"); @@ -285,6 +285,6 @@ fn a_see_through_appearance_reaches_the_scene() { // Clearing the appearance makes it solid again. s.execute("appearance.assign", &json!({"bodies": ["Target"], "color": null})).unwrap(); - let sc = scene(&s, &cam); + let sc = scene(&s, &cam).unwrap(); assert_eq!(sc.meshes.first().map(|m| m.opacity), Some(1.0)); } diff --git a/crates/engine/src/world_placement_cache_tests.rs b/crates/engine/src/world_placement_cache_tests.rs index 9c736b7fb..3fd5d7b08 100644 --- a/crates/engine/src/world_placement_cache_tests.rs +++ b/crates/engine/src/world_placement_cache_tests.rs @@ -21,8 +21,8 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let path = vec![second]; let placement = session.occurrence_placement(&path).unwrap(); let name = placement.bodies[0].world.clone(); - let world = session.world_state(); - assert!(Arc::ptr_eq(&world, &session.world_state())); + let world = session.world_state().unwrap(); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); let source_state = session.model.state(); let source = source_state.body("Block").unwrap(); let placed = world.body(&name).unwrap(); @@ -38,10 +38,10 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let top = placed.body.faces(0.001).unwrap().into_iter().find(|face| face.plane_normal.is_some_and(|n| n.z > 0.99)).unwrap().index; run(&mut session, "select.set", json!({"items":[{"type":"face","body":name,"index":top,"point":[pick.x,pick.y,pick.z]}]})); assert!(matches!(&session.selection[0], crate::Sel::Face { body, index, .. } if body == &name && *index == top)); - assert!(Arc::ptr_eq(&world, &session.world_state()), "selection changes must not discard prepared placements"); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap()), "selection changes must not discard prepared placements"); let scratch = session.scratch(); assert_eq!(scratch.pending_moves, pending); - let scratch_world = scratch.world_state(); + let scratch_world = scratch.world_state().unwrap(); assert!(Arc::ptr_eq(&world, &scratch_world)); let scratch_body = scratch_world.body(&name).unwrap(); assert!(scratch_body.mesh().bounds().min.dist(bounds.min) < 1e-9); @@ -53,7 +53,7 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let before_joint = crate::doc::mat_mul(&crate::doc::joints::occurrence_world(&session.doc, second), &local_frame); assert!(crate::doc::apply_point(&before_joint, Vec3::ZERO).dist(pick) < 1e-9); run(&mut session, "occurrence.move", json!({"occurrence":second,"translate":[5,0,0],"capture":true})); - let moved = session.world_state(); + let moved = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&world, &moved), "a changed transform must invalidate placed meshes"); assert!(moved.body(&name).unwrap().mesh().bounds().min.dist(bounds.min + Vec3::new(5., 0., 0.)) < 1e-9); assert!(world.body(&name).unwrap().mesh().bounds().min.dist(bounds.min) < 1e-9, "prior snapshots must remain immutable"); @@ -62,7 +62,7 @@ fn world_placement_cache_preserves_pending_picks_materials_scratch_and_named_joi let after_joint = crate::doc::mat_mul(&crate::doc::joints::occurrence_world(&session.doc, second), &local_frame); assert!(crate::doc::apply_point(&after_joint, Vec3::ZERO).dist(pick + Vec3::new(5., 0., 0.)) < 1e-9); let reopened = Session::new(crate::doc::Document::from_json(&session.doc.to_json()).unwrap()); - assert!(reopened.world_state().body(&name).unwrap().mesh().bounds().min.dist(bounds.min + Vec3::new(5., 0., 0.)) < 1e-9); + assert!(reopened.world_state().unwrap().body(&name).unwrap().mesh().bounds().min.dist(bounds.min + Vec3::new(5., 0., 0.)) < 1e-9); assert_eq!(reopened.model.results.iter().filter(|r| r.error.is_some()).count(), 0); } @@ -71,22 +71,22 @@ fn selection_visibility_section_and_view_revisions_reuse_world_geometry() { let mut session = Session::default(); run(&mut session, "component.create", json!({"name":"Part"})); run(&mut session, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Block","operation":"new"})); - let world = session.world_state(); + let world = session.world_state().unwrap(); let revision = session.revision; run(&mut session, "select.set", json!({"items":[{"type":"body","name":"Block"}]})); assert!(session.revision > revision); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); run(&mut session, "select.clear", json!({})); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); run(&mut session, "browser.visibility", json!({"items":["Block"],"visible":false})); assert!(!session.body_visible("Block")); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); run(&mut session, "inspect.section", json!({"plane":{"origin":[0,0,2],"normal":[0,0,1]}})); assert!(session.section.is_some()); - assert!(Arc::ptr_eq(&world, &session.world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); session.invalidate_view(session.revision + 10); - assert!(Arc::ptr_eq(&world, &session.world_state())); - assert!(Arc::ptr_eq(&world, &session.scratch().world_state())); + assert!(Arc::ptr_eq(&world, &session.world_state().unwrap())); + assert!(Arc::ptr_eq(&world, &session.scratch().world_state().unwrap())); } #[test] @@ -99,50 +99,53 @@ fn world_cache_requires_exact_design_model_pending_and_author_context() { let sketch = run(&mut session, "sketch.create", json!({"plane":"XY"}))["sketch"].as_u64().unwrap(); run(&mut session, "sketch.finish", json!({})); let second = run(&mut session, "occurrence.copy", json!({"occurrence":first}))["occurrence"].as_u64().unwrap(); - let initial = session.world_state(); + let initial = session.world_state().unwrap(); run(&mut session, "occurrence.move", json!({"occurrence":second,"translate":[10,20,0],"capture":false})); - let pending = session.world_state(); + let pending = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&initial, &pending)); let name = session.occurrence_placement(&[second]).unwrap().bodies[0].world.clone(); assert!(pending.body(&name).unwrap().mesh().bounds().min.dist(Vec3::new(10., 20., 0.)) < 1e-9); run(&mut session, "component.activate", json!({"component":component,"occurrence":second,"path":[second]})); - let authored = session.world_state(); + let authored = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&pending, &authored)); assert!(authored.sketch(sketch).unwrap().plane.origin.dist(Vec3::new(10., 20., 0.)) < 1e-9); let mut scratch = session.scratch(); - assert!(Arc::ptr_eq(&authored, &scratch.world_state())); + assert!(Arc::ptr_eq(&authored, &scratch.world_state().unwrap())); scratch.active_occurrence_path = Some(vec![first]); - let scratch_world = scratch.world_state(); + let scratch_world = scratch.world_state().unwrap(); assert!(!Arc::ptr_eq(&authored, &scratch_world)); assert!(scratch_world.sketch(sketch).unwrap().plane.origin.dist(Vec3::ZERO) < 1e-9); - assert!(Arc::ptr_eq(&authored, &session.world_state()), "scratch context must not replace the source cache"); + assert!(Arc::ptr_eq(&authored, &session.world_state().unwrap()), "scratch context must not replace the source cache"); // Evaluation and placement never read appearances: an appearance edit, its undo and its redo // keep the evaluated model and the placed world (the cache follows the new document). let model = session.model.state(); run(&mut session, "appearance.assign", json!({"bodies":["Block"],"color":"#ff0000"})); - let painted = session.world_state(); + let painted = session.world_state().unwrap(); assert!(Arc::ptr_eq(&authored, &painted), "an appearance edit keeps the placed world"); assert!(Arc::ptr_eq(&model, &session.model.state()), "and the evaluated model"); assert_ne!(session.doc.model_body_look(painted.body("Block").unwrap()), None); run(&mut session, "edit.undo", json!({})); - let undone = session.world_state(); + let undone = session.world_state().unwrap(); assert!(Arc::ptr_eq(&painted, &undone), "undoing it too"); assert_eq!(session.doc.model_body_look(undone.body("Block").unwrap()), None); run(&mut session, "edit.redo", json!({})); - let redone = session.world_state(); + let redone = session.world_state().unwrap(); assert!(Arc::ptr_eq(&undone, &redone), "and redoing it"); assert!(session.doc.model_body_look(redone.body("Block").unwrap()).is_some()); - let before_edit = session.world_state(); + let before_edit = session.world_state().unwrap(); run(&mut session, "solid.box", json!({"length":5,"width":6,"height":7,"body_name":"Other","operation":"new"})); - let edited = session.world_state(); + let edited = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&before_edit, &edited)); assert!(edited.body("Other").is_some()); session.doc = Arc::new(crate::doc::Document::from_json(&session.doc.to_json()).unwrap()); - let replaced = session.world_state(); + let replaced = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&edited, &replaced), "equal contents in a different document cannot share the cache key"); session.model = crate::doc::Model::default(); session.model.evaluate(&session.doc); - assert!(!Arc::ptr_eq(&replaced, &session.world_state()), "a new evaluated model must invalidate even when the document Arc is unchanged"); + assert!( + !Arc::ptr_eq(&replaced, &session.world_state().unwrap()), + "a new evaluated model must invalidate even when the document Arc is unchanged" + ); } #[test] @@ -150,35 +153,35 @@ fn adopted_scratch_keeps_its_warm_geometry_and_history_stages_invalidate_it() { let mut session = Session::default(); run(&mut session, "component.create", json!({"name":"Part"})); run(&mut session, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Block","operation":"new"})); - let source = session.world_state(); + let source = session.world_state().unwrap(); let source_json = session.doc.to_json(); let mut scratch = session.scratch(); run(&mut scratch, "solid.box", json!({"length":5,"width":6,"height":7,"body_name":"Draft","operation":"new"})); - let warmed = scratch.world_state(); + let warmed = scratch.world_state().unwrap(); assert!(!Arc::ptr_eq(&source, &warmed)); assert_eq!(session.doc.to_json(), source_json); - assert!(Arc::ptr_eq(&source, &session.world_state())); + assert!(Arc::ptr_eq(&source, &session.world_state().unwrap())); assert!(source.body("Draft").is_none()); let feature = warmed.body("Draft").unwrap().feature; session.accept_computed(scratch); - assert!(Arc::ptr_eq(&warmed, &session.world_state()), "adoption/view revision must retain the worker's prepared geometry"); + assert!(Arc::ptr_eq(&warmed, &session.world_state().unwrap()), "adoption/view revision must retain the worker's prepared geometry"); session.invalidate_view(session.revision + 20); - assert!(Arc::ptr_eq(&warmed, &session.world_state())); + assert!(Arc::ptr_eq(&warmed, &session.world_state().unwrap())); run(&mut session, "timeline.rollback", json!({"position":1})); - let rolled = session.world_state(); + let rolled = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&warmed, &rolled)); assert!(rolled.body("Block").is_some()); assert!(rolled.body("Draft").is_none()); run(&mut session, "timeline.rollback", json!({})); - let restored = session.world_state(); + let restored = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&rolled, &restored)); assert!(restored.body("Draft").is_some()); run(&mut session, "timeline.suppress", json!({"feature":feature,"suppressed":true})); - let suppressed = session.world_state(); + let suppressed = session.world_state().unwrap(); assert!(!Arc::ptr_eq(&restored, &suppressed)); assert!(suppressed.body("Draft").is_none()); run(&mut session, "timeline.suppress", json!({"feature":feature,"suppressed":false})); - assert!(session.world_state().body("Draft").is_some()); + assert!(session.world_state().unwrap().body("Draft").is_some()); } /// A moved component's bodies keep their placed geometry and display mesh while the design @@ -192,26 +195,26 @@ fn moved_component_bodies_are_not_placed_again_when_something_else_changes() { run(&mut session, "solid.box", json!({"length":60,"width":60,"height":5,"body_name":"Rim"})); run(&mut session, "component.activate", json!({"component":"root"})); run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[100,0,0]})); - let placed = session.world_state(); + let placed = session.world_state().unwrap(); let rim = placed.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap().clone(); let mesh = rim.mesh(); assert!(mesh.bounds().min.dist(Vec3::new(100., 0., 0.)) < 1e-6); // A body added elsewhere: the rim is the same placed body, already meshed. run(&mut session, "solid.box", json!({"length":5,"width":6,"height":7,"body_name":"Frame"})); - let after = session.world_state(); + let after = session.world_state().unwrap(); let again = after.body(&rim.name).unwrap(); assert!(Arc::ptr_eq(&mesh, &again.mesh()), "an unchanged placed body keeps its mesh"); assert!(again.body.same(&rim.body)); // The placement moves: new world coordinates, reusing the definition's triangulation. run(&mut session, "occurrence.move", json!({"occurrence":occurrence,"translate":[0,50,0]})); - let moved = session.world_state(); + let moved = session.world_state().unwrap(); let moved_rim = moved.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap(); assert!(!Arc::ptr_eq(&mesh, &moved_rim.mesh())); assert!(moved_rim.mesh().bounds().min.dist(Vec3::new(100., 50., 0.)) < 1e-6); // The body itself changes: placed again too, and the old snapshot is untouched. run(&mut session, "body.rename", json!({"body":"Frame","name":"Frame tube"})); let source = session.model.state().body("Rim").unwrap().clone(); - let world = session.world_state(); + let world = session.world_state().unwrap(); let kept = world.bodies.iter().find(|b| b.source_name.as_deref() == Some("Rim")).unwrap(); assert!(Arc::ptr_eq(&moved_rim.mesh(), &kept.mesh())); assert_eq!(kept.source_transform, moved_rim.source_transform); @@ -233,14 +236,14 @@ fn joint_drive_reuses_reference_tessellation_across_rigid_poses() { json!({"type":"revolute","name":"Crank","a":0,"b":"Crank","at":{"occurrence":0,"point":[0,0,0],"z":[0,0,1]}}), ); let definitions = session.model.state(); - let original = session.world_state(); + let original = session.world_state().unwrap(); let local = original.body("Crank").unwrap().mesh(); let bounds = local.bounds(); for angle in [37., 91., 37., 0.] { let driven = run(&mut session, "joint.drive", json!({"joint":"Crank","value":angle})); assert_eq!(driven["moved"], true); assert!(Arc::ptr_eq(&definitions, &session.model.state())); - let world = session.world_state(); + let world = session.world_state().unwrap(); let body = world.body("Crank").unwrap(); let (mesh, work) = crate::kernel::profile::capture(|| body.mesh()); assert_eq!(work.tessellate_ms, 0., "a warm definition must not enter the kernel mesher at a new pose: {work:?}"); diff --git a/crates/engine/tests/save_as_cache.rs b/crates/engine/tests/save_as_cache.rs index 5bfd1f4e1..a8a28105b 100644 --- a/crates/engine/tests/save_as_cache.rs +++ b/crates/engine/tests/save_as_cache.rs @@ -13,7 +13,7 @@ fn assembly() -> Session { } fn warm(session: &Session) { - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index bb067ddf0..03f0d21cc 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -196,7 +196,10 @@ fn a_resident_mesh_matches_the_cpu() { #[test] fn a_scene_in_one_dispatch_matches_each_body_on_the_cpu() { let Some(gpu) = gpu() else { return }; - let plans: Vec = bodies().iter().map(|(_, b)| ok(b.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: 0.01, angle: Some(std::f64::consts::PI / 9.0) }))).collect(); + let plans: Vec = bodies() + .iter() + .map(|(_, b)| ok(b.mesh_plan(&solidcraft_kernel::MeshTolerance { chord: 0.01, angle: Some(std::f64::consts::PI / 9.0) }))) + .collect(); let refs: Vec<&TessPlan> = plans.iter().collect(); let mesh = ok(gpu.prepare_many(&refs)); assert_eq!(mesh.parts.len(), plans.len()); diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rs index 130982d38..17bbbe856 100644 --- a/crates/gpu/tests/capture.rs +++ b/crates/gpu/tests/capture.rs @@ -70,8 +70,8 @@ fn opengl_viewport_pipelines_render_a_model() { .unwrap(); let c = Capturer::new(&adapter, device, queue).unwrap(); let s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]); - let cam = view::home_camera(&s); - let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }), &cam, 160, 100).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }).unwrap(), &cam, 160, 100).unwrap(); let empty = c.rgba(&Default::default(), &cam, 160, 100).unwrap(); let changed = pixels(&img).zip(pixels(&empty)).filter(|(a, b)| a != b).count(); assert!(changed > 500, "the model covers only {changed} pixels"); @@ -87,8 +87,8 @@ fn pictures_show_appearances() { ("appearance.assign", json!({"bodies": ["Body2"], "color": [220, 60, 40]})), ("appearance.assign", json!({"faces": [[20, 15, 20]], "body": "Body1", "color": [40, 170, 80]})), ]); - let cam = view::home_camera(&s); - let img = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let img = c.rgba(&view::scene(&s, &cam).unwrap(), &cam, 200, 140).unwrap(); assert_eq!(img.len(), 200 * 140 * 4); let green = pixels(&img).filter(|p| p[1] > 120 && p[0] < 90 && p[2] < 110).count(); let red = pixels(&img).filter(|p| p[0] > 150 && p[1] < 90 && p[2] < 80).count(); @@ -126,8 +126,8 @@ fn the_renderer_counts_what_it_draws() { fn guides_change_the_picture() { let Some(c) = capturer() else { return }; let s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20, "corner": [10, -15, -10]}))]); - let cam = view::home_camera(&s); - let picture = |grid, axes| c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid, axes }), &cam, 160, 100).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let picture = |grid, axes| c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid, axes }).unwrap(), &cam, 160, 100).unwrap(); let (all, no_grid, no_axes, bare) = (picture(true, true), picture(false, true), picture(true, false), picture(false, false)); assert!(all != no_grid && all != no_axes && no_grid != bare && no_axes != bare); } @@ -137,8 +137,8 @@ fn guides_change_the_picture() { fn pictures_draw_silhouettes_on_curved_surfaces() { let Some(c) = capturer() else { return }; let s = session(&[("solid.sphere", json!({"diameter": 20}))]); - let cam = view::home_camera(&s); - let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }), &cam, 400, 400).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let img = c.rgba(&view::scene_with_guides(&s, &cam, None, Guides { grid: false, axes: false }).unwrap(), &cam, 400, 400).unwrap(); let dark = pixels(&img).filter(|p| p[0] < 90 && p[1] < 90 && p[2] < 95).count(); assert!(dark > 40, "silhouette pixels: {dark}"); } @@ -149,17 +149,17 @@ fn pictures_draw_silhouettes_on_curved_surfaces() { fn pictures_show_the_section_and_its_cap() { let Some(c) = capturer() else { return }; let mut s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]); - let cam = view::home_camera(&s); - let whole = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let whole = c.rgba(&view::scene(&s, &cam).unwrap(), &cam, 200, 140).unwrap(); // Cut away the front half (y < 15), so the iso camera looks into the cut. s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); - let cut = c.rgba(&view::scene(&s, &cam), &cam, 200, 140).unwrap(); + let cut = c.rgba(&view::scene(&s, &cam).unwrap(), &cam, 200, 140).unwrap(); let changed = pixels(&whole).zip(pixels(&cut)).filter(|(a, b)| a != b).count(); assert!(changed > 500, "{changed} pixels changed"); for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&s); + let mut cam = view::home_camera(&s).unwrap(); cam.fov = fov; - let mut sc = view::scene(&s, &cam); + let mut sc = view::scene(&s, &cam).unwrap(); // A marker inside the body, behind the cut face. let red = Rgb(255, 0, 0); sc.lines.push(SceneLine { @@ -266,8 +266,9 @@ fn pictures_show_the_surface_analysis() { ("solid.box", json!({"length": 60, "width": 40, "height": 20})), ("solid.hole", json!({"position": [30, 20, 20], "diameter": 10, "depth": 20})), ]); - let cam = view::home_camera(&s); - let picture = |s: &Session| c.rgba(&view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }), &cam, 320, 200).unwrap(); + let cam = view::home_camera(&s).unwrap(); + let picture = + |s: &Session| c.rgba(&view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }).unwrap(), &cam, 320, 200).unwrap(); let plain = picture(&s); s.execute("inspect.curvature_map", &json!({})).unwrap(); let curvature = picture(&s); diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rs index 024aeca91..14155fbec 100644 --- a/crates/gpu/tests/depth.rs +++ b/crates/gpu/tests/depth.rs @@ -59,7 +59,7 @@ fn session(script: &[(&str, serde_json::Value)]) -> Session { } fn picture(c: &Capturer, s: &Session, cam: &Camera, w: u32, h: u32) -> Vec { - c.rgba(&view::scene_with_guides(s, cam, None, Guides { grid: false, axes: false }), cam, w, h).unwrap() + c.rgba(&view::scene_with_guides(s, cam, None, Guides { grid: false, axes: false }).unwrap(), cam, w, h).unwrap() } fn differing(a: &[u8], b: &[u8]) -> usize { @@ -114,7 +114,7 @@ fn at_ten_metres_a_thin_label_is_whole_and_a_washer_behind_stays_hidden() { continue; } // The label's front face (y = -0.3), sampled inside its outline. - let radius = view::scene(&with, &cam).radius; + let radius = view::scene(&with, &cam).unwrap().radius; let mut grey = Vec::new(); for i in 1..20 { for j in 1..20 { @@ -271,12 +271,12 @@ fn an_edge_on_the_cut_face_draws_over_the_cap() { s.execute("inspect.section", &json!({"plane": {"origin": [0, 15, 0], "normal": [0, -1, 0]}})).unwrap(); for (mode, c) in capturers() { for fov in [0.0, 0.6] { - let mut cam = view::home_camera(&s); + let mut cam = view::home_camera(&s).unwrap(); cam.fov = fov; let count = |on_top: bool| { // The session's section (`scene_with_guides` takes its own). The line is 2 µm on // the kept side: exactly on the plane, rounding cuts parts of it away with the rest. - let mut sc = view::scene(&s, &cam); + let mut sc = view::scene(&s, &cam).unwrap(); sc.lines.push(red_line(Vec3::new(5.0, 15.002, 10.0), Vec3::new(35.0, 15.002, 10.0), on_top)); pixels(&c.rgba(&sc, &cam, 300, 220).unwrap()).filter(|p| red(*p)).count() }; diff --git a/crates/io/src/design/native_cache.rs b/crates/io/src/design/native_cache.rs index cace5e151..780c2b2c8 100644 --- a/crates/io/src/design/native_cache.rs +++ b/crates/io/src/design/native_cache.rs @@ -295,7 +295,7 @@ fn matrix_of(numbers: &[f64]) -> Result<[[f64; 4]; 4]> { pub(super) fn geometry_preview(document: &[u8], model: &SavedModel) -> Result { let doc = Document::from_json(std::str::from_utf8(document).map_err(invalid)?)?; - let world = solidcraft_doc::world_state(&doc, &*model.final_state()?); + let world = solidcraft_doc::world_state(&doc, &*model.final_state()?)?; let mut preview = DesignPreview::default(); let mut triangles = 0usize; let mut display_bytes = 0usize; diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 023ba44f5..475a263ee 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -513,7 +513,7 @@ impl Backend for Headless { match v { // Fit keeps the orientation, also of a camera `view.apply` chose. "fit" => { - let b = solidcraft_engine::view::bounds(s); + let b = solidcraft_engine::view::bounds(s).map_err(|e| e.to_string())?; if let Some(c) = s.camera.as_mut() { c.fit(&b); } @@ -528,18 +528,21 @@ impl Backend for Headless { "ui.render" => { let (w, h) = (dim(&p, "width", 1280.0), dim(&p, "height", 800.0)); // The camera `view.apply` chose, else the standard view framing the model. - let cam = s.camera.unwrap_or_else(|| { - let mut cam = solidcraft_engine::view::home_camera(s); - cam.set_view(self.view); - cam - }); + let cam = match s.camera { + Some(cam) => cam, + None => { + let mut cam = solidcraft_engine::view::home_camera(s).map_err(|e| e.to_string())?; + cam.set_view(self.view); + cam + } + }; // The grid and the axes are drawn unless the request leaves them out. let shown = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(true); let guides = Guides { grid: shown("grid"), axes: shown("axes") }; let path = str_p("path").ok_or("missing `path`")?; // A path outside the agent's folders is refused before anything is drawn. solidcraft_engine::io::vfs::check(path).map_err(|e| format!("{path}: {e}"))?; - let scene = solidcraft_engine::view::scene_with_guides(s, &cam, s.section, guides); + let scene = solidcraft_engine::view::scene_with_guides(s, &cam, s.section, guides).map_err(|e| e.to_string())?; // Drawn on the GPU by the renderer the host installed (`solidcraft-cli mcp`). let png = solidcraft_engine::capture::png(&scene, &cam, w, h)?; solidcraft_engine::io::vfs::write(path, &png.bytes).map_err(|e| format!("{path}: {e}"))?; diff --git a/crates/ui-egui/src/access.rs b/crates/ui-egui/src/access.rs index 19bdc8ea8..167f32884 100644 --- a/crates/ui-egui/src/access.rs +++ b/crates/ui-egui/src/access.rs @@ -21,7 +21,7 @@ pub fn map(app: &SolveApp) -> Option { if let Some(m) = CACHE.with(|c| c.borrow().as_ref().filter(|(k, _)| *k == key).map(|(_, m)| m.clone())) { return Some(m); } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let meshes: Vec<_> = st.bodies.iter().filter(|b| app.session.body_visible(&b.name)).map(|b| b.mesh()).collect(); // Every new map gets a new version (the GPU uploads it once). let version = VERSION.with(|v| { diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rs index 9236e3ada..058c7b1c1 100644 --- a/crates/ui-egui/src/agent_cursor.rs +++ b/crates/ui-egui/src/agent_cursor.rs @@ -279,7 +279,7 @@ pub fn picks(app: &SolveApp, command: &str, params: &Value) -> Vec { { out.push((q[0] + q[1] + q[2] + q[3]) / 4.0); } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let sketch = app.session.active_sketch.and_then(|s| st.sketch(s)).map(|ss| ss.plane); walk(params, None, &mut |key, v| { let num = |i: usize| v.get(i).and_then(Value::as_f64).filter(|x| x.is_finite()); diff --git a/crates/ui-egui/src/blend_arrow_tests.rs b/crates/ui-egui/src/blend_arrow_tests.rs index 9ad9f0d22..fb9821e9d 100644 --- a/crates/ui-egui/src/blend_arrow_tests.rs +++ b/crates/ui-egui/src/blend_arrow_tests.rs @@ -21,7 +21,7 @@ fn l_step() -> Harness { } fn edge(h: &Harness, p: Vec3) -> Sel { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let m = st.body("Body1").unwrap().mesh(); let i = m.edges.iter().position(|e| e.windows(2).any(|w| p.dist_to_segment(w[0], w[1]) < 1e-9)).expect("an edge there"); Sel::Edge { body: "Body1".into(), index: i, point: p } @@ -29,7 +29,7 @@ fn edge(h: &Harness, p: Vec3) -> Sel { fn grow(h: &Harness, s: &Sel) -> Vec3 { let Sel::Edge { body, index, point } = s else { panic!("an edge") }; - blend_grow_dir(&h.app.session.world_state().body(body).unwrap().mesh(), *index, *point).unwrap() + blend_grow_dir(&h.app.session.world_state().unwrap().body(body).unwrap().mesh(), *index, *point).unwrap() } fn close(a: Vec3, b: Vec3) -> bool { diff --git a/crates/ui-egui/src/blend_dialog_tests.rs b/crates/ui-egui/src/blend_dialog_tests.rs index 09aaa8a5f..1956ee46e 100644 --- a/crates/ui-egui/src/blend_dialog_tests.rs +++ b/crates/ui-egui/src/blend_dialog_tests.rs @@ -55,7 +55,7 @@ fn edges_at_each_end_make_a_blend_and_come_back_in_an_edit() { assert_eq!((a.as_str(), b.as_str()), ("A", "B")); assert_eq!(continuity, [Continuity::G2, Continuity::G1]); assert_eq!((bulge, seam, stitch), ([0.5, 0.0], None, false)); - assert_eq!(h.app.session.world_state().bodies.len(), 3, "a new surface body beside the boxes"); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 3, "a new surface body beside the boxes"); // A blend made by the command with a seam the dialog does not show: an edit keeps it. h.app.session.execute("edit.undo", &json!({})).unwrap(); h.app @@ -78,5 +78,5 @@ fn edges_at_each_end_make_a_blend_and_come_back_in_an_edit() { assert_eq!(continuity, [Continuity::G2, Continuity::G1]); assert_eq!(seam, Some([Vec3::new(0.0, 10.0, 10.0), Vec3::new(0.0, 20.0, 15.0)])); assert!(stitch); - assert_eq!(h.app.session.world_state().bodies.len(), 1, "stitched onto both boxes"); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1, "stitched onto both boxes"); } diff --git a/crates/ui-egui/src/boundary_dialog_tests.rs b/crates/ui-egui/src/boundary_dialog_tests.rs index 54a1c44d8..f73840b8b 100644 --- a/crates/ui-egui/src/boundary_dialog_tests.rs +++ b/crates/ui-egui/src/boundary_dialog_tests.rs @@ -40,7 +40,7 @@ fn a_loop_of_sketch_curves_is_the_loop_patch() { let FeatureKind::SurfaceBoundary { curves, orders, .. } = &f.kind else { panic!("{:?}", f.kind) }; assert_eq!(curves, &["s1", "s2", "s3", "s4"]); assert!(orders.iter().all(|o| *o == Continuity::G1), "{orders:?}"); - assert_eq!(h.app.session.world_state().bodies.len(), 1); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); } /// A quarter cylinder sheet (its top edge open at y = 10, z = 0) and a 3D line above it. @@ -84,7 +84,7 @@ fn edges_and_curves_make_a_network_and_come_back_in_an_edit() { assert_eq!(u[0].continuity, Continuity::G2); assert_eq!(u[1].curves, vec![top.clone()]); // Joined into the sheet: one body, two faces. - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); assert_eq!(st.bodies.len(), 1); assert_eq!(st.body(&body).map(|b| b.body.face_count()), Some(2)); drop(st); @@ -123,5 +123,5 @@ fn curves_that_meet_are_one_chain() { assert_eq!(p["v"], json!([{"sketch": sketch, "curves": ["c"]}, {"sketch": sketch, "curves": ["d"]}]), "{p}"); // And it builds: the chain a1–a2 is one boundary of the patch. h.app.run("surface.boundary", p.clone()).unwrap(); - assert_eq!(h.app.session.world_state().bodies.len(), 1); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); } diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index ee5592ebf..9b3e516d9 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -281,7 +281,7 @@ fn offer_bodies(app: &mut SolveApp, names: &[String], take: Take) -> bool { /// The bodies in a group (none for sketch and plane groups). pub fn group_bodies(app: &SolveApp, id: u64) -> Vec { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); find_group(app, id) .filter(|g| g.folder == "bodies") .map(|g| g.items.iter().filter(|b| st.body(b).is_some()).cloned().collect()) @@ -378,7 +378,7 @@ pub fn toggle_folder(app: &mut SolveApp, key: &str) { pub fn selection_group(app: &SolveApp, target: &Target) -> Option { let (comp, folder) = match target { Target::Body { name } => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let b = st.body(name)?; (b.component, "bodies") } @@ -2616,7 +2616,7 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { let tk = Tokens::get(); let proj = crate::viewport::projection(app, rect); let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect); - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); for id in app .session .visibility diff --git a/crates/ui-egui/src/browser/features.rs b/crates/ui-egui/src/browser/features.rs index 5ebae12a0..08c7bf24b 100644 --- a/crates/ui-egui/src/browser/features.rs +++ b/crates/ui-egui/src/browser/features.rs @@ -18,7 +18,7 @@ pub(crate) fn reveal(app: &mut SolveApp, id: u64, body: &str) { } let component = feature.component; let state = app.session.model.state(); - let world = app.session.world_state(); + let world = crate::open_meshing::session_world(&app.session); let Some(source) = world.body(body).map(|selected| selected.definition_name()) else { return }; let Some((_, path, _)) = app .session @@ -234,7 +234,7 @@ mod tests { } fn find_in_timeline(app: &mut SolveApp, feature: u64, body: &str) { - let state = app.session.world_state(); + let state = app.session.world_state().unwrap(); let model_body = state.body(body).unwrap(); let names = solidcraft_engine::doc::naming::face_names(model_body); let index = names.iter().position(|name| name.starts_with(&format!("F{feature}:"))).unwrap(); @@ -416,7 +416,7 @@ mod tests { let inserted = h.app.run("component.insert_design", json!({"path":source.0.to_string_lossy()})).unwrap(); let path = vec![inserted["occurrence"].as_u64().unwrap()]; let name = h.app.session.occurrence_bodies(&path, false).unwrap()[0].clone(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let owner = state.body(&name).unwrap().feature; assert_ne!(owner, base); h.app.session.selection = vec![Sel::Face { body: name, index: 0, point: solidcraft_engine::geom::Vec3::ZERO }]; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1dec97603..acc50954c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -19,7 +19,7 @@ use crate::viewport::{Proj, projected_polygon}; /// Where the dialog's geometry is: a base point and, for values that can be dragged, the /// direction a growing value points. pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let first = d.inputs.first()?.items.first()?; let (at, normal) = match first { Sel::Profile { sketch, index } => { @@ -205,7 +205,7 @@ fn reference_height(app: &SolveApp, d: &Dialog, label: &str, plane: &solidcraft_ let point = crate::dialogs::object_point(&d.inputs, label)?; let p = point.as_array()?; let p = Vec3::new(p.first()?.as_f64()?, p.get(1)?.as_f64()?, p.get(2)?.as_f64()?); - Some(solidcraft_engine::doc::object_height(&app.session.world_state(), plane, centre, p)) + Some(solidcraft_engine::doc::object_height(&crate::open_meshing::session_world(&app.session), plane, centre, p)) } /// The two faces at an edge, near `p`: for each, the normal and centroid of its triangle nearest @@ -256,7 +256,7 @@ pub(crate) fn blend_grow_dir(m: &Mesh, index: usize, p: Vec3) -> Option { pub(crate) fn chamfer_face_dirs(app: &SolveApp, d: &Dialog, at: Vec3) -> Option<(Vec3, Vec3)> { let Kind::Fillet { chamfer: true, ctype: 1, flip, .. } = &d.kind else { return None }; let Some(Sel::Edge { body, index, .. }) = d.inputs.first()?.items.first() else { return None }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let mesh = st.body(body)?.mesh(); let sides = edge_sides(&mesh, *index, at)?; let [(n1, c1), (n2, c2)] = sides.as_slice() else { return None }; @@ -481,7 +481,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, }); let all_span = if matches!(d.kind, Kind::Extrude { all: true, .. }) { dir.and_then(|n| { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let plane = match d.inputs.first()?.items.first()? { Sel::Profile { sketch, .. } => profile_plane(app, *sketch)?, _ => solidcraft_engine::geom::Plane::from_normal(base, n)?, @@ -611,7 +611,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, let px = 2.0 * half_height / f64::from(proj.rect.height().max(1.0)); let ang = crate::length_input::eval(&app.session.doc, taper, ValueKind::Angle).ok().filter(|v| v.is_finite()).unwrap_or(0.0); let before = taper.clone(); - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let regions: Vec<&solidcraft_engine::geom::Region2> = d .inputs .first() @@ -1070,7 +1070,7 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain } let t = Tokens::get(); let Kind::Fillet { chamfer: false, .. } = d.kind else { return false }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let edges: Vec<(std::sync::Arc, usize, Vec3, Vec3)> = d .inputs .first() @@ -1596,7 +1596,7 @@ fn revolve_convention(d: &Dialog) -> solidcraft_engine::doc::RevolveConvention { fn revolve_display_extent(app: &SolveApp, d: &Dialog, axis: (Vec3, Vec3)) -> Option { let Sel::Profile { sketch, .. } = d.inputs.first()?.items.first()? else { return None }; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let ss = state.sketch(*sketch)?; let regions: Vec<_> = d .inputs diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbe2c82e9..105989e0c 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -314,7 +314,7 @@ fn touched_bodies(app: &SolveApp) -> Vec { } fn body_feature(app: &SolveApp, body: &str) -> Option { - app.session.world_state().body(body).map(|b| b.feature) + crate::open_meshing::session_world(&app.session).body(body).map(|b| b.feature) } /// Bodies in a component and its subcomponents. @@ -449,7 +449,7 @@ fn picked_face_feature(app: &SolveApp) -> Option { Sel::Face { body, index, .. } => Some((body, *index)), _ => None, })?; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let body = state.body(body)?; let names = solidcraft_engine::doc::naming::face_names(body); let name = names.get(index)?; @@ -677,7 +677,7 @@ fn sketch_items(app: &SolveApp, id: u64) -> Vec { let profiles = !app.session.visibility.hidden_profiles.contains(&id); let dims = app.session.visibility.shown_dimensions.contains(&id); let editing = app.session.active_sketch == Some(id); - let has_profiles = app.session.world_state().sketch(id).is_some_and(|s| !s.profiles.is_empty()); + let has_profiles = crate::open_meshing::session_world(&app.session).sketch(id).is_some_and(|s| !s.profiles.is_empty()); vec![ act("ui.extrudeSketch", "Extrude", "extrude").key("E").with(json!({ "sketch": id })).on(has_profiles && !editing), Item::sep(), @@ -948,7 +948,7 @@ fn alignment_items(selection: &[Sel]) -> Vec { fn sketch_entity_items(app: &SolveApp) -> Vec { use solidcraft_engine::sketch::CurveKind; let Some(sid) = app.session.active_sketch else { return Vec::new() }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = st.sketch(sid) else { return Vec::new() }; if app.session.selection.iter().any(|sel| matches!(sel, Sel::SketchMidpoint { .. })) { return alignment_items(&app.session.selection); @@ -1202,7 +1202,7 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } "ui.isolate" => { // The picked bodies stay (shown first if they were hidden), everything else goes. - let others: Vec = app.session.world_state().bodies.iter().map(|b| b.name.clone()).filter(|b| !bodies.contains(b)).collect(); + let others: Vec = crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).filter(|b| !bodies.contains(b)).collect(); if !bodies.is_empty() { let _ = app.run("browser.visibility", json!({ "items": bodies, "visible": true })); } @@ -1476,14 +1476,14 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } "ui.extrudeSketch" => { if let Some(id) = id_of(&p, "sketch") { - let n = app.session.world_state().sketch(id).map_or(0, |s| s.profiles.len()); + let n = crate::open_meshing::session_world(&app.session).sketch(id).map_or(0, |s| s.profiles.len()); let items: Vec = (0..n).map(|i| json!({"type": "profile", "sketch": id, "index": i})).collect(); let _ = app.run("select.set", json!({ "items": items })); app.start("solid.extrude"); } } "ui.lookAt" => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); if let Some(ss) = id_of(&p, "sketch").and_then(|id| st.sketch(id)) { let to = crate::dialogs::onto_sketch(app.cam.looking_from(ss.plane.normal()), ss); app.animate_to(to); @@ -1609,7 +1609,7 @@ pub fn rename_selection(app: &mut SolveApp, at: Pos2) -> bool { /// Add the edges that continue the selected edges smoothly to the selection. fn tangent_chain(app: &mut SolveApp) { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let mut out: Vec = Vec::new(); for s in &app.session.selection { let Sel::Edge { body, index, .. } = s else { continue }; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 62d7c376b..b2c3df404 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -244,7 +244,7 @@ fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result | "browser.collapse_all" ) && app.session.active_sketch.is_none() - && app.session.world_state().bodies.len() == 1 + && crate::open_meshing::session_world(&app.session).bodies.len() == 1 && app.session.undo.len() <= 2 { app.fit_view(); @@ -377,7 +377,7 @@ pub fn request_scope(app: &SolveApp, params: &Value) -> Result solidcraft_engine::render::Scene { +pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides) -> Result { let mut scene = solidcraft_engine::view::scene_with_thread_markings( &app.session, &app.cam, @@ -386,9 +386,10 @@ pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides &crate::viewport::scene_palette(app.viewport_dark(), app.preferences.color_vision), guides, app.preferences.cosmetic_threads, - ); + ) + .map_err(|e| e.to_string())?; scene.plain_cap = !crate::viewport::section_hatch(app); - scene + Ok(scene) } /// The grid and the origin's axes as the window shows them (the Grid and Origin switches). @@ -402,7 +403,7 @@ pub(crate) fn window_guides(app: &SolveApp) -> solidcraft_engine::view::Guides { /// A picture of the view as the window shows it, RGBA, drawn on the GPU with the viewport's /// pipelines (the renderer the app installs). pub(crate) fn view_rgba(app: &SolveApp, w: u32, h: u32) -> Result, String> { - solidcraft_engine::capture::rgba(&view_scene(app, window_guides(app)), &app.cam, w, h).map(|p| p.rgba) + solidcraft_engine::capture::rgba(&view_scene(app, window_guides(app))?, &app.cam, w, h).map(|p| p.rgba) } /// [`view_rgba`] as PNG. @@ -815,7 +816,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> let world = if let Some(w) = p.get("world") { Some(solidcraft_engine::geom::Vec3::new(num(w, 0), num(w, 1), num(w, 2))) } else if let Some(s) = p.get("sketch") { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); app.session .active_sketch .and_then(|id| st.sketch(id)) @@ -857,7 +858,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } "ui.sketchToScreen" => { // Screen points of active-sketch coordinates (for driving sketch interaction). - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let (Some(rect), Some(ss)) = (app.viewport.rect, app.session.active_sketch.and_then(|s| st.sketch(s))) else { return err("no active sketch in a drawn viewport"); }; @@ -1032,7 +1033,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> if let Some(Err(e)) = s("path").map(vfs::check) { return err(e); } - let scene = view_scene(app, guides); + let scene = match view_scene(app, guides) { + Ok(scene) => scene, + Err(e) => return err(e), + }; let png = match solidcraft_engine::capture::png(&scene, &app.cam, w, h) { Ok(png) => png, Err(e) => return err(format!("render failed: {e}")), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0d288fa60..62665a305 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -778,7 +778,7 @@ impl Dialog { pub fn for_command(app: &SolveApp, id: &str) -> Option { let s = &app.session; - let has_bodies = !s.world_state().bodies.is_empty(); + let has_bodies = !crate::open_meshing::session_world(s).bodies.is_empty(); let mut d = match id { "sketch.create" => Dialog::new(Kind::Sketch, vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)]), "solid.extrude" => Dialog::new( @@ -1118,7 +1118,7 @@ impl Dialog { } *of = picks.to_vec(); *suggested = picks.first().and_then(|sel| match sel { - Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&s.world_state(), *point).ok().map(|value| { + Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&crate::open_meshing::session_world(s), *point).ok().map(|value| { solidcraft_engine::doc::parse_metric_thread(&value).map(|(d, p)| crate::dialogs_thread::designation(d, p)).unwrap_or(value) }), _ => None, @@ -1359,7 +1359,7 @@ impl Dialog { return None; } let Some(Hit::Face { body, index, .. }) = hits.iter().find(|h| matches!(h, Hit::Face { .. })) else { return None }; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let near: Vec = hits .iter() .filter_map(|h| match h { @@ -1396,7 +1396,7 @@ impl Dialog { && let Hit::SketchPoint { sketch, at, .. } = h { let snap = snap?; - return snap.place_at(s.world_state().sketch(*sketch)?.plane.to_world(*at)); + return snap.place_at(crate::open_meshing::session_world(s).sketch(*sketch)?.plane.to_world(*at)); } if let Some(sel) = self.circle_centre_pick(s, inp, h, snap) { return Some(sel); @@ -1629,7 +1629,7 @@ fn fillet_edges(s: &Session, sel: &Sel, chain: bool) -> Vec { let mut picked = crate::viewport::picked_selection(s, sel); if chain && let Sel::Edge { body, index, .. } = sel - && let Some(b) = s.world_state().body(body) + && let Some(b) = crate::open_meshing::session_world(s).body(body) { let m = b.mesh(); for i in m.tangent_chain(*index, 2f64.to_radians()) { @@ -1667,7 +1667,7 @@ fn single_hole_point(app: &SolveApp, d: &Dialog, x: &Sel) -> Option<(u64, String if let Some(k) = d.extra.get("single_point").filter(|k| k["point"] == pt3(*point)) { return Some((k["sketch"].as_u64()?, k["id"].as_str()?.to_string())); } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); crate::viewport::visible_sketches(app).into_iter().find_map(|sid| { let ss = st.sketch(sid)?; let shown = SnapPoints::of(&ss.sketch); @@ -1771,7 +1771,7 @@ impl FaceSnap { /// Face `face` of `body`, for sketch points at `near` (in the world). fn new(s: &Session, body: &str, face: usize, near: &[Vec3]) -> FaceSnap { let mut snap = FaceSnap { body: body.to_string(), face, plane: None, tris: Vec::new(), budget: std::cell::Cell::new(snap_budget()) }; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let (Some((origin, normal)), Some(b)) = (planar_face(s, body, face), st.body(body)) else { return snap }; let m = b.mesh(); #[cfg(test)] @@ -1864,7 +1864,7 @@ mod face_snap_tests { let mut s = Session::default(); s.execute("solid.box", &json!({"length":40,"width":30,"height":20})).unwrap(); let top = |s: &Session| { - let st = s.world_state(); + let st = s.world_state().unwrap(); let b = st.bodies.first().unwrap(); let faces = b.body.faces(1e-3).unwrap(); let f = faces.iter().max_by(|a, b| a.centroid.z.total_cmp(&b.centroid.z)).unwrap(); @@ -1939,7 +1939,7 @@ fn profiles_used(s: &Session, sketch: u64) -> bool { /// The plane of a planar body face: (point on it, unit normal). pub fn planar_face(s: &Session, body: &str, face: usize) -> Option<(Vec3, Vec3)> { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let known = FACE_PLANES.with(|c| { let c = c.borrow(); c.0.as_ref().filter(|k| std::sync::Arc::ptr_eq(k, &st)).and_then(|_| c.1.iter().find(|(b, f, _)| b == body && *f == face).map(|x| x.2)) @@ -2294,7 +2294,7 @@ pub(crate) fn selection_label(s: &Session, d: &Dialog, inp: &SelInput, item: &Se Sel::Vertex { body, .. } if !body.is_empty() => format!("{body} · point"), Sel::Feature { id } => s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_else(|| format!("Feature {id}")), Sel::Vertex { body, point } if body.is_empty() => { - let state = s.world_state(); + let state = crate::open_meshing::session_world(s); let p = s.active_sketch.and_then(|id| state.sketch(id)).map(|sk| sk.plane.to_local(*point)).unwrap_or_default(); format!("({:.2}, {:.2}) mm", p.x, p.y) } @@ -2530,7 +2530,7 @@ fn update_fill_cells(app: &SolveApp, d: &mut Dialog) { // Editing: the tools as they were before this feature (it may have removed them). let st = match d.editing { Some((id, _)) => app.session.model.state_before(id), - None => app.session.world_state(), + None => crate::open_meshing::session_world(&app.session), }; let found = fill_cells(&st, &names); let kept: Vec = cells.iter().filter(|c| c.2).map(|c| c.1.clone()).collect(); @@ -2695,7 +2695,8 @@ fn auto_operation(app: &SolveApp, d: &mut Dialog) { { side = crate::smart_extrude::side(reach, 0); } - let Some(fresh) = solidcraft_engine::auto_operation(&app.session, ¶ms).and_then(|op| OPS.iter().position(|o| *o == op)) else { + // A model that cannot be placed suggests nothing; running the command reports why. + let Some(fresh) = solidcraft_engine::auto_operation(&app.session, ¶ms).ok().flatten().and_then(|op| OPS.iter().position(|o| *o == op)) else { return; }; if let Kind::Extrude { operation, smart, .. } = &mut d.kind { @@ -2708,7 +2709,9 @@ fn auto_operation(app: &SolveApp, d: &mut Dialog) { fn picked_side(app: &SolveApp, d: &Dialog, first: &Sel) -> Option { let normal = match first { Sel::Profile { sketch, .. } => crate::canvas::profile_plane(app, *sketch)?.normal(), - Sel::SketchCurve { .. } => app.session.world_state().sketch(picks_sketch(app, std::slice::from_ref(first), None)?)?.plane.normal(), + Sel::SketchCurve { .. } => { + crate::open_meshing::session_world(&app.session).sketch(picks_sketch(app, std::slice::from_ref(first), None)?)?.plane.normal() + } Sel::Face { .. } => return Some(0), _ => return None, }; @@ -3487,7 +3490,7 @@ pub(crate) fn plane_by_name(s: &Session, name: &str) -> Option Result }; if let Some(sketch) = original_all && !d.profile_selection_changed - && let Some(ss) = app.session.world_state().sketch(sketch.0) + && let Some(ss) = crate::open_meshing::session_world(&app.session).sketch(sketch.0) { let mut selected: Vec = sels(d, 0) .iter() @@ -3804,7 +3807,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S }; if *thin { // The picked curves, and the outlines (outer and holes) of picked profiles. - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let mut curves = sels(d, 0).curve_ids(); let mut sketch = None; for x in sels(d, 0) { @@ -3845,7 +3848,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S } // Coplanar faces of one body share one sketch and Boolean. Mixed selections // retain their original order and explicit face-body scope. - let state = s.world_state(); + let state = crate::open_meshing::session_world(s); let mut group: Option<(String, solidcraft_engine::geom::Plane, Vec)> = None; let mut coplanar = true; for pick in sels(d, 0) { @@ -3919,7 +3922,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Kind::Fillet { radius, chamfer, ctype, distance2, angle, flip, .. } => { need(0, "edges")?; // Faces stand for all their edges. - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let mut pts: Vec = Vec::new(); for x in sels(d, 0) { match x { @@ -4130,7 +4133,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S let path = match sels(d, 0).first() { Some(Sel::SketchCurve { id, sketch: Some(named) }) => json!({"sketch": named, "curve": id}), Some(Sel::SketchCurve { id, .. }) => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let matches: Vec = st .sketches .iter() @@ -4260,7 +4263,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S // A straight sketch line, in the sketch it was picked in (#1552). Some(Sel::SketchCurve { id, sketch: named }) => { let picked = named.or_else(|| d.extra.get("tool_sketch").and_then(Value::as_u64)); - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let holding: Vec = st.sketches.iter().filter(|ss| ss.sketch.curve_index(id).is_some()).map(|ss| ss.feature).collect(); let sketch = match picked { Some(k) if holding.contains(&k) => k, @@ -4590,7 +4593,7 @@ fn pattern_features(s: &Session, objects: &[Sel]) -> Vec { } fn source_features(s: &Session, bodies: &[String]) -> Vec { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let mut features: Vec = Vec::new(); for n in bodies { if let Some(f) = st.body(n).and_then(|b| s.doc.feature(b.feature)).map(|f| f.name.clone()) @@ -4619,7 +4622,7 @@ pub(crate) fn picks_sketch(app: &SolveApp, sels: &[Sel], not: Option) -> Op } pub(crate) fn curves_sketch(app: &SolveApp, ids: &[String], not: Option) -> Option { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let has = |sid: u64| st.sketch(sid).is_some_and(|ss| ids.iter().all(|id| ss.sketch.curve_index(id).is_some() || ss.sketch.wire_index(id).is_some())); if let Some(a) = app.session.active_sketch @@ -4643,7 +4646,7 @@ pub fn axis_of(app: &SolveApp, sel: &Sel) -> Option<(Vec3, Vec3)> { n => solidcraft_engine::view::construction_axes(&app.session).into_iter().find(|(_, an, _, _)| an == n).map(|(_, _, o, d)| (o, d)), }, Sel::SketchCurve { id, .. } => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let sid = picks_sketch(app, std::slice::from_ref(sel), None)?; let ss = st.sketch(sid)?; let (pa, pb) = if let Some(i) = ss.sketch.curve_index(id) { @@ -4661,7 +4664,7 @@ pub fn axis_of(app: &SolveApp, sel: &Sel) -> Option<(Vec3, Vec3)> { } // A straight model edge, along it; a circular one, about its axis. Sel::Edge { body, index, .. } => { - let b = app.session.world_state().body(body).cloned()?; + let b = crate::open_meshing::session_world(&app.session).body(body).cloned()?; let m = b.mesh(); let e = m.edges.get(*index)?; let (a, z) = (*e.first()?, *e.last()?); @@ -4826,7 +4829,7 @@ fn stored_frames(s: &Session) -> Option Option { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let frames = stored_frames(s); let mut best: Option<(f64, Sel)> = None; for b in &st.bodies { @@ -4849,7 +4852,7 @@ pub(crate) fn face_sel(s: &Session, p0: Vec3) -> Option { if !p0.is_finite() { return None; } - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let frames = stored_frames(s); let mut best: Option<(f64, &solidcraft_engine::doc::ModelBody, usize, Vec3)> = None; for b in &st.bodies { @@ -4918,7 +4921,7 @@ fn emboss_face_sel(s: &Session, component: u64, face: &solidcraft_engine::doc::E let world_name = s.doc.world_body_name(&source, &face.body, owner, &face.path); let author = solidcraft_engine::doc::EmbossFace::component_frame(&s.doc, component, &face.author_path).ok()?; let point = solidcraft_engine::doc::apply_point(&author, face.at.0); - s.world_state().body(&world_name)?; + crate::open_meshing::session_world(s).body(&world_name)?; Some(Sel::Face { body: world_name, index, point }) } @@ -4989,7 +4992,7 @@ fn construct_ref(app: &SolveApp, sel: &Sel) -> Result { }, Sel::SketchCurve { id, sketch: Some(sketch) } => json!({"sketch": sketch, "curve": id}), Sel::SketchCurve { id, .. } => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let sketches: Vec = st .sketches .iter() @@ -5100,7 +5103,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { @@ -5266,9 +5269,9 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { - s.world_state().body(&body).and_then(|b| b.mesh().edges.get(index).and_then(|e| e.last().copied())) - } + Sel::Edge { body, index, .. } => crate::open_meshing::session_world(s) + .body(&body) + .and_then(|b| b.mesh().edges.get(index).and_then(|e| e.last().copied())), _ => None, }); let swapped = first_end.is_some_and(|e| e.dist(start.0) < 1e-6); @@ -5369,7 +5372,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { // A Single hole at a sketch point: picked on its face where the point is now. let id = sp.ids.first().cloned().unwrap_or_default(); - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let at = st .sketch(sp.sketch.0) .and_then(|ss| ss.sketch.points.iter().find(|p| p.id == id).map(|p| ss.plane.to_world(p.pos))) diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index bf25da503..ba56e5618 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -60,8 +60,8 @@ fn fixture() -> Harness { fn representative(h: &Harness, command: &str) -> Dialog { let mut d = Dialog::for_command(&h.app, command).unwrap(); let s = &h.app.session; - let profiles: Vec<_> = s.world_state().sketches.iter().take(2).map(|sk| Sel::Profile { sketch: sk.feature, index: 0 }).collect(); - let path = s.world_state().sketches.last().unwrap().sketch.curves.first().unwrap().id.clone(); + let profiles: Vec<_> = s.world_state().unwrap().sketches.iter().take(2).map(|sk| Sel::Profile { sketch: sk.feature, index: 0 }).collect(); + let path = s.world_state().unwrap().sketches.last().unwrap().sketch.curves.first().unwrap().id.clone(); for (index, input) in d.inputs.iter_mut().enumerate() { if command == "joint.gear" { continue; @@ -107,7 +107,7 @@ fn representative(h: &Harness, command: &str) -> Dialog { }; } if let Kind::PathPlane { sketch, .. } = &mut d.kind { - *sketch = Some(s.world_state().sketches.last().unwrap().feature); + *sketch = Some(s.world_state().unwrap().sketches.last().unwrap().feature); } if let Kind::Mirror = &d.kind { d.extra.insert("combine".into(), json!(false)); diff --git a/crates/ui-egui/src/dialogs_appearance.rs b/crates/ui-egui/src/dialogs_appearance.rs index 4d0d2cdec..b33e6585a 100644 --- a/crates/ui-egui/src/dialogs_appearance.rs +++ b/crates/ui-egui/src/dialogs_appearance.rs @@ -199,7 +199,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { (id == "appearance.assign").then(|| { let faces = app.session.selection.iter().any(|s| matches!(s, Sel::Face { .. })) && !app.session.selection.iter().any(|s| matches!(s, Sel::Body { .. })); - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let body_look = |body: &solidcraft_engine::doc::ModelBody| { app.session.doc.model_body_look(body).or_else(|| { (body.body.paint().is_some() || body.imported.is_some() || body.body.color().is_some()).then(|| { diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index d54698139..8a943edbe 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -356,7 +356,7 @@ pub fn find_joint(app: &mut SolveApp, id: u64) { /// are placed; occurrence 0 is the root, holding the bodies outside every occurrence. pub fn occurrence_bounds(s: &Session, occs: &[u64]) -> Aabb3 { let model = s.model.state(); - let world = s.world_state(); + let world = crate::open_meshing::session_world(s); let mut bb = Aabb3::default(); for (name, _, path, _) in s.doc.body_frames(&model) { let on = occs.iter().any(|o| if *o == 0 { path.is_empty() } else { path.contains(o) }); @@ -394,7 +394,7 @@ pub struct SnapPt { /// The occurrence placing a world body (0: the root design), the instance its name says. pub(crate) fn occurrence_of_body(s: &Session, body: &str) -> Option { // The world name tells the instance: a further occurrence of a component is not its first. - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let b = st.body(body)?; if s.doc.model_body_component(b) == 0 { return Some(0); @@ -453,7 +453,7 @@ fn face_normal_near(m: &Mesh, f: u32, p: Vec3) -> Option { /// The snap a picked item stands for (world coordinates, as the viewport shows them). pub fn snap_of(s: &Session, sel: &Sel) -> Option { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let (body, mut snap) = match sel { Sel::Face { body, index, point } => { let b = st.body(body)?; @@ -781,7 +781,7 @@ fn interference(app: &mut SolveApp, picked: &[Sel], clearance: &str) -> (Value, Ok(v) => v, Err(e) => return (json!({ "error": e }), Vec::new()), }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let mut meshes = Vec::new(); for hit in r["overlaps"].as_array().into_iter().flatten() { let (Some(a), Some(b)) = (hit["a"].as_str().and_then(|n| st.body(n)), hit["b"].as_str().and_then(|n| st.body(n))) else { continue }; diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index 07b060104..ef2ef047d 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -562,7 +562,7 @@ fn face_snaps_mate_face_to_face() { for (id, p) in c { app.run(&id, p).unwrap(); } - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let b = st.body("Body2").unwrap().mesh().bounds(); assert!((b.min.z - 10.0).abs() < 1e-6 && (b.max.z - 20.0).abs() < 1e-6, "{b:?}"); // Edit Joint shows the mate unflipped; Flip puts B back into A's volume. @@ -575,7 +575,7 @@ fn face_snaps_mate_face_to_face() { for (id, p) in apply_commands(&app, &e).unwrap() { app.run(&id, p).unwrap(); } - let b = app.session.world_state().body("Body2").unwrap().mesh().bounds(); + let b = app.session.world_state().unwrap().body("Body2").unwrap().mesh().bounds(); assert!((b.max.z - 10.0).abs() < 1e-6, "{b:?}"); } diff --git a/crates/ui-egui/src/dialogs_cam_tests.rs b/crates/ui-egui/src/dialogs_cam_tests.rs index 47df9f934..6111a636c 100644 --- a/crates/ui-egui/src/dialogs_cam_tests.rs +++ b/crates/ui-egui/src/dialogs_cam_tests.rs @@ -34,7 +34,7 @@ fn valve() -> SolveApp { /// A pick of the mesh edge nearest a point. fn edge(app: &SolveApp, p: Vec3) -> Sel { - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let mut best: Option<(f64, Sel)> = None; for b in &st.bodies { for (index, e) in b.mesh().edges.iter().enumerate() { diff --git a/crates/ui-egui/src/dialogs_coupling.rs b/crates/ui-egui/src/dialogs_coupling.rs index abb8b5324..d34774fb9 100644 --- a/crates/ui-egui/src/dialogs_coupling.rs +++ b/crates/ui-egui/src/dialogs_coupling.rs @@ -107,7 +107,7 @@ fn pick(inputs: &[SelInput], i: usize) -> Option<(&str, solidcraft_engine::geom: /// The radius of the round face picked in input `i`. fn picked_radius(s: &Session, inputs: &[SelInput], i: usize) -> Option { let (body, point) = pick(inputs, i)?; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); solidcraft_engine::kernel::cylinder_face_at(&st.body(body)?.body, point).map(|c| c.radius) } diff --git a/crates/ui-egui/src/dialogs_coupling_tests.rs b/crates/ui-egui/src/dialogs_coupling_tests.rs index 888c3ccd5..f6c2f973a 100644 --- a/crates/ui-egui/src/dialogs_coupling_tests.rs +++ b/crates/ui-egui/src/dialogs_coupling_tests.rs @@ -28,7 +28,7 @@ fn discs() -> SolveApp { /// A pick of the round wall a point of the exact geometry lies on (the facets of the wall's mesh /// cut inside it, so the nearest face of any body). fn wall(app: &SolveApp, p: Vec3) -> Sel { - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let mut best: Option<(f64, Sel)> = None; for b in &st.bodies { let m = b.mesh(); diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs index db69a2cec..47f697b42 100644 --- a/crates/ui-egui/src/dialogs_motion.rs +++ b/crates/ui-egui/src/dialogs_motion.rs @@ -777,7 +777,7 @@ pub fn commands(app: &SolveApp, k: &Mo, inputs: &[SelInput]) -> Result = Vec::new(); for x in inputs.first().map(|i| i.items.as_slice()).unwrap_or(&[]) { if let solidcraft_engine::Sel::Body { name } = x - && let Some(b) = app.session.world_state().body(name) + && let Some(b) = crate::open_meshing::session_world(&app.session).body(name) { let comp = app.session.doc.model_body_component(b); if let Some(o) = app.session.doc.occurrence_of(comp).map(|o| o.id) diff --git a/crates/ui-egui/src/dialogs_part_size.rs b/crates/ui-egui/src/dialogs_part_size.rs index 4f252d66c..550948a5d 100644 --- a/crates/ui-egui/src/dialogs_part_size.rs +++ b/crates/ui-egui/src/dialogs_part_size.rs @@ -58,7 +58,7 @@ impl std::fmt::Debug for Resize { /// Resolve a whole definition, including bodies displayed through an occurrence path. pub fn component_for_bodies(app: &SolveApp, bodies: &[String]) -> Option { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let mut component = None; for name in bodies { let body = state.bodies.iter().find(|b| b.name == *name)?; @@ -362,7 +362,7 @@ mod tests { apply(&mut app); assert_eq!(app.session.doc.assembly.joints, joints); assert_eq!(app.session.doc.occurrences, occurrences); - let state = app.session.world_state(); + let state = app.session.world_state().unwrap(); let body = state.bodies.iter().find(|b| app.session.doc.model_body_component(b) == id).unwrap(); let bounds = body.mesh().bounds(); assert!((bounds.max.z - 18.0).abs() < 1e-6 && (bounds.min.z + 15.0).abs() < 1e-6); @@ -371,7 +371,7 @@ mod tests { #[test] fn part_size_resolves_body_face_and_occurrence_contexts_and_rejects_mixed_targets() { let (mut app, id) = part("hex_nut", "M5", None); - let body = app.session.world_state().bodies.iter().find(|b| app.session.doc.model_body_component(b) == id).unwrap().name.clone(); + let body = app.session.world_state().unwrap().bodies.iter().find(|b| app.session.doc.model_body_component(b) == id).unwrap().name.clone(); menu(&mut app, Target::Body { name: body.clone() }); assert_eq!(editor(&app).component, id); crate::dialogs::cancel(&mut app); diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs index 61a388218..dcf78de15 100644 --- a/crates/ui-egui/src/dialogs_sheet.rs +++ b/crates/ui-egui/src/dialogs_sheet.rs @@ -665,7 +665,7 @@ pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map { let ids: Vec = items(inputs, 0).curve_ids(); - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let sketch = items(inputs, 0) .named_sketch() .or_else(|| st.sketches.iter().rev().find(|ss| ids.iter().all(|id| ss.sketch.curve_index(id).is_some())).map(|ss| ss.feature)) @@ -698,7 +698,7 @@ pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let sketch = named .or_else(|| st.sketches.iter().rev().find(|ss| ss.sketch.curve_index(id).is_some()).map(|ss| ss.feature)) .ok_or("the line's sketch is gone")?; @@ -781,7 +781,7 @@ pub fn commands(app: &SolveApp, k: &Sm, inputs: &[SelInput], extra: &Map Option<(Kind, Vec, Map)> { let s = &app.session; - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); let rule_index = |r: &Option| r.as_ref().and_then(|n| rule_list(app).iter().position(|x| &x.name == n)).map_or(0, |i| i + 1); let mut extra = Map::new(); let (k, items): (Sm, Vec) = match kind { @@ -949,7 +949,7 @@ pub fn arrow(app: &SolveApp, d: &Dialog) -> Option { /// from the sheet), and the sheet's thickness along the first. fn edge_frame(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Vec3, f64)> { let Sel::Edge { body, index, point } = d.inputs.first()?.items.first()? else { return None }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let m = st.body(body)?.mesh(); let faces = m.edge_faces.get(*index)?; let area = |f: u32| -> f64 { diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 33f6876a7..82f09f3dd 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -364,7 +364,7 @@ fn sheet_picks(app: &SolveApp, picks: &[Sel]) -> Result { /// A surface builder's stored picks as selections again: its profiles, then its curves. fn sheet_sels(app: &SolveApp, sketch: u64, profiles: Option<&ProfileSel>, curves: &[String]) -> Vec { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let mut sels: Vec = match (profiles, st.sketch(sketch)) { (Some(sel), Some(ss)) => crate::dialogs::profile_indices(ss, sel).into_iter().map(|index| Sel::Profile { sketch, index }).collect(), _ => Vec::new(), @@ -397,7 +397,7 @@ enum Chain { /// The picks grouped into curves: picks of one sketch (or one body) whose ends meet run on into /// one chain, in the order they were first picked; anything else is a curve of its own. fn chains(app: &SolveApp, picks: &[Sel]) -> Result, String> { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); // Each pick: what it belongs to (a sketch or a body), its ends, and how it joins a chain. let mut parts: Vec<(Chain, [Vec3; 2])> = Vec::with_capacity(picks.len()); for x in picks { @@ -939,7 +939,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K FeatureKind::Patch { sketch, edges, crown, continuity, points, .. } => { let mut sels: Vec = edges.iter().filter_map(edge).collect(); if let Some(sk) = sketch { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); if let Some(ss) = st.sketch(sk.0) { sels.extend((0..ss.profiles.len()).map(|index| Sel::Profile { sketch: sk.0, index })); } @@ -1041,7 +1041,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K let tools: Vec = match (with, curves) { (Some(_), _) => Vec::new(), (None, Some(c)) if c.curves.is_empty() => { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); st.sketch(c.sketch.0) .map(|ss| { ss.sketch diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs index 3c5aeae49..41ef8d548 100644 --- a/crates/ui-egui/src/dim_view.rs +++ b/crates/ui-egui/src/dim_view.rs @@ -112,7 +112,7 @@ impl DimensionDraft { let mut scratch = app.session.scratch(); let result = scratch.execute("sketch.dimension", &self.params(expr)).map_err(|e| shown_error("sketch.dimension", &e.to_string()))?; let param = result.get("param").and_then(serde_json::Value::as_str).ok_or("The dimension value is unavailable")?; - let state = scratch.world_state(); + let state = crate::open_meshing::session_world(&scratch); let solved = state.sketch(self.sketch).ok_or("The dimension sketch is unavailable")?; if !solved.report.ok() { return Err("That value conflicts with the sketch constraints".into()); @@ -227,7 +227,7 @@ fn reevaluate(app: &SolveApp, draft: &mut DimensionDraft, expr: &str) { draft.checked_expr = expr.to_string(); match draft.evaluate(app, expr) { Ok(scratch) => { - draft.preview = scratch.world_state(); + draft.preview = crate::open_meshing::session_world(&scratch); draft.preview_doc = scratch.doc.clone(); draft.error = None; } @@ -274,7 +274,7 @@ fn draft_of(app: &SolveApp, sketch: u64, entities: &[String], at: Option, entities: entities.to_vec(), at, checked_expr: expr.clone(), - preview: scratch.world_state(), + preview: crate::open_meshing::session_world(&scratch), preview_doc: scratch.doc.clone(), error: None, driven, @@ -579,7 +579,7 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &P }); let placing = !editing(); let draft = editor_draft.or_else(|| placing.then(|| placement_preview(app)).flatten()); - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { DRAWN.with(|d| d.borrow_mut().clear()); // Only a finished sketch's dimension edited from the model view stays open, at its text. diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs index 1c5b15091..f503448a9 100644 --- a/crates/ui-egui/src/dimension_create_ui_tests.rs +++ b/crates/ui-egui/src/dimension_create_ui_tests.rs @@ -236,7 +236,7 @@ fn edge_and_endpoint_creation_commit_once_and_undo_restores_exact_design() { h.step(&json!({"key":"Enter"})).unwrap(); assert!(!crate::dim_view::editing()); assert_eq!(h.app.session.undo.len(), undo + 1); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!( (sk.point(sk.resolve_point("l1.start").unwrap()).unwrap().dist(sk.point(sk.resolve_point("l1.end").unwrap()).unwrap()) - 30.).abs() @@ -310,7 +310,7 @@ fn rectangle_side_and_fixed_origin_line_dimensions_preserve_other_constraints() place(&mut h, &picks, [10., 5.]); type_value(&mut h, "30 mm"); h.step(&json!({"key":"Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!(sk.point(sk.resolve_point("l1.start").unwrap()).unwrap().len() < 1e-8, "fixed origin remains fixed"); assert!((sk.point(sk.resolve_point("l1.end").unwrap()).unwrap().x - 30.).abs() < 1e-6); @@ -334,7 +334,7 @@ fn rectangle_side_and_fixed_origin_line_dimensions_preserve_other_constraints() place(&mut h, &picks, at); type_value(&mut h, "12 mm"); h.step(&json!({"key":"Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let solved = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); // The sketch's first dimension scales it (#1365): 20 × 10 becomes 24 × 12. assert!((solved.profiles[0].area - 288.).abs() < 1e-5, "the first dimension scales the rectangle: {}", solved.profiles[0].area); @@ -366,7 +366,7 @@ fn pending_second_nested_plane_uses_world_picks_but_one_local_dimension() { h.app.run("occurrence.move", json!({"occurrence":second,"translate":[25,32,40],"axis":[1,0,0],"angle":"35 deg","capture":false})).unwrap(); h.call("ui.view", json!({"view":"top"})); h.app.cam.distance = 90.; - let plane = h.app.session.world_state().sketch(sid).unwrap().plane; + let plane = h.app.session.world_state().unwrap().sketch(sid).unwrap().plane; h.app.cam.target = plane.to_world(Vec2::new(10., 0.)); h.settle(); let baseline = h.app.session.doc.to_json(); @@ -447,7 +447,7 @@ fn dimension_to_fillet_virtual_sharp_keeps_the_arc_and_fixed_origin() { h.step(&json!({"key":"Enter"})).unwrap(); assert!(!crate::dim_view::editing()); assert_eq!(h.app.session.undo.len(), undo + 1); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let solved = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert!(solved.report.ok()); let sk = &solved.sketch; @@ -495,23 +495,23 @@ fn inch_dimension_entry_survives_unit_changes_undo_and_reopen() { h.settle(); type_value(&mut h, "1.3456"); h.step(&json!({"key":"Enter"})).unwrap(); - let edited = h.app.session.world_state(); + let edited = h.app.session.world_state().unwrap(); let edited = &edited.sketch(sketch).unwrap().sketch; assert!(edited.constraints.iter().any(|c| c.kind.value().is_some_and(|v| (v - 1.3456 * 25.4).abs() < 1e-6))); h.app.run("edit.undo", json!({})).unwrap(); - let before = h.app.session.world_state().sketch(sketch).unwrap().sketch.clone(); + let before = h.app.session.world_state().unwrap().sketch(sketch).unwrap().sketch.clone(); let c = before.constraints.iter().find(|c| c.param.is_some()).unwrap(); let p = h.app.session.doc.param(c.param.as_deref().unwrap()).unwrap(); assert_eq!(crate::dim_view::label(&c.kind, Some(&p.expr), false, "in", 2), "1.2345 in"); assert!((c.kind.value().unwrap() - 31.3563).abs() < 1e-6); h.app.run("document.units", json!({"units":"mm"})).unwrap(); - assert_eq!(h.app.session.world_state().sketch(sketch).unwrap().sketch, before); + assert_eq!(h.app.session.world_state().unwrap().sketch(sketch).unwrap().sketch, before); h.app.run("edit.undo", json!({})).unwrap(); assert_eq!(h.app.session.doc.units, "in"); let doc = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); let reopened = solidcraft_engine::Session::new(doc); assert_eq!(reopened.doc.units, "in"); - assert_eq!(reopened.world_state().sketch(sketch).unwrap().sketch, before); + assert_eq!(reopened.world_state().unwrap().sketch(sketch).unwrap().sketch, before); crate::dim_view::cancel(); } @@ -527,7 +527,7 @@ fn placing_a_two_point_dimension_picks_horizontal_vertical_or_aligned() { type_value(&mut h, "10 mm"); h.step(&json!({"key":"Enter"})).unwrap(); assert!(!crate::dim_view::editing()); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let a = sk.point(sk.resolve_point("l1.start").unwrap()).unwrap(); let b = sk.point(sk.resolve_point("l1.end").unwrap()).unwrap(); @@ -562,7 +562,7 @@ fn an_over_constraining_dimension_is_placed_as_a_driven_one() { assert!(!crate::dim_view::editing(), "a driven dimension has no value to edit"); assert_eq!(h.app.session.undo.len(), undo + 1); assert_eq!(h.app.session.doc.params.len(), params, "a driven dimension adds no parameter"); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let solved = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert!(solved.report.ok()); let dims: Vec<_> = solved.sketch.constraints.iter().filter(|c| c.kind.is_dimension()).collect(); @@ -609,7 +609,7 @@ fn keys(h: &mut Harness, text: &str) { } fn solved(h: &Harness) -> solidcraft_engine::sketch::Sketch { - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.clone() } diff --git a/crates/ui-egui/src/drag_snap.rs b/crates/ui-egui/src/drag_snap.rs index d30c9c9d7..e3a47623e 100644 --- a/crates/ui-egui/src/drag_snap.rs +++ b/crates/ui-egui/src/drag_snap.rs @@ -217,7 +217,7 @@ pub fn show(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { return; } let Some(s) = current() else { return }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = app.session.active_sketch.and_then(|i| st.sketch(i)) else { return }; let to = |p: Vec2| proj.to_screen(ss.plane.to_world(p)); let tk = Tokens::get(); diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rs index 0b271fea8..82ef4cf76 100644 --- a/crates/ui-egui/src/extrude_edit_tests.rs +++ b/crates/ui-egui/src/extrude_edit_tests.rs @@ -35,7 +35,7 @@ fn unchanged_all_profiles_includes_profiles_added_after_edit() { h.app.run("sketch.edit", json!({"sketch":"Base"})).unwrap(); h.app.run("sketch.rectangle.two_point", json!({"p0":[20,0],"p1":[25,5]})).unwrap(); h.app.run("sketch.finish", json!({})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let volume: f64 = state.bodies.iter().map(|b| solidcraft_engine::doc::kernel::measure(&b.body).unwrap().volume).sum(); assert!((volume - 1250.0).abs() < 1e-7, "{volume}"); } @@ -57,13 +57,13 @@ fn unchanged_actual_editor_preserves_all_extents_and_parameter_identities() { let mut h = make(p.clone()); let original = extent(&h); let names = h.app.session.doc.find_feature("Depth").unwrap().param_names.clone(); - let before = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let before = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); open(&mut h); h.step(&json!({"widget":"OK"})).unwrap(); assert!(h.app.dialog.is_none(), "{p}: {:?}", h.app.session.log); assert_eq!(extent(&h), original, "{p}"); assert_eq!(h.app.session.doc.find_feature("Depth").unwrap().param_names, names, "{p}"); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), before, "{p}"); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), before, "{p}"); } } @@ -74,7 +74,7 @@ fn negative_edit_keeps_downstream_distance_reference_positive() { open(&mut h); h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(h.app.session.doc.eval("d1", solidcraft_engine::doc::expr::Kind::Length).unwrap(), 10.0); - assert_eq!(h.app.session.world_state().body("Dependent").unwrap().mesh().bounds().max.z, 10.0); + assert_eq!(h.app.session.world_state().unwrap().body("Dependent").unwrap().mesh().bounds().max.z, 10.0); } #[test] @@ -102,7 +102,7 @@ fn to_offset_canvas_edit_changes_offset_and_one_undo_restores_extent() { h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(extent(&h).to_offset.as_deref(), Some("4 mm")); assert_eq!(extent(&h).distance, original.distance); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds().max.z, 19.0); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().max.z, 19.0); h.app.run("edit.undo", json!({})).unwrap(); assert_eq!(extent(&h), original); } @@ -124,7 +124,7 @@ fn moved_owner_references_survive_actual_edit_with_another_component_active() { h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(extent(&h), original); assert_eq!(h.app.session.active_component, active); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds().max.z, 37.0); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().max.z, 37.0); } #[test] @@ -136,7 +136,7 @@ fn dragged_to_object_handle_edits_offset_not_dormant_distance() { h.step(&json!({"widget":"OK"})).unwrap(); assert!(h.app.dialog.is_none(), "{:?}", h.app.session.log); assert_eq!(extent(&h).distance, original.distance); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let z = state.body("Main").unwrap().mesh().bounds().max.z; assert!((z - 21.0).abs() < 0.1, "dragged end {z}"); } @@ -150,12 +150,12 @@ fn referenced_offset_recomputes_after_edit_and_save_reopen() { h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(extent(&h).to_offset.as_deref(), Some("clearance")); h.app.run("parameters.change", json!({"name":"clearance","expression":"6 mm"})).unwrap(); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds().max.z, 21.0); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().max.z, 21.0); let path = h.dir.join("extent.solidcraft"); h.app.run("file.save", json!({"path":path})).unwrap(); h.app.run("doc.open", json!({"path":path})).unwrap(); assert_eq!(extent(&h).to_offset.as_deref(), Some("clearance")); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds().max.z, 21.0); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().max.z, 21.0); } #[test] @@ -166,7 +166,7 @@ fn from_object_start_can_be_explicitly_changed_to_profile_plane() { h.step(&json!({"click":{"handle":"dialog:Start:Profile Plane"}})).unwrap(); h.step(&json!({"widget":"OK"})).unwrap(); assert!(extent(&h).from.is_none()); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds().min.z, 0.0); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().min.z, 0.0); } #[test] @@ -178,7 +178,7 @@ fn explicit_reverse_keeps_original_expression_and_parameter_sign() { assert_eq!(extent(&h).distance, "10"); assert_eq!(extent(&h).direction, solidcraft_engine::doc::Direction::Negative); assert_eq!(h.app.session.doc.eval("d1", solidcraft_engine::doc::expr::Kind::Length).unwrap(), 10.0); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds().min.z, -10.0); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().min.z, -10.0); } #[test] @@ -210,7 +210,7 @@ fn failed_edit_and_cancel_keep_full_history_and_existing_redo() { assert_eq!(h.app.session.redo.len(), redo); assert_eq!(h.app.session.selection, selection); h.app.run("edit.redo", json!({})).unwrap(); - assert!(h.app.session.world_state().body("RedoBody").is_some()); + assert!(h.app.session.world_state().unwrap().body("RedoBody").is_some()); } #[test] @@ -222,7 +222,7 @@ fn tapered_from_and_signed_to_have_correct_start_volume_and_preview_parity() { (json!({"from":[0,0,5],"to":[0,0,-5],"direction":"positive","taper":"atan(0.1)"}), -5.0, 5.0), ] { let mut h = make(params.clone()); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let body = state.body("Main").unwrap(); let bounds = body.mesh().bounds(); assert!((bounds.min.z - lo).abs() < 1e-8 && (bounds.max.z - hi).abs() < 1e-8, "{params}: {bounds:?}"); @@ -236,7 +236,7 @@ fn tapered_from_and_signed_to_have_correct_start_volume_and_preview_parity() { assert_eq!(preview.after.body("Main").unwrap().mesh().bounds(), bounds); h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(extent(&h), original); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), bounds); } } @@ -252,7 +252,7 @@ fn adjacent_profiles_from_slanted_face_use_same_merged_centre_as_geometry() { let angle = 0.1f64.atan(); let point = [2.0 * angle.sin(), 0.0, 10.0 + 2.0 * angle.cos()]; h.app.run("solid.extrude", json!({"sketch":"Adjacent","distance":10,"from":point,"name":"Depth","body_name":"Main","operation":"new"})).unwrap(); - let min_z = h.app.session.world_state().body("Main").unwrap().mesh().bounds().min.z; + let min_z = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().min.z; open(&mut h); let base = crate::canvas::anchor(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().0; assert!((base.z - min_z).abs() < 1e-7, "displayed start{} geometry start{min_z}", base.z); @@ -261,7 +261,7 @@ fn adjacent_profiles_from_slanted_face_use_same_merged_centre_as_geometry() { let unmerged_height = 10.0 + 2.0 / angle.cos() - 3.5 * angle.tan(); assert!((base.z - unmerged_height).abs() > 0.01, "fixture must distinguish the raw-profile centre"); h.step(&json!({"widget":"OK"})).unwrap(); - assert!((h.app.session.world_state().body("Main").unwrap().mesh().bounds().min.z - min_z).abs() < 1e-7); + assert!((h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().min.z - min_z).abs() < 1e-7); } #[test] @@ -273,11 +273,11 @@ fn rotated_second_occurrence_keeps_saved_from_and_to_points_exact() { h.app.run("occurrence.move", json!({"occurrence":second,"axis":[1,0,0],"angle":"17 deg"})).unwrap(); h.app.run("component.activate", json!({"component":owner["component"],"occurrence":second,"path":[second]})).unwrap(); let original = extent(&h); - let before: Vec<_> = h.app.session.world_state().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); + let before: Vec<_> = h.app.session.world_state().unwrap().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); open(&mut h); h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(extent(&h), original); - let after: Vec<_> = h.app.session.world_state().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); + let after: Vec<_> = h.app.session.world_state().unwrap().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); assert_eq!(after, before); } @@ -319,14 +319,14 @@ fn symmetric_total_distance_preview_handle_drag_apply_and_reopen_agree() { let preview_bounds = preview.after.body("Main").unwrap().mesh().bounds(); assert!((preview_bounds.min.z + 60.0).abs() < 1e-7 && (preview_bounds.max.z - 60.0).abs() < 1e-7); h.step(&json!({"widget":"OK"})).unwrap(); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), preview_bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), preview_bounds); let path = h.dir.join("symmetric.solidcraft"); h.app.run("file.save_as", json!({"path":path})).unwrap(); h.app.run("doc.open", json!({"path":path})).unwrap(); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), preview_bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), preview_bounds); open(&mut h); h.step(&json!({"widget":"OK"})).unwrap(); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), preview_bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), preview_bounds); } } @@ -342,7 +342,7 @@ fn switching_one_side_to_symmetric_in_actual_editor_keeps_total_thickness() { let bounds = preview.after.body("Main").unwrap().mesh().bounds(); assert!((bounds.min.z + 5.0).abs() < 1e-7 && (bounds.max.z - 5.0).abs() < 1e-7); h.step(&json!({"widget":"OK"})).unwrap(); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), bounds); assert_eq!(extent(&h).convention, solidcraft_engine::doc::ExtrudeConvention::TotalDistance); } } @@ -361,7 +361,7 @@ fn symmetric_through_all_handle_drag_switches_to_total_distance() { assert!(!all); assert_eq!(h.app.session.doc.eval(distance, solidcraft_engine::doc::expr::Kind::Length).unwrap(), 120.0); h.step(&json!({"widget":"OK"})).unwrap(); - let bounds = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let bounds = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); assert!((bounds.min.z + 60.0).abs() < 1e-7 && (bounds.max.z - 60.0).abs() < 1e-7); } @@ -422,7 +422,7 @@ fn the_extrude_arrow_drags_from_its_stem() { h.step(&json!({"drag":[from, to]})).unwrap(); assert!((dialog_distance(&h) - 15.0).abs() < 1e-9, "{}", dialog_distance(&h)); h.step(&json!({"widget":"OK"})).unwrap(); - let bounds = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let bounds = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); assert!((bounds.max.z - 15.0).abs() < 1e-7, "{bounds:?}"); } @@ -459,7 +459,7 @@ fn a_click_on_the_extrude_arrow_stem_keeps_the_profile() { /// The volume of the body `name`. fn volume(h: &Harness, name: &str) -> f64 { - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); solidcraft_engine::doc::kernel::measure(&state.body(name).unwrap().body).unwrap().volume } diff --git a/crates/ui-egui/src/extrude_preview.rs b/crates/ui-egui/src/extrude_preview.rs index 227daa4bb..b1c6e2286 100644 --- a/crates/ui-egui/src/extrude_preview.rs +++ b/crates/ui-egui/src/extrude_preview.rs @@ -157,7 +157,7 @@ impl StraightPreview { } fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let mut surfaces = Vec::new(); let mut budget = 65_536usize; if inputs.iter().all(|input| matches!(input, Sel::Profile { .. })) { @@ -297,7 +297,7 @@ mod tests { fn face_mesh_feedback_reuses_cap_and_handles_both_distance_signs() { let mut harness = Harness::new(); harness.app.run("solid.box", json!({"length":4,"width":3,"height":5,"body_name":"Stock"})).unwrap(); - let state = harness.app.session.world_state(); + let state = harness.app.session.world_state().unwrap(); let face = state .body("Stock") .unwrap() @@ -353,7 +353,7 @@ mod tests { let mut h = Harness::new(); let made = h.app.run("component.create", json!({"name":"Imported part","grounded":false})).unwrap(); h.app.run("solid.box", json!({"length":4,"width":3,"height":5,"body_name":"Stock"})).unwrap(); - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let face = world.body("Stock").unwrap().body.faces(0.001).unwrap().into_iter().find(|face| face.plane_normal.is_some_and(|n| n.z > 0.99)).unwrap(); h.app.session.selection = vec![Sel::Face { body: "Stock".into(), index: face.index, point: face.centroid }]; @@ -375,7 +375,7 @@ mod tests { fn zero_distance_is_refused_without_a_scratch_preview() { let mut h = Harness::new(); h.app.run("solid.box", json!({"length":4,"width":3,"height":5,"body_name":"Stock"})).unwrap(); - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let face = world.body("Stock").unwrap().body.faces(0.001).unwrap().into_iter().find(|face| face.plane_normal.is_some_and(|n| n.z > 0.99)).unwrap(); h.app.session.selection = vec![Sel::Face { body: "Stock".into(), index: face.index, point: face.centroid }]; diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 496f7e5c8..a1b1bb736 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -405,7 +405,7 @@ fn start(app: &mut SolveApp) { return; } let insert = request.insert(); - let before = if insert { app.session.world_state().bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() }; + let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() }; let update = request.kind == Kind::UpdateLinks; let mut scratch = if insert || update || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() }; if insert { @@ -532,7 +532,7 @@ fn start_staged(app: &mut SolveApp) { } let Some(request) = app.file_load.queued.pop_front() else { return }; let insert = request.insert(); - let before = if insert { app.session.world_state().bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() }; + let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() }; let mut session = if insert { app.session.scratch() } else { Session::default() }; if insert { session.selection = app.session.selection.clone(); @@ -588,7 +588,7 @@ fn step_staged(running: &mut Running) { let in_budget = || began.elapsed().as_secs_f64() * 1000.0 < STAGED_FRAME_MS; if staged.ran.is_some() { let Some(session) = staged.session.as_ref() else { return }; - let world = session.world_state(); + let world = crate::open_meshing::session_world(session); while staged.warmed < world.bodies.len() && in_budget() { if let Some(body) = world.bodies.get(staged.warmed) { staged.triangles += body.mesh().triangles.len(); @@ -826,7 +826,7 @@ fn compute( let geometry_ms = began.elapsed().as_secs_f64() * 1000.0; let view_began = std::time::Instant::now(); phase.store(1, Ordering::Relaxed); - let world = session.world_state(); + let world = crate::open_meshing::session_world(&session); let placement_ms = view_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. @@ -1505,7 +1505,7 @@ mod tests { part.execute("file.export", &serde_json::json!({"path": path})).unwrap(); let ctx = crate::fonts::test_context(); let mut app = SolveApp::new(Session::default(), Default::default()); - let bodies = |app: &SolveApp| app.session.world_state().bodies.len(); + let bodies = |app: &SolveApp| app.session.world_state().unwrap().bodies.len(); assert!(staged_kind(&Request::new(&path, Kind::Insert)) && staged_kind(&Request::new(&path, Kind::Open))); assert!(!staged_kind(&Request::new("part.igs", Kind::Insert)) && !staged_kind(&Request::new("part.solidcraft", Kind::Open))); app.file_load.queued.push_back(Request::new(&path, Kind::Insert)); diff --git a/crates/ui-egui/src/file_load_ui_tests.rs b/crates/ui-egui/src/file_load_ui_tests.rs index e38543c2c..b456e0632 100644 --- a/crates/ui-egui/src/file_load_ui_tests.rs +++ b/crates/ui-egui/src/file_load_ui_tests.rs @@ -77,10 +77,10 @@ fn scratch(name: &str) -> std::path::PathBuf { /// What two sessions must agree on after opening the same file. fn fingerprint(s: &Session) -> serde_json::Value { - let world = s.world_state(); + let world = s.world_state().unwrap(); let bodies: Vec<_> = world.bodies.iter().map(|b| (b.name.clone(), b.mesh().triangles.len())).collect(); let errors = s.model.results.iter().filter(|r| r.error.is_some()).count(); - let b = solidcraft_engine::view::bounds(s); + let b = solidcraft_engine::view::bounds(s).unwrap(); json!({ "name": s.doc.name, "path": s.path, @@ -404,7 +404,7 @@ fn a_control_import_passes_up_and_names_on() { assert_eq!(reply["ok"], true, "{params}: {reply}"); let mut sync = Session::default(); assert_eq!(reply["result"], sync.execute("file.insert_step", ¶ms).unwrap(), "the window's reply is the session's"); - let b = solidcraft_engine::view::bounds(&w.app.session); + let b = solidcraft_engine::view::bounds(&w.app.session).unwrap(); (reply, [b.max.x - b.min.x, b.max.y - b.min.y, b.max.z - b.min.z], w.app.stand_up.is_some()) }; @@ -476,12 +476,12 @@ fn an_opened_design_shows_its_bodies_as_they_are_meshed() { 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}"); + assert!(done <= total && total == w.app.session.world_state().unwrap().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(); + let world = w.app.session.world_state().unwrap(); // 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(); @@ -504,7 +504,7 @@ fn an_opened_design_shows_its_bodies_as_they_are_meshed() { // 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())); + assert!(std::sync::Arc::ptr_eq(&crate::open_meshing::shown_world(&w.app), &w.app.session.world_state().unwrap())); let _ = std::fs::remove_dir_all(&dir); } @@ -587,7 +587,7 @@ fn open_timed(path: &str) -> (Win, (f64, &'static str)) { 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()); + eprintln!("{path}: slowest frame {:.1} ms while {}, {} bodies", slowest.0, slowest.1, w.app.session.world_state().unwrap().bodies.len()); (w, slowest) } @@ -608,7 +608,7 @@ fn opening_a_large_design_never_stalls_the_window() { 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); + assert!(w.app.session.world_state().unwrap().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(); diff --git a/crates/ui-egui/src/fillet_spline_handle_tests.rs b/crates/ui-egui/src/fillet_spline_handle_tests.rs index ce44168e9..8b0f11879 100644 --- a/crates/ui-egui/src/fillet_spline_handle_tests.rs +++ b/crates/ui-egui/src/fillet_spline_handle_tests.rs @@ -28,7 +28,7 @@ fn open(h: &mut Harness) { } fn volume(h: &Harness) -> f64 { - kernel::measure(&h.app.session.world_state().body("Plate").unwrap().body).unwrap().volume + kernel::measure(&h.app.session.world_state().unwrap().body("Plate").unwrap().body).unwrap().volume } #[test] @@ -168,7 +168,7 @@ fn double_clicks_add_and_remove_control_radii() { panic!("a spline fillet") }; assert_eq!(radii.len() + 1, law.radii.len()); - assert!(h.app.session.world_state().body("Box").is_some()); + assert!(h.app.session.world_state().unwrap().body("Box").is_some()); } #[test] diff --git a/crates/ui-egui/src/help.rs b/crates/ui-egui/src/help.rs index 90132c8a3..0879a0d4e 100644 --- a/crates/ui-egui/src/help.rs +++ b/crates/ui-egui/src/help.rs @@ -36,7 +36,7 @@ pub fn diagnostics(app: &SolveApp) -> String { if app.custom_titlebar { "custom title bar" } else { "system title bar" }, app.session.doc.name, app.session.doc.features.len(), - app.session.world_state().bodies.len(), + crate::open_meshing::session_world(&app.session).bodies.len(), ) } diff --git a/crates/ui-egui/src/hole_placement_ui_tests.rs b/crates/ui-egui/src/hole_placement_ui_tests.rs index 8c480b405..500fa2947 100644 --- a/crates/ui-egui/src/hole_placement_ui_tests.rs +++ b/crates/ui-egui/src/hole_placement_ui_tests.rs @@ -327,7 +327,7 @@ fn block_and_circle_on(sketch: Value, at: [f64; 2]) -> (Harness, Vec3) { h.app.run("sketch.finish", json!({})).unwrap(); h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap(); h.settle(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketches.first().unwrap(); let centre = ss .sketch @@ -451,11 +451,12 @@ fn a_single_hole_at_a_circle_centre_follows_the_circle() { h.step(&json!({"key": "Enter"})).unwrap(); assert!(h.app.dialog.is_none(), "OK closed the dialog: {:?}", h.app.dialog.as_ref().map(|d| &d.error)); let (id, _, _) = hole(&h); - let sketch = h.app.session.world_state().sketches.first().unwrap().feature; + let sketch = h.app.session.world_state().unwrap().sketches.first().unwrap().feature; let circle = h .app .session .world_state() + .unwrap() .sketches .first() .unwrap() @@ -471,7 +472,7 @@ fn a_single_hole_at_a_circle_centre_follows_the_circle() { h.app.run("sketch.move_point", json!({"point": format!("{circle}.center"), "to": [20, 9]})).unwrap(); h.app.run("sketch.finish", json!({})).unwrap(); h.settle(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketches.first().unwrap(); let moved = ss .sketch @@ -602,7 +603,7 @@ fn block_with_lettering(circle: Option) -> (Harness, Vec3, Option) { h.app.run("sketch.create", json!({"plane": {"face": [20, 15, 20]}})).unwrap(); h.app.run("sketch.text", json!({"text": "L", "at": [5, 5], "height": 10})).unwrap(); let outline = |h: &Harness| { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketches.first().unwrap(); let sk = &ss.sketch; let text = |p: &&SPoint| p.link.as_deref().and_then(|l| sk.link(l)).is_some_and(|l| l.kind == LinkKind::Text); @@ -616,7 +617,7 @@ fn block_with_lettering(circle: Option) -> (Harness, Vec3, Option) { h.app.run("sketch.finish", json!({})).unwrap(); h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap(); h.settle(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let plane = st.sketches.first().unwrap().plane; assert_eq!(outline(&h).len(), 6, "the L's outline has six corners"); (h, plane.to_world(corner), centre.map(|c| plane.to_world(c))) @@ -765,7 +766,7 @@ fn cylinder_with_cluster(sketch: Value, at: [f64; 2], view: &str) -> Cluster { h.app.run("sketch.finish", json!({})).unwrap(); h.step(&json!({"call": "ui.view", "params": {"view": view}})).unwrap(); h.settle(); - let plane = h.app.session.world_state().sketches.first().unwrap().plane; + let plane = h.app.session.world_state().unwrap().sketches.first().unwrap().plane; let centre = plane.to_world(Vec2::new(at[0], at[1])); let mut points = Aabb3::EMPTY; local.iter().for_each(|p| points.add(plane.to_world(*p))); @@ -773,7 +774,7 @@ fn cylinder_with_cluster(sketch: Value, at: [f64; 2], view: &str) -> Cluster { h.step(&json!({"start": "solid.hole"})).unwrap(); let ray = hits_at(&h, click); let Some(Hit::Face { body, index, .. }) = ray.iter().find(|x| matches!(x, Hit::Face { .. })) else { panic!("no face under {centre:?}: {ray:?}") }; - let m = h.app.session.world_state().body(body).unwrap().mesh(); + let m = h.app.session.world_state().unwrap().body(body).unwrap().mesh(); let face: Vec<[Vec3; 3]> = m.triangles.iter().zip(&m.tri_face).filter(|(_, f)| **f as usize == *index).filter_map(|(t, _)| m.tri(t)).collect(); let near_points = |t: &[Vec3; 3]| { let mut b = Aabb3::EMPTY; @@ -852,7 +853,7 @@ fn a_face_place_snaps_to_the_points_of_shown_geometry_only() { // text outline's points (`view::sketch_point_visible`), and no linked point while Show // Projected is off. An id names its first link; a point whose link is gone counts as shown. let (h, _, _) = block_with_lettering(None); - let mut sk = h.app.session.world_state().sketches.first().unwrap().sketch.clone(); + let mut sk = h.app.session.world_state().unwrap().sketches.first().unwrap().sketch.clone(); let text = sk.links.iter().find(|l| l.kind == LinkKind::Text).unwrap().clone(); let edges = sk.links.iter().find(|l| l.kind != LinkKind::Text).unwrap().clone(); // Later links reusing the ids, with the other kind: the first link of an id is the one. diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index d5d4c8e12..b04e03345 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -128,14 +128,15 @@ impl HomeState { pub fn thumbnail(s: &Session) -> Option { let mut cam = Camera::default(); cam.set_view(StandardView::Iso); - let b = solidcraft_engine::view::bounds(s); + // No picture of a model that cannot be placed. + let b = solidcraft_engine::view::bounds(s).ok()?; if b.is_empty() { return None; } cam.fit(&b); // Fill the card: the fit leaves room for a whole window's margins. cam.distance *= 0.7; - let scene = solidcraft_engine::view::scene(s, &cam); + let scene = solidcraft_engine::view::scene(s, &cam).ok()?; // Drawn on the GPU by the renderer the app installs; none (a browser): no picture. let picture = solidcraft_engine::capture::rgba(&scene, &cam, THUMB[0] as u32, THUMB[1] as u32).ok()?; Some(egui::ColorImage::from_rgba_unmultiplied(THUMB, &picture.rgba)) @@ -320,7 +321,7 @@ fn make(key: &str) -> Made { } if sample.is_some() { // Keep the first viewport frame warm even though the preview needs no new render. - s.world_state().warm_meshes(|| true); + crate::open_meshing::session_world(&s).warm_meshes(|| true); } let img = match sample { Some(i) => sample_picture(i), @@ -1187,7 +1188,7 @@ mod tests { } let mut session = Session::default(); session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); - for body in &session.world_state().bodies { + for body in &session.world_state().unwrap().bodies { body.mesh(); } let bytes = session.design_container(solidcraft_engine::io::DesignCompression::Fast, false, true).unwrap(); @@ -1255,7 +1256,7 @@ mod tests { let key = path.to_string_lossy().into_owned(); let mut s = Session::default(); s.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); - for b in &s.world_state().bodies { + for b in &s.world_state().unwrap().bodies { b.mesh(); } let bytes = s.design_container(solidcraft_engine::io::DesignCompression::Fast, false, true).unwrap(); diff --git a/crates/ui-egui/src/inference.rs b/crates/ui-egui/src/inference.rs index 6dc2d299f..d0a7c1b63 100644 --- a/crates/ui-egui/src/inference.rs +++ b/crates/ui-egui/src/inference.rs @@ -241,7 +241,7 @@ pub fn show(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { return; } let Some(i) = current() else { return }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return }; let to = |p: Vec2| proj.to_screen(ss.plane.to_world(p)); let tk = Tokens::get(); diff --git a/crates/ui-egui/src/infinite_line_display_tests.rs b/crates/ui-egui/src/infinite_line_display_tests.rs index fc0cb52e3..b85f955f6 100644 --- a/crates/ui-egui/src/infinite_line_display_tests.rs +++ b/crates/ui-egui/src/infinite_line_display_tests.rs @@ -23,7 +23,7 @@ fn it_is_drawn_from_edge_to_edge_of_the_view() { let h = short_infinite_line(); let rect = h.app.viewport.rect.unwrap(); let proj = projection(&h.app, rect); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); let i = ss.sketch.curve_index("inf").unwrap(); let parts = super::curve_parts(&ss.sketch, i, &ss.plane, &proj, 1.0); @@ -43,7 +43,7 @@ fn it_is_picked_far_beyond_its_two_points() { let h = short_infinite_line(); let rect = h.app.viewport.rect.unwrap(); let proj = projection(&h.app, rect); - let ss_plane = h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().plane; + let ss_plane = h.app.session.world_state().unwrap().sketch(h.app.session.active_sketch.unwrap()).unwrap().plane; let far = proj.to_screen(ss_plane.to_world(solidcraft_engine::geom::Vec2::new(150.0, 0.0))).unwrap(); assert!(rect.contains(far)); let hits = pick(&h.app, &proj, far); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 53eaa0dac..5581b01c7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1062,7 +1062,7 @@ impl SolveApp { self.cancel_view_animation(); self.cam = to; } else if v.get("fit").and_then(Value::as_bool).unwrap_or(false) { - let bounds = solidcraft_engine::view::bounds(&self.session); + let bounds = solidcraft_engine::view::bounds(&self.session).map_err(|e| e.to_string())?; self.animate_to(self.fitted(to)); self.pending_fit = Some((to, bounds, true)); } else { @@ -1724,7 +1724,7 @@ impl SolveApp { /// Insert CAD bodies, meshes or sketch drawing geometry into the current design. pub fn insert_path(&mut self, path: &str) { let cmd = file_load::insert_command(path); - let before: Vec = self.session.world_state().bodies.iter().map(|b| b.name.clone()).collect(); + let before: Vec = crate::open_meshing::session_world(&self.session).bodies.iter().map(|b| b.name.clone()).collect(); if let Ok(r) = self.run(cmd, json!({ "path": path })) { self.fit_view(); stand_up::offer(self, path, &before, Some(&r)); diff --git a/crates/ui-egui/src/menu_tests.rs b/crates/ui-egui/src/menu_tests.rs index 3d84c601d..5877c6dbd 100644 --- a/crates/ui-egui/src/menu_tests.rs +++ b/crates/ui-egui/src/menu_tests.rs @@ -143,7 +143,7 @@ fn a_sketch_curve_in_the_viewport_offers_the_sketch_menu() { app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})).unwrap(); app.run("sketch.finish", json!({})).unwrap(); let (sketch, curve) = { - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let ss = st.sketches.first().expect("the design has one sketch"); (ss.feature, ss.sketch.curves.first().expect("the rectangle drew curves").id.clone()) }; @@ -171,7 +171,7 @@ fn a_sketch_curve_in_the_viewport_offers_the_sketch_menu() { fn a_selected_face_keeps_the_body_menu_beside_a_sketch_curve() { let mut app = sample_app(); let b = body(&app); - let sketch = app.session.world_state().sketches.first().expect("the sample design has sketches").feature; + let sketch = app.session.world_state().unwrap().sketches.first().expect("the sample design has sketches").feature; let items = json!([ {"type": "face", "body": b, "index": 0, "point": [0, 0, 0]}, {"type": "external_sketch_curve", "sketch": sketch, "id": "l1"}, @@ -639,7 +639,7 @@ fn browser_feature_menu_confirms_dependent_changes_before_deleting() { fn menu_delete_items_use_the_same_path() { let mut app = sample_app(); let b = body(&app); - let original_volume = solidcraft_engine::kernel::measure(&app.session.world_state().body(&b).unwrap().body).unwrap().volume; + let original_volume = solidcraft_engine::kernel::measure(&app.session.world_state().unwrap().body(&b).unwrap().body).unwrap().volume; let created = app.run("component.from_bodies", json!({"bodies": [b]})).unwrap(); let c = app.session.doc.components[0].id; let transfer = created["components"][0]["feature"].as_u64().unwrap(); @@ -654,7 +654,7 @@ fn menu_delete_items_use_the_same_path() { assert!(crate::delete::confirm(&mut app, true)); assert!(app.session.doc.components.is_empty()); assert!(app.session.doc.feature(transfer).is_none()); - let restored = app.session.world_state(); + let restored = app.session.world_state().unwrap(); assert_eq!(restored.bodies.len(), 1, "the original joined plate stays intact"); let plate = restored.body(&b).unwrap(); assert_eq!(plate.component, 0); @@ -662,7 +662,7 @@ fn menu_delete_items_use_the_same_path() { assert!(plate.mesh().contains(solidcraft_engine::geom::Vec3::new(40.0, 35.0, 12.0))); let mut reopened = solidcraft_engine::Session::new(solidcraft_engine::doc::Document::from_json(&app.session.doc.to_json()).unwrap()); reopened.refresh(); - let reopened_state = reopened.world_state(); + let reopened_state = reopened.world_state().unwrap(); assert_eq!(reopened_state.bodies.len(), 1); assert_eq!(reopened_state.body(&b).unwrap().component, 0); assert!((solidcraft_engine::kernel::measure(&reopened_state.body(&b).unwrap().body).unwrap().volume - original_volume).abs() < 1e-6); @@ -1026,7 +1026,7 @@ fn construction_plane_row_opens_its_menu() { #[test] fn right_click_on_a_plane_offers_a_sketch_on_it() { use solidcraft_engine::geom::Vec3; - let normal = |h: &crate::scenario::Harness| h.app.session.world_state().sketches.first().map(|s| s.plane.normal()).unwrap_or_default(); + let normal = |h: &crate::scenario::Harness| h.app.session.world_state().unwrap().sketches.first().map(|s| s.plane.normal()).unwrap_or_default(); for (plane, axis) in [("XY", Vec3::Z), ("XZ", Vec3::Y), ("YZ", Vec3::X)] { let mut h = crate::scenario::Harness::new(); h.app.home.open = false; @@ -1073,7 +1073,7 @@ fn right_click_on_a_plane_offers_a_sketch_on_it() { let id = h.app.session.doc.find_feature("Cut").map(|f| f.id).unwrap(); act(&mut h.app, &Target::Plane { id }, "Create Sketch"); h.frames(3); - let sketch = h.app.session.active_sketch.and_then(|s| h.app.session.world_state().sketch(s).map(|s| s.plane.origin.z)); + let sketch = h.app.session.active_sketch.and_then(|s| h.app.session.world_state().unwrap().sketch(s).map(|s| s.plane.origin.z)); assert_eq!(sketch, Some(25.0), "the sketch is on the construction plane"); } @@ -1205,7 +1205,7 @@ fn contribution_picked_faces_open_their_own_feature_after_later_modifiers() { app.run("solid.hole", json!({"position":[20,15,20],"diameter":8})).unwrap(); app.run("solid.fillet", json!({"edges":[[0,0,10]],"radius":2})).unwrap(); app.run("solid.hole", json!({"position":[32,20,20],"diameter":4})).unwrap(); - let state = app.session.world_state(); + let state = app.session.world_state().unwrap(); let b = state.body("Plate").unwrap(); let names = solidcraft_engine::doc::naming::face_names(b); let index = names.iter().position(|n| n.starts_with(&format!("F{expected}:"))).unwrap(); diff --git a/crates/ui-egui/src/occurrence_ui_tests.rs b/crates/ui-egui/src/occurrence_ui_tests.rs index 7f77c3b2a..87ad08ac9 100644 --- a/crates/ui-egui/src/occurrence_ui_tests.rs +++ b/crates/ui-egui/src/occurrence_ui_tests.rs @@ -22,7 +22,7 @@ fn replaced_body_name_uses_evaluated_owner_in_browser_and_component_actions() { assert_eq!(cache.root.folders[0].as_ref().unwrap().entries().map(|entry| entry.key.as_str()).collect::>(), ["Block"]); let occurrence = h.app.session.doc.occurrence_of(owner).unwrap().id; assert!(cache.occurrences.get([occurrence].as_slice()).unwrap().folders[0].as_ref().unwrap().entries().next().is_none()); - let bounds = h.app.session.world_state().body("Block").unwrap().mesh().bounds(); + let bounds = h.app.session.world_state().unwrap().body("Block").unwrap().mesh().bounds(); assert!((bounds.min.x - 30.0).abs() < 1e-9); assert!((bounds.max.x - 35.0).abs() < 1e-9); } @@ -192,7 +192,7 @@ fn occurrence_delete_targets_second_copy_even_if_first_was_selected() { crate::delete::confirm(&mut h.app, true); assert!(h.app.session.doc.occurrences.iter().any(|o| o.id == first)); assert!(!h.app.session.doc.occurrences.iter().any(|o| o.id == second)); - assert_eq!(h.app.session.world_state().bodies.len(), 1); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); } #[test] @@ -210,7 +210,7 @@ fn occurrence_new_component_keeps_inactive_second_parent_authoring_context() { h.app.run("solid.box", json!({"corner":[51,1,1],"length":2,"width":2,"height":2})).unwrap(); let feature = h.app.session.model.state().bodies.last().unwrap().feature; let mut centers: Vec = - h.app.session.world_state().bodies.iter().filter(|b| b.feature == feature).map(|b| b.mesh().bounds().center().x).collect(); + h.app.session.world_state().unwrap().bodies.iter().filter(|b| b.feature == feature).map(|b| b.mesh().bounds().center().x).collect(); centers.sort_by(f64::total_cmp); assert_eq!(centers.len(), 2); assert!((centers[0] - 2.0).abs() < 1e-8 && (centers[1] - 52.0).abs() < 1e-8, "{centers:?}"); diff --git a/crates/ui-egui/src/open_meshing.rs b/crates/ui-egui/src/open_meshing.rs index 420fae03a..60f93693b 100644 --- a/crates/ui-egui/src/open_meshing.rs +++ b/crates/ui-egui/src/open_meshing.rs @@ -126,7 +126,7 @@ impl Drop for Meshing { 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, app.viewport.gpu.is_some()); + let mut meshing = Meshing::start(crate::open_meshing::session_world(&app.session), plans, app.viewport.gpu.is_some()); meshing.remember = remember; app.open_meshing = Some(meshing); app.fit_view(); @@ -176,7 +176,7 @@ pub(crate) fn framing(app: &SolveApp) -> bool { /// 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(); + let world = crate::open_meshing::session_world(&app.session); if !Arc::ptr_eq(&world, &m.world) { if m.complete { // The design changed after its open: the viewport draws it as ever. @@ -214,13 +214,26 @@ pub(crate) fn tick(app: &mut SolveApp, ctx: &egui::Context) { ctx.request_repaint(); } +/// The session's placed model, as every panel, pick and hover reads it. A model that cannot be +/// placed shows no placed bodies, and the viewport says why ([`placement_error`]); the session +/// keeps the failure, so it is not placed again on every read. +pub(crate) fn session_world(s: &solidcraft_engine::Session) -> Arc { + s.world_state().unwrap_or_default() +} + +/// Why the session's model cannot be placed, if it cannot. +pub(crate) fn placement_error(s: &solidcraft_engine::Session) -> Option { + s.world_state().err().map(|e| e.to_string()) +} + /// 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. +/// the design changes; otherwise the session's ([`session_world`]). 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(); + let world = session_world(&app.session); + let Some(m) = app.open_meshing.as_ref() else { return world }; + if !Arc::ptr_eq(&world, &m.world) { + return world; } m.shown.as_ref().map(|(_, st)| st.clone()).unwrap_or_else(|| Arc::new(ModelState::default())) } diff --git a/crates/ui-egui/src/pick_index_tests.rs b/crates/ui-egui/src/pick_index_tests.rs index f37a63ac3..184020e87 100644 --- a/crates/ui-egui/src/pick_index_tests.rs +++ b/crates/ui-egui/src/pick_index_tests.rs @@ -120,7 +120,7 @@ fn pick_timing_on_curved_models() { for (name, mut app, pitch) in scenes { app.set_origin_shown(false); (app.cam.yaw, app.cam.pitch) = (0.6, pitch); - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); app.cam.fit(&st.bodies.iter().fold(solidcraft_engine::geom::Aabb3::EMPTY, |a, b| a.union(&b.mesh_bounds()))); let (tris, segs) = st .bodies diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 5e12de463..430f20aef 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -4417,7 +4417,7 @@ mod tests { app.open_path(&path); let offered = app.stand_up.clone().unwrap_or_default(); assert_eq!(offered.len(), 1, "the file's body is offered"); - let size = |app: &SolveApp| solidcraft_engine::view::bounds(&app.session); + let size = |app: &SolveApp| solidcraft_engine::view::bounds(&app.session).unwrap(); assert!((size(&app).max.y - size(&app).min.y - 40.0).abs() < 1e-6); control(&mut app, &json!({"stand_up": true})).unwrap(); let b = size(&app); diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 5d9f87278..f691b6a2c 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -20,7 +20,7 @@ fn confirming_coplanar_body_faces_uses_one_atomic_extrusion() { h.app.run("sketch.finish", json!({})).unwrap(); h.app.run("solid.extrude", json!({"distance":6,"operation":"join"})).unwrap(); h.app.run("component.activate", json!({"component":parent})).unwrap(); - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let body = world.body("Plate").unwrap(); h.app.session.selection = body .body @@ -231,7 +231,7 @@ fn feature_mirror_picks_clear_preview_and_replay_the_source_cut() { wait_feature_preview(&mut h); h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); h.step(&json!({"until":{"dialog":null,"features":4}})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); assert_eq!(state.bodies.len(), 1, "a mirrored hole cuts the plate instead of copying it"); assert!(!state.bodies[0].body.contains(Vec3::new(70.0, 25.0, 2.5))); let mirror = h.app.session.doc.features.last().unwrap().id; @@ -315,7 +315,18 @@ fn cylinder_emboss_empty_target_face_applies_automatic_wrap_and_deboss() { for deboss in [false, true] { let mut h = crate::scenario::Harness::new(); h.app.run("solid.cylinder", json!({"radius":10,"height":20,"body_name":"Sleeve"})).unwrap(); - let initial = h.app.session.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume; + let initial = h + .app + .session + .model + .state() + .body("Sleeve") + .unwrap() + .body + .mesh(&solidcraft_engine::kernel::MeshTolerance::chord(1e-4)) + .unwrap() + .measure() + .volume; let sketch = h.app.run("sketch.create", json!({"plane":{"origin":[0,10,0],"x_dir":[-1,0,0],"y_dir":[0,0,1]},"name":"Badge"})).unwrap()["sketch"] .as_u64() @@ -336,7 +347,9 @@ fn cylinder_emboss_empty_target_face_applies_automatic_wrap_and_deboss() { assert!(commands[0].1.get("face").is_none()); let preview = h.app.session.preview_world(&commands).unwrap(); let expected = if deboss { -19.0 } else { 21.0 }; - let preview_delta = preview.after.body("Sleeve").unwrap().body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume - initial; + let preview_delta = + preview.after.body("Sleeve").unwrap().body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume + - initial; assert!( (preview_delta - expected).abs() < 0.05, "deboss={deboss}, preview delta={preview_delta}, expected={expected}, commands={commands:?}" @@ -350,7 +363,19 @@ fn cylinder_emboss_empty_target_face_applies_automatic_wrap_and_deboss() { assert_eq!(*actual, deboss); assert_eq!(face.body, "Sleeve"); assert!( - (h.app.session.model.state().body("Sleeve").unwrap().body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(1e-4)).unwrap().measure().volume - initial - expected) + (h.app + .session + .model + .state() + .body("Sleeve") + .unwrap() + .body + .mesh(&solidcraft_engine::kernel::MeshTolerance::chord(1e-4)) + .unwrap() + .measure() + .volume + - initial + - expected) .abs() < 0.05 ); @@ -658,7 +683,7 @@ fn profile_use_not_curve_use_stops_the_pre_pick() { {"command": "timeline.roll_to", "params": {"position": 1}}, ])); let base = app.session.doc.features.first().unwrap().id; - assert_eq!(app.session.world_state().sketch(base).map(|s| s.profiles.len()), Some(1)); + assert_eq!(app.session.world_state().unwrap().sketch(base).map(|s| s.profiles.len()), Some(1)); assert!(start(&mut app, vec![], "solid.extrude").inputs[0].items.is_empty(), "the rolled-back extrude's profile is taken"); // A pipe follows the circle; the disc inside it is used by nothing. let mut app = app_with(json!([ @@ -1155,7 +1180,7 @@ fn variable_fillet_mid_radii_round_trip() { /// Use an actual mesh point, as a viewport pick does; analytic cylinder points need not lie /// on the display mesh's facets. fn thread_face(app: &SolveApp, body: &str) -> Sel { - let state = app.session.world_state(); + let state = app.session.world_state().unwrap(); let body_state = state.body(body).unwrap(); let index = solidcraft_engine::doc::naming::face_spots(body_state) .into_iter() @@ -1343,11 +1368,11 @@ fn modeled_thread_survives_timeline_double_click_and_ok() { h.app.home.open = false; h.app.apply_off_thread = Some(std::time::Duration::ZERO); h.app.run("solid.cylinder", json!({"radius":4,"height":4})).unwrap(); - let smooth_volume = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + let smooth_volume = h.app.session.world_state().unwrap().body("Body1").unwrap().mesh().measure().volume; let Sel::Face { point, .. } = thread_face(&h.app, "Body1") else { panic!("face") }; let point = if analytic_pick { Vec3::new(4.0, 0.0, 2.0) } else { point }; let id = h.app.run("solid.thread", json!({"face":point,"designation":"M8x1","modeled":true})).unwrap()["feature"].as_u64().unwrap(); - let threaded_volume = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + let threaded_volume = h.app.session.world_state().unwrap().body("Body1").unwrap().mesh().measure().volume; assert!(smooth_volume - threaded_volume > 1.0); h.frames(4); h.step(&json!({"click":{"handle":"timeline:Thread1"},"double":true})).unwrap(); @@ -1378,7 +1403,7 @@ fn modeled_thread_survives_timeline_double_click_and_ok() { assert!(matches!(h.app.session.doc.feature(id).unwrap().kind, solidcraft_engine::doc::FeatureKind::Thread { modeled: true, .. })); let result = h.app.session.model.result(id).unwrap(); assert!(!result.skipped && result.error.is_none(), "{result:?}"); - let edited_volume = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + let edited_volume = h.app.session.world_state().unwrap().body("Body1").unwrap().mesh().measure().volume; assert!(smooth_volume - edited_volume > 1.0, "the modeled cut disappeared: {smooth_volume} -> {edited_volume}"); if change_length { assert!(edited_volume - threaded_volume > 1.0, "shortening the thread restores some material"); @@ -1387,7 +1412,7 @@ fn modeled_thread_survives_timeline_double_click_and_ok() { } h.app.run("edit.undo", json!({})).unwrap(); assert_eq!(h.app.session.doc.marker, None); - let restored = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + let restored = h.app.session.world_state().unwrap().body("Body1").unwrap().mesh().measure().volume; assert!((restored - threaded_volume).abs() < 1e-6, "one undo restores the original modeled thread"); } } @@ -1410,7 +1435,7 @@ fn planar_face_reopen_keeps_the_tight_pick_tolerance() { params["height"] = json!(99.99); h.app.run("timeline.redefine", json!({"feature":base,"command":command,"params":params})).unwrap(); h.app.edit_feature(feature); - assert!(h.app.session.world_state().body("Body1").unwrap().display_tol() > 0.01); + assert!(h.app.session.world_state().unwrap().body("Body1").unwrap().display_tol() > 0.01); assert!(crate::dialogs::face_sel(&h.app.session, point - Vec3::Z * 0.01).is_some()); assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty(), "{command}: a stale planar pick must stay empty"); } @@ -1445,9 +1470,9 @@ fn thread_choices_apply_a_fine_pitch_and_partial_modelled_thread() { assert_eq!(params["length"], "4 mm"); assert_eq!(params["modeled"], true); assert_eq!(h.app.session.doc.to_json(), saved, "changing options only previews"); - let before = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + let before = h.app.session.world_state().unwrap().body("Body1").unwrap().mesh().measure().volume; let result = h.app.session.execute(&command, ¶ms).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let after = state.body("Body1").unwrap().mesh().measure().volume; assert!(before - after > 1.0, "the selected fine pitch must cut the shaft"); let id = result["feature"].as_u64().unwrap(); @@ -1501,7 +1526,7 @@ fn thread_choices_preserve_custom_saved_pairs_and_offer_large_fine_pitches() { // before checking the complete saved design. reopened.marker = None; let session = Session::new(reopened); - assert_eq!(session.world_state().threads[0].designation, "M56x2"); + assert_eq!(session.world_state().unwrap().threads[0].designation, "M56x2"); } } } @@ -1996,7 +2021,7 @@ fn trim_dialog_takes_curves_several_keep_points_and_another_surface() { assert_eq!(p["curves"]["curves"], json!(["c1"]), "{p}"); assert_eq!(p["keep"], json!([[1.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]), "{p}"); app.session.execute(&id, &p).unwrap(); - let area = |app: &SolveApp, n: &str| app.session.world_state().body(n).unwrap().mesh().measure().area; + let area = |app: &SolveApp, n: &str| app.session.world_state().unwrap().body(n).unwrap().mesh().measure().area; assert!((area(&app, "Floor") - 130.0).abs() < 1e-6, "{}", area(&app, "Floor")); app.session.execute("edit.undo", &json!({})).unwrap(); // Mutual: the other surface replaces the tool; stitched into an L. @@ -2012,7 +2037,7 @@ fn trim_dialog_takes_curves_several_keep_points_and_another_surface() { assert_eq!((&p["with"], &p["keep_with"], &p["stitch"]), (&json!("Wall"), &json!([0.0, 5.0, 5.0]), &json!(true)), "{p}"); assert!(p.get("extend").is_none() && p.get("plane").is_none(), "{p}"); app.session.execute(&id, &p).unwrap(); - assert!((area(&app, "Floor") - 200.0).abs() < 1e-6 && app.session.world_state().body("Wall").is_none()); + assert!((area(&app, "Floor") - 200.0).abs() < 1e-6 && app.session.world_state().unwrap().body("Wall").is_none()); let fid = app.session.doc.features.last().unwrap().id; let back = crate::dialogs::for_feature(&app, fid, None).unwrap(); assert!(matches!(back.kind, Kind::Surface(crate::dialogs_surface::Surf::Trim { stitch: true, extend: false, direction: None }))); @@ -2377,7 +2402,7 @@ fn delete_face_asks_for_faces_and_takes_the_preselected_one() { let mut h = crate::scenario::Harness::new(); h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"B"})).unwrap(); h.app.run("solid.fillet", json!({"edges":[[40,15,20]],"radius":5})).unwrap(); - let volume = |h: &crate::scenario::Harness| h.app.session.world_state().body("B").unwrap().mesh().measure().volume; + let volume = |h: &crate::scenario::Harness| h.app.session.world_state().unwrap().body("B").unwrap().mesh().measure().volume; let filleted = volume(&h); h.app.session.selection.clear(); @@ -2527,7 +2552,7 @@ fn hovering_a_large_body_does_not_wait_for_its_pick_index() { let path = h.dir.join("ball.stl"); std::fs::write(&path, stl).unwrap(); h.app.run("file.insert_mesh", json!({"path": path.to_string_lossy()})).unwrap(); - let mesh = h.app.session.world_state().bodies[0].mesh(); + let mesh = h.app.session.world_state().unwrap().bodies[0].mesh(); assert!(mesh.triangles.len() > 250_000, "{}", mesh.triangles.len()); let t = std::time::Instant::now(); let _ = solidcraft_engine::geom::MeshIndex::new(&mesh); diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index e64fb145e..a2448a2bb 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -502,7 +502,7 @@ pub(crate) fn extrusion_target_error(s: &Session, cmds: &[(String, Value)], befo before.bodies.iter().any(|body| s.doc.model_body_component(body) == s.active_component) || (matches!(op, "cut" | "intersect") && s.cut_takes_every_body(before)) }, - |name| s.world_state().body(name).is_some(), + |name| crate::open_meshing::session_world(s).body(name).is_some(), ); } if !found && matches!(op, "cut" | "intersect") { diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 27c796ef8..04bf2ee60 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -1596,7 +1596,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let mut visibility = std::collections::hash_map::DefaultHasher::new(); app.session.visibility.hidden_bodies.hash(&mut visibility); app.session.visibility.hidden_occurrences.hash(&mut visibility); - let signature = (app.session.revision, Arc::as_ptr(&app.session.world_state()) as usize, visibility.finish()); + let signature = (app.session.revision, Arc::as_ptr(&crate::open_meshing::session_world(&app.session)) as usize, visibility.finish()); app.render_workspace .prepare_preview(signature, || solidcraft_engine::product_scene::extract(&app.session).map_err(|error| error.to_string()))?; let scene = app.render_workspace.scene.as_ref().ok_or("no product scene")?; diff --git a/crates/ui-egui/src/revolve_edit_tests.rs b/crates/ui-egui/src/revolve_edit_tests.rs index 4f34753a6..5c585b78c 100644 --- a/crates/ui-egui/src/revolve_edit_tests.rs +++ b/crates/ui-egui/src/revolve_edit_tests.rs @@ -36,7 +36,7 @@ fn unchanged_all_profiles_retains_future_geometry_but_reselection_is_explicit() h.app.run("sketch.edit", json!({"sketch":"Profile"})).unwrap(); h.app.run("sketch.rectangle.two_point", json!({"p0":[20,0],"p1":[25,5]})).unwrap(); h.app.run("sketch.finish", json!({})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let volume: f64 = state.bodies.iter().map(|b| solidcraft_engine::doc::kernel::measure(&b.body).unwrap().volume).sum(); let expected = if reselect { 490.873852 } else { 1374.446786 }; assert!((volume - expected).abs() < 0.3, "{volume} != {expected}"); @@ -50,7 +50,7 @@ fn to_object_noop_preserves_cut_targets_and_untargeted_body() { h.app.run("solid.box", json!({"length":20,"width":5,"height":20,"corner":[0,0,0],"body_name":name})).unwrap(); } let mut h = make_params(h, json!("Y"), json!({"to":[0,2,12],"angle":"45 deg","operation":"cut","targets":["A"]})); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); // A quarter annulus separates the stock into inner and outer solids. Both are // results of cutting A; checking only the first named solid loses material. let cut_volume = |state: &solidcraft_engine::doc::ModelState| -> f64 { @@ -69,7 +69,7 @@ fn to_object_noop_preserves_cut_targets_and_untargeted_body() { open(&mut h); h.step(&json!({"widget":"OK"})).unwrap(); assert!(h.app.dialog.is_none()); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); assert!((solidcraft_engine::doc::kernel::measure(&state.body("B").unwrap().body).unwrap().volume - 2000.0).abs() < 1e-7); assert!((cut_volume(&state) - before_a).abs() < 1e-7); assert_eq!(state.bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect::>(), before_bounds); @@ -88,7 +88,7 @@ fn to_object_noop_retains_dormant_secondary_angle_and_downstream_dimension() { h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(), original); assert_eq!(h.app.session.doc.find_feature("Turn").unwrap().param_names, names); - assert!((h.app.session.world_state().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::PI / 6.0).abs() < 1e-8); + assert!((h.app.session.world_state().unwrap().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::PI / 6.0).abs() < 1e-8); } #[test] @@ -99,11 +99,11 @@ fn rotated_owner_to_point_remains_exact_on_noop_edit() { h.app.run("occurrence.move", json!({"occurrence":owner["occurrence"],"translate":[100,0,20],"axis":[0,0,1],"angle":"17 deg"})).unwrap(); h.app.run("component.create", json!({"name":"Other","parent":0})).unwrap(); let original = serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(); - let bounds = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let bounds = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); open(&mut h); h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(), original); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), bounds); } #[test] @@ -117,7 +117,7 @@ fn second_active_occurrence_noop_preserves_definition_axis_target_and_instances( let original = serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(); let frame = h.app.session.active_component_frame(); let expected_origin = solidcraft_engine::doc::apply_point(&frame, solidcraft_engine::geom::Vec3::ZERO); - let before: Vec<_> = h.app.session.world_state().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); + let before: Vec<_> = h.app.session.world_state().unwrap().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); open(&mut h); let (origin, _) = crate::canvas::revolve_axis(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); assert!((origin - expected_origin).len() < 1e-8); @@ -133,7 +133,7 @@ fn second_active_occurrence_noop_preserves_definition_axis_target_and_instances( h.step(&json!({"widget":"OK"})).unwrap(); assert!(h.app.dialog.is_none(), "OK must apply even underneath the Sweep badge"); assert_eq!(serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(), original); - let after: Vec<_> = h.app.session.world_state().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); + let after: Vec<_> = h.app.session.world_state().unwrap().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); assert_eq!(after, before); assert_eq!(h.app.session.active_occurrence_path.as_ref(), Some(&vec![second.as_u64().unwrap()])); } @@ -152,7 +152,7 @@ fn actual_noop_editor_retains_all_revolve_axis_kinds_and_analytic_volume() { let mut h = make(Harness::new(), axis_value.clone()); let original = axis(&h); let names = h.app.session.doc.find_feature("Turn").unwrap().param_names.clone(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let body = state.body("Main").unwrap(); let bounds = body.mesh().bounds(); let radii = if axis_value == json!("l4") { 25.0 } else { 225.0 - 100.0 }; @@ -167,7 +167,7 @@ fn actual_noop_editor_retains_all_revolve_axis_kinds_and_analytic_volume() { assert!(h.app.dialog.is_none(), "{axis_value}: {:?}", h.app.session.log); assert_eq!(axis(&h), original); assert_eq!(h.app.session.doc.find_feature("Turn").unwrap().param_names, names); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), bounds); } } @@ -183,10 +183,10 @@ fn revolve_angle_edit_preserves_axis_downstream_binding_and_one_undo() { h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(axis(&h), original); assert_eq!(h.app.session.undo.len(), undo + 1); - assert!((h.app.session.world_state().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::PI).abs() < 1e-8); + assert!((h.app.session.world_state().unwrap().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::PI).abs() < 1e-8); h.app.run("edit.undo", json!({})).unwrap(); assert_eq!(axis(&h), original); - assert!((h.app.session.world_state().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::FRAC_PI_2).abs() < 1e-8); + assert!((h.app.session.world_state().unwrap().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::FRAC_PI_2).abs() < 1e-8); } #[test] @@ -198,7 +198,7 @@ fn rotated_owner_explicit_axis_is_lossless_with_another_component_active() { h.app.run("component.create", json!({"name":"Other","parent":0})).unwrap(); let active = h.app.session.active_component; let original = axis(&h); - let bounds = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let bounds = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); open(&mut h); let (origin, direction) = crate::canvas::revolve_axis(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); assert!((origin.x - 100.0).abs() < 1e-8 && (origin.z - 20.0).abs() < 1e-8); @@ -207,7 +207,7 @@ fn rotated_owner_explicit_axis_is_lossless_with_another_component_active() { h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(axis(&h), original); assert_eq!(h.app.session.active_component, active); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), bounds); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), bounds); } #[test] diff --git a/crates/ui-egui/src/revolve_manipulator_tests.rs b/crates/ui-egui/src/revolve_manipulator_tests.rs index a9d493af2..4fbc2c858 100644 --- a/crates/ui-egui/src/revolve_manipulator_tests.rs +++ b/crates/ui-egui/src/revolve_manipulator_tests.rs @@ -29,7 +29,7 @@ fn handle_at(h: &mut Harness, name: &str, world: Value) { assert!((actual[0] - expected[0]).hypot(actual[1] - expected[1]) < 1.0, "{actual:?} != {expected:?}"); } fn volume(h: &Harness) -> f64 { - kernel::measure(&h.app.session.world_state().body("Main").unwrap().body).unwrap().volume + kernel::measure(&h.app.session.world_state().unwrap().body("Main").unwrap().body).unwrap().volume } fn angle(h: &Harness) -> String { let FeatureKind::Revolve { angle, .. } = &h.app.session.doc.find_feature("Turn").unwrap().kind else { panic!("revolve") }; @@ -89,7 +89,7 @@ fn symmetric_boundary_drags_edit_included_angle_and_cancel_is_lossless() { assert_eq!(entered, "90 deg", "second {handle} drag"); h.step(&json!({"widget":"OK"})).unwrap(); assert!((volume(&h) - expected_volume(90.0)).abs() < 0.1, "{handle}: {} angle {}", volume(&h), angle(&h)); - let bounds = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let bounds = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); assert!((bounds.max.z - 15.0 / 2.0f64.sqrt()).abs() < 0.03 && (bounds.min.z + 15.0 / 2.0f64.sqrt()).abs() < 0.03); let path = h.dir.join("symmetric.solidcraft"); h.app.run("file.save", json!({"path":path})).unwrap(); @@ -139,7 +139,7 @@ fn two_side_boundary_preserves_other_angle_and_parameter_binding() { assert_eq!(angle, "60 deg"); assert_eq!(angle2.as_deref(), Some("45 deg")); assert_eq!(h.app.session.doc.find_feature("Turn").unwrap().param_names, names); - assert!((h.app.session.world_state().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::FRAC_PI_4).abs() < 1e-8); + assert!((h.app.session.world_state().unwrap().body("Dependent").unwrap().mesh().bounds().max.z - std::f64::consts::FRAC_PI_4).abs() < 1e-8); assert!((volume(&h) - expected_volume(105.0)).abs() < 0.03); } @@ -267,19 +267,19 @@ fn legacy_reversed_axis_symmetric_interval_is_shown_and_preserved_exactly() { let FeatureKind::Revolve { convention, .. } = &h.app.session.doc.find_feature("Turn").unwrap().kind else { panic!("revolve") }; assert_eq!(*convention, solidcraft_engine::doc::RevolveConvention::LegacyAxisStart); let original = serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(); - let before = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let before = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); assert!(before.min.x < -14.9 && before.max.x < 7.6 && before.min.z > -1e-6 && before.max.z > 14.9); open(&mut h); handle_at(&mut h, "revolve", at_angle(180.0)); handle_at(&mut h, "revolve2", at_angle(60.0)); h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(), original); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), before); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), before); open(&mut h); h.step(&json!({"drag":[{"handle":"revolve"},{"world":at_angle(135.0)}]})).unwrap(); h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(angle(&h), "90 deg"); - let after = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let after = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); assert!((after.min.x + 15.0 / 2.0f64.sqrt()).abs() < 0.03 && (after.max.x - 15.0 / 2.0f64.sqrt()).abs() < 0.03); assert!(after.min.z > 7.0 && after.max.z > 14.9); assert!((volume(&h) - expected_volume(90.0)).abs() < 0.1); @@ -337,7 +337,7 @@ fn reversed_axis_to_object_canvas_sweep_and_preview_follow_the_quarter_target() let mut h = fixture(Harness::new(), json!({"axis":{"origin":[0,0,0],"dir":[0,-2,0]},"to":[0,2,12],"angle":"45 deg"})); let original = serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(); let names = h.app.session.doc.find_feature("Turn").unwrap().param_names.clone(); - let before = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + let before = h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(); let p = 12.5 / 2.0f64.sqrt(); open(&mut h); assert!(h.widget("Sweep 90.0°").is_some()); @@ -362,5 +362,5 @@ fn reversed_axis_to_object_canvas_sweep_and_preview_follow_the_quarter_target() assert!(h.widget("Sweep 90.0°").is_some()); h.step(&json!({"widget":"OK"})).unwrap(); assert_eq!(serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(), original); - assert_eq!(h.app.session.world_state().body("Main").unwrap().mesh().bounds(), before); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds(), before); } diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs index ad7598c7d..384b0a259 100644 --- a/crates/ui-egui/src/scale_tests.rs +++ b/crates/ui-egui/src/scale_tests.rs @@ -40,7 +40,7 @@ fn ms(f: impl FnOnce()) -> f64 { fn frame_and_cheap_command_cost_by_body_count() { for n in [50, 500, 5000] { let mut h = grid(n); - h.app.session.world_state().warm_meshes(|| true); + h.app.session.world_state().unwrap().warm_meshes(|| true); let scene_cold = ms(|| drop(crate::viewport::build_scene(&h.app))); let scene_again = ms(|| drop(crate::viewport::build_scene(&h.app))); let idle = ms(|| h.frames(10)) / 10.0; @@ -378,7 +378,7 @@ fn frame_cost_of_a_design_file() { let doc = solidcraft_engine::io::read_design(&bytes).unwrap(); let mut h = Harness::new(); h.app.session = solidcraft_engine::Session::new(doc); - h.app.session.world_state().warm_meshes(|| true); + h.app.session.world_state().unwrap().warm_meshes(|| true); h.frames(3); let idle = ms(|| h.frames(5)) / 5.0; let keys: Vec = @@ -388,7 +388,7 @@ fn frame_cost_of_a_design_file() { let expanded = ms(|| h.frames(5)) / 5.0; let scene = ms(|| drop(crate::viewport::build_scene(&h.app))); let scene_again = ms(|| drop(crate::viewport::build_scene(&h.app))); - let bodies = h.app.session.world_state().bodies.len(); + let bodies = h.app.session.world_state().unwrap().bodies.len(); let rename = ms(|| { h.app.run("body.rename", json!({"body": "Body1", "name": "Renamed"})).unwrap(); h.frame(); diff --git a/crates/ui-egui/src/select_other.rs b/crates/ui-egui/src/select_other.rs index 717613980..4973973a8 100644 --- a/crates/ui-egui/src/select_other.rs +++ b/crates/ui-egui/src/select_other.rs @@ -312,7 +312,7 @@ fn point_label(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> String { /// A row's name: "Line 3", "Point (arc 2 centre)", "Edge 4 · Body1", "XY Plane"… pub fn label(app: &SolveApp, sel: &Sel) -> String { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let in_sketch = |sketch: u64, f: &dyn Fn(&solidcraft_engine::sketch::Sketch) -> String| st.sketch(sketch).map(|ss| f(&ss.sketch)).unwrap_or_default(); match sel { @@ -338,7 +338,7 @@ pub fn label(app: &SolveApp, sel: &Sel) -> String { } fn icon(app: &SolveApp, sel: &Sel) -> &'static str { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let curve = |sketch: Option, id: &str| { let kind = sketch.and_then(|s| st.sketch(s)).and_then(|ss| ss.sketch.curves.iter().find(|c| c.id == id).map(|c| c.kind.clone())); match kind { diff --git a/crates/ui-egui/src/shell_face_sketch_ui_tests.rs b/crates/ui-egui/src/shell_face_sketch_ui_tests.rs index 9e96658cb..8f7877f2f 100644 --- a/crates/ui-egui/src/shell_face_sketch_ui_tests.rs +++ b/crates/ui-egui/src/shell_face_sketch_ui_tests.rs @@ -24,7 +24,7 @@ fn assert_attached(h: &Harness) { assert_eq!(anchor.target.body, "Case"); assert_eq!(serde_json::to_value(&anchor.target.certificate).unwrap()["kind"], "shell_planar"); assert!(matches!(h.app.session.doc.sketch_face_attachment(id, &h.app.session.model), FaceAttachmentStatus::Healthy { .. })); - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let solved = world.sketch(id).unwrap(); assert!(solved.plane.origin.y.abs() < 1e-8); assert!(solved.plane.normal().y.abs() > 0.999); @@ -86,7 +86,7 @@ fn rounded_shell_corner_is_one_physical_face_above_and_below_the_floor() { h.call("ui.view", json!({"view":"iso"})); h.call("ui.view", json!({"view":"fit"})); h.settle(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); assert_eq!(state.body("Case").unwrap().body.face_count(), 19, "no artificial lower corner faces remain in the BRep"); let document = h.app.session.doc.to_json(); let undo = h.app.session.undo.len(); diff --git a/crates/ui-egui/src/sketch3d.rs b/crates/ui-egui/src/sketch3d.rs index 76ddb2971..9b2235c71 100644 --- a/crates/ui-egui/src/sketch3d.rs +++ b/crates/ui-egui/src/sketch3d.rs @@ -34,7 +34,7 @@ const ARROW: f32 = 60.0; /// Is the sketch being edited a 3D sketch? pub fn active(app: &SolveApp) -> bool { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); app.session.active_sketch.and_then(|s| st.sketch(s)).is_some_and(|ss| ss.sketch.view.three_d) } @@ -49,7 +49,7 @@ pub fn drawing(app: &SolveApp) -> bool { /// Points drawn in 3D: (wire id, fit index, point). fn drawn_points(app: &SolveApp) -> Vec<(String, usize, Vec3)> { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return Vec::new() }; ss.sketch.wires.iter().flat_map(|w| w.fit.iter().enumerate().map(|(i, p)| (w.id.clone(), i, *p))).collect() } @@ -73,7 +73,7 @@ pub fn point_at(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option<(Vec3, &'stati return Some((p, "Pt")); } } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let ss = app.session.active_sketch.and_then(|s| st.sketch(s))?; let (o, d) = proj.ray(pos); for h in pick_3d(app, proj, pos) { @@ -85,7 +85,7 @@ pub fn point_at(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option<(Vec3, &'stati } Hit::Vertex { point, .. } => return Some((point, "Vertex")), Hit::Edge { body, index, .. } => { - let ws = app.session.world_state(); + let ws = crate::open_meshing::session_world(&app.session); let m = ws.body(&body)?.mesh(); let e = m.edges.get(index)?; let best = e @@ -103,7 +103,7 @@ pub fn point_at(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option<(Vec3, &'stati /// The sketch-plane coordinates of `p` when it lies on the plane. fn on_plane(app: &SolveApp, p: Vec3) -> Option { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let ss = app.session.active_sketch.and_then(|s| st.sketch(s))?; let q = ss.plane.to_local(p); (ss.plane.to_world(q).dist(p) < 1e-6).then_some(q) @@ -356,7 +356,7 @@ fn target(app: &SolveApp, proj: &Proj, pos: Pos2, axis: Option, p: Vec3) - Some(p + u * ((b * d.dot(w0) - c * u.dot(w0)) / den)) } None => { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let n = app.session.active_sketch.and_then(|s| st.sketch(s))?.plane.normal(); let den = d.dot(n); (den.abs() > 1e-12).then(|| o + d * ((p - o).dot(n) / den)) diff --git a/crates/ui-egui/src/sketch3d_frame_ui_tests.rs b/crates/ui-egui/src/sketch3d_frame_ui_tests.rs index 6a3291e77..511eb9b15 100644 --- a/crates/ui-egui/src/sketch3d_frame_ui_tests.rs +++ b/crates/ui-egui/src/sketch3d_frame_ui_tests.rs @@ -38,14 +38,14 @@ fn bridge_line_snaps_to_points_on_two_visible_sketch_planes() { } h.step(&json!({"key":"Escape"})).unwrap(); h.step(&json!({"key":"Escape"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let wire = state.sketch(bridge).unwrap().sketch.wires.first().unwrap(); assert!(wire.fit[0].dist(Vec3::new(10.0, 20.0, 10.0)) < 1e-6); assert!(wire.fit[1].dist(Vec3::new(30.0, 35.0, 40.0)) < 1e-6); h.app.run("edit.undo", json!({})).unwrap(); - assert!(h.app.session.world_state().sketch(bridge).unwrap().sketch.wires.is_empty()); + assert!(h.app.session.world_state().unwrap().sketch(bridge).unwrap().sketch.wires.is_empty()); h.app.run("edit.redo", json!({})).unwrap(); - assert_eq!(h.app.session.world_state().sketch(bridge).unwrap().sketch.wires[0].fit, wire.fit); + assert_eq!(h.app.session.world_state().unwrap().sketch(bridge).unwrap().sketch.wires[0].fit, wire.fit); } /// Another sketch's point and an active sketch on the same XY plane, so both lie under one cursor. @@ -84,12 +84,12 @@ fn sketch_tools_never_pick_another_sketchs_point() { assert!(id.is_none(), "sketch_3d={sketch_3d}: snapped to foreign point id {id:?}"); assert!(at.dist(solidcraft_engine::geom::Vec2::new(10.0, 20.0)) < 0.5, "{at:?}"); if !sketch_3d { - let before = h.app.session.world_state().sketch(other).unwrap().sketch.clone(); + let before = h.app.session.world_state().unwrap().sketch(other).unwrap().sketch.clone(); // A real 2D line click there creates nothing tied to the other sketch's point. h.step(&json!({"click":{"world":[10,20,0]}})).unwrap(); h.step(&json!({"click":{"world":[40,5,0]}})).unwrap(); h.step(&json!({"key":"Escape"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let own = &state.sketch(active).unwrap().sketch; assert!(!own.curves.is_empty(), "line was drawn"); assert_eq!(state.sketch(other).unwrap().sketch, before, "other sketch untouched"); @@ -144,7 +144,7 @@ fn second_occurrence_drawn_wire_fit_picks_and_world_triad_drag_stay_aligned() { crate::sketch3d::active(&h.app), "palette click must enable 3D: raw={:?}, world={:?}, status={:?}, active={:?}", h.app.session.model.state().sketch(sketch).unwrap().sketch.view, - h.app.session.world_state().sketch(sketch).unwrap().sketch.view, + h.app.session.world_state().unwrap().sketch(sketch).unwrap().sketch.view, h.app.status, h.app.session.active_sketch ); @@ -173,7 +173,7 @@ fn second_occurrence_drawn_wire_fit_picks_and_world_triad_drag_stay_aligned() { let wire = raw.sketch(sketch).unwrap().sketch.wires.first().expect("actual off-plane clicks create a wire"); assert!(wire.fit[0].dist(Vec3::new(2.0, 3.0, 5.0)) < 1e-6, "{:?}", wire.fit); assert!(wire.fit[1].dist(Vec3::new(2.0, 3.0, 15.0)) < 1e-6, "{:?}", wire.fit); - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let shown = &world.sketch(sketch).unwrap().sketch.wires[0]; assert!(shown.fit[0].dist(Vec3::new(17.0, 32.0, 45.0)) < 1e-6, "{:?}", shown.fit); assert!(shown.fit[1].dist(Vec3::new(17.0, 32.0, 55.0)) < 1e-6, "{:?}", shown.fit); @@ -187,7 +187,7 @@ fn second_occurrence_drawn_wire_fit_picks_and_world_triad_drag_stay_aligned() { let fit = &moved.sketch(sketch).unwrap().sketch.wires[0].fit; assert!(fit[0].dist(Vec3::new(2.0, -1.0, 5.0)) < 1e-5, "{fit:?}"); assert!(fit[1].dist(Vec3::new(2.0, 3.0, 15.0)) < 1e-6); - let placed = h.app.session.world_state(); + let placed = h.app.session.world_state().unwrap(); assert!(placed.sketch(sketch).unwrap().sketch.wires[0].fit[0].dist(Vec3::new(21.0, 32.0, 45.0)) < 1e-5); assert_eq!(h.app.session.undo.len(), history + 1); h.app.run("edit.undo", json!({})).unwrap(); diff --git a/crates/ui-egui/src/sketch_attachment_ui_tests.rs b/crates/ui-egui/src/sketch_attachment_ui_tests.rs index 7fa8ed395..9bf877ae4 100644 --- a/crates/ui-egui/src/sketch_attachment_ui_tests.rs +++ b/crates/ui-egui/src/sketch_attachment_ui_tests.rs @@ -59,8 +59,8 @@ fn lost_attachment_ghost_rebind_preview_cancel_apply_and_undo_preserve_sketch() h.app.run("solid.extrude", json!({"sketch":sketch,"distance":2,"operation":"new_body","body_name":"Boss"})).unwrap(); h.app.run("timeline.suppress", json!({"feature":"Original","suppressed":true})).unwrap(); assert!(h.app.session.model.result(sketch).unwrap().error.is_some()); - assert!(h.app.session.world_state().body("Boss").is_none(), "lost attachment cannot produce a Boss on ControlBox"); - assert!(h.app.session.world_state().sketch(sketch).is_none(), "saved repair guides are not solved sketch geometry"); + assert!(h.app.session.world_state().unwrap().body("Boss").is_none(), "lost attachment cannot produce a Boss on ControlBox"); + assert!(h.app.session.world_state().unwrap().sketch(sketch).is_none(), "saved repair guides are not solved sketch geometry"); let raw = raw_sketch(&h, sketch); let before = h.app.session.doc.to_json(); h.app.edit_sketch(sketch); @@ -111,7 +111,7 @@ fn lost_attachment_ghost_rebind_preview_cancel_apply_and_undo_preserve_sketch() assert_eq!(raw_sketch(&h, sketch), raw, "curves, dimensions and expressions remain exact"); assert_eq!(h.app.session.undo.len(), undo + 1); assert!(h.app.session.model.result(sketch).unwrap().error.is_none()); - let boss = h.app.session.world_state().body("Boss").unwrap().mesh().bounds(); + let boss = h.app.session.world_state().unwrap().body("Boss").unwrap().mesh().bounds(); assert!((boss.min.z - 30.0).abs() < 1e-7 && (boss.max.z - 32.0).abs() < 1e-7); let repaired = h.app.session.doc.to_json(); let path = h.dir.join("rebound-face.solidcraft"); @@ -262,7 +262,7 @@ fn nested_anchor_saved_fixed_conversion_preserves_rotated_second_author_plane() h.app.run("component.activate", json!({"component":component,"path":[second],"occurrence":second})).unwrap(); let doc = h.app.session.placed_document(); let body_name = doc.body_frames_with_source(&h.app.session.model.state()).into_iter().find(|(_, _, _, path, _)| path == &[second]).unwrap().0; - let world = h.app.session.world_state(); + let world = h.app.session.world_state().unwrap(); let face = world .body(&body_name) .unwrap() diff --git a/crates/ui-egui/src/sketch_clover_ui_tests.rs b/crates/ui-egui/src/sketch_clover_ui_tests.rs index a393f804f..b96e227ae 100644 --- a/crates/ui-egui/src/sketch_clover_ui_tests.rs +++ b/crates/ui-egui/src/sketch_clover_ui_tests.rs @@ -40,12 +40,12 @@ fn a_clover_of_typed_10_by_10_rectangles_is_drawn_and_fully_constrained() { if let Some((message, _, true)) = &h.app.status { panic!("rectangle {i} was refused: {message}"); } - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let solved = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(solved.sketch.curves.iter().filter(|c| !c.construction).count(), 4 * (i + 1), "rectangle {i} was not added"); assert!(solved.report.ok()); } - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let solved = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(solved.profiles.len(), 4); assert!(solved.profiles.iter().all(|p| (p.area - 100.0).abs() < 1e-6), "{:?}", solved.profiles.iter().map(|p| p.area).collect::>()); @@ -64,7 +64,7 @@ fn a_clover_drawn_by_clicks_snaps_every_corner_without_redundant_constraints() { rectangle(&mut h, a, b, false); } assert!(h.app.status.as_ref().is_none_or(|(_, _, error)| !error), "{:?}", h.app.status); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let solved = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(solved.profiles.len(), 4); assert!(solved.report.ok() && solved.report.redundant.is_empty(), "{:?}", solved.report); diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index aa14d0629..28b9f8f75 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -138,7 +138,7 @@ fn clicked_extend_endpoint_reaches_exact_ellipse_and_preserves_support() { h.frames(2); h.step(&json!({"start":"sketch.extend"})).unwrap(); h.step(&json!({"click":{"world":[5,3,0]}})).unwrap(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); let end = ss.sketch.point(ss.sketch.resolve_point("l1.end").unwrap()).unwrap(); assert!(end.dist(Vec2::new(12.0, 3.0)) < 1e-7, "clicked endpoint must extend: {end:?}, {:?}", h.app.status); @@ -193,7 +193,7 @@ fn apply(h: &mut crate::scenario::Harness) { /// Is there a point of the active sketch at `at`? fn has_point(h: &crate::scenario::Harness, at: Vec2) -> bool { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let Some(ss) = h.app.session.active_sketch.and_then(|sid| st.sketch(sid)) else { return false }; ss.sketch.points.iter().any(|p| p.pos.dist(at) < 1e-6) } @@ -232,7 +232,7 @@ fn corner_window_takes_the_corner_then_applies_the_typed_size() { apply(&mut h); assert!(h.app.dialog.is_none(), "{command}: {:?}", h.app.status); assert_eq!(h.app.session.undo.len(), before.1 + 1, "{command} must be one undo entry"); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(sid).unwrap(); assert_eq!(ss.sketch.point(0), Some(Vec2::ZERO)); assert!(ss.sketch.points[0].fixed); @@ -247,7 +247,7 @@ fn corner_window_takes_the_corner_then_applies_the_typed_size() { assert!((ss.profiles[0].area - expected).abs() < 1e-6, "{command}: {}", ss.profiles[0].area); drop(st); h.app.run("edit.undo", json!({})).unwrap(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(sid).unwrap(); assert_eq!(ss.sketch.curves.len(), 4); assert!((ss.profiles[0].area - 600.0).abs() < 1e-6); @@ -304,7 +304,7 @@ fn fillet_window_reads_design_units_and_preserves_explicit_units_and_parameters( apply(&mut h); assert!(h.app.dialog.is_none(), "{units}, {text}, lines {lines}: {:?}", h.app.status); let check = |session: &solidcraft_engine::Session, expected: f64| { - let state = session.world_state(); + let state = session.world_state().unwrap(); let ss = state.sketch(1).unwrap(); let arc = ss .sketch @@ -355,7 +355,7 @@ fn typed_chamfer_angle_other_than_45_degrees_reaches_the_command() { assert!(has_point(&h, Vec2::new(30.0, 0.0)), "10 mm along the first line"); assert!(has_point(&h, Vec2::new(40.0, second)), "{second} mm along the second line, not 10 mm"); assert!(!has_point(&h, Vec2::new(40.0, 10.0)), "45 degrees must no longer be forced"); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert!((ss.profiles[0].area - (1200.0 - 0.5 * 10.0 * second)).abs() < 1e-6, "{}", ss.profiles[0].area); } @@ -480,7 +480,7 @@ fn a_fillet_rounds_every_picked_corner_to_one_radius() { apply(&mut h); assert!(h.app.dialog.is_none(), "{:?}", h.app.status); assert_eq!(h.app.session.undo.len(), undo + 1, "one radius, one undo entry"); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(ss.sketch.curves.iter().filter(|c| matches!(c.kind, CurveKind::Arc { .. })).count(), 3); assert!((ss.profiles[0].area - (1200.0 - 3.0 * 25.0 * (1.0 - std::f64::consts::PI / 4.0))).abs() < 1e-6, "{}", ss.profiles[0].area); @@ -511,7 +511,7 @@ fn fully_constrained_center_rectangle_corners_can_be_picked_and_filleted() { let info = h.app.run("sketch.inspect", json!({})).unwrap(); assert_eq!(info["dof"], 0, "{info}"); assert_eq!(info["status"], "solved", "{info}"); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(ss.sketch.curves.iter().filter(|c| matches!(c.kind, CurveKind::Arc { .. })).count(), 4); assert!((ss.profiles[0].area - (1200.0 - 36.0 * (1.0 - std::f64::consts::PI / 4.0))).abs() < 1e-6); @@ -536,7 +536,7 @@ fn ordinary_drawing_keeps_origin_snap_and_real_origin_corners_work() { set_size(&mut h.app, "5"); apply(&mut h); assert!(h.app.dialog.is_none(), "{:?}", h.app.status); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(ss.sketch.point(0), Some(Vec2::ZERO)); assert!(ss.sketch.curves.iter().any(|c| matches!(c.kind, CurveKind::Arc { .. }))); @@ -609,7 +609,7 @@ fn fillet_chamfer_corner_preview_draws_curves() { // Verify the sketch itself hasn't been modified yet. let sid = h.app.session.active_sketch.unwrap(); - let sk = h.app.session.world_state().sketch(sid).unwrap().sketch.clone(); + let sk = h.app.session.world_state().unwrap().sketch(sid).unwrap().sketch.clone(); assert_eq!(sk.curves.len(), 2, "fillet preview must not modify the sketch"); // Now test chamfer too. Close the fillet dialog first. @@ -623,7 +623,7 @@ fn fillet_chamfer_corner_preview_draws_curves() { // Show the chamfer line and both shortened sides too. h.step(&json!({"until":{"count":{"name":"sketch_preview_curves","value":3}}})).unwrap(); - let sk = h.app.session.world_state().sketch(sid).unwrap().sketch.clone(); + let sk = h.app.session.world_state().unwrap().sketch(sid).unwrap().sketch.clone(); assert_eq!(sk.curves.len(), 2, "chamfer preview must not modify the sketch"); } diff --git a/crates/ui-egui/src/sketch_dims.rs b/crates/ui-egui/src/sketch_dims.rs index 756feb83e..d8dbf901a 100644 --- a/crates/ui-egui/src/sketch_dims.rs +++ b/crates/ui-egui/src/sketch_dims.rs @@ -172,7 +172,7 @@ fn on_curve_axis(app: &SolveApp, t: &Tool, p: &(Vec2, Option)) -> Option if ang == v.angle() { return None; } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let sk = &st.sketch(app.session.active_sketch?)?.sketch; let shape = sk.shape(sk.curve_index(curve)?)?; let dir = Vec2::from_angle(ang); @@ -443,7 +443,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, proj: &Proj) { fn boxes(app: &SolveApp, ui: &mut egui::Ui, proj: &Proj, t: &mut Tool) -> Option { let tk = Tokens::get(); let sid = app.session.active_sketch?; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let plane = st.sketch(sid)?.plane; let e = shown(app, t, t.hover.as_ref()?); let px = 2.0 * app.cam.half_height() / f64::from(proj.rect.height().max(1.0)); diff --git a/crates/ui-egui/src/sketch_dims_tests.rs b/crates/ui-egui/src/sketch_dims_tests.rs index d57a82f5e..d95ed9ca1 100644 --- a/crates/ui-egui/src/sketch_dims_tests.rs +++ b/crates/ui-egui/src/sketch_dims_tests.rs @@ -54,7 +54,7 @@ fn tabs_cycle_rectangle_dimensions_indefinitely_and_enter_commits_values() { assert_eq!(dims.iter().map(|d| d.value.as_str()).collect::>(), ["32", "14"]); assert!(dims.iter().all(|d| d.locked)); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(sketch.sketch.curves.iter().filter(|curve| !curve.construction).count(), 4); assert_eq!(sketch.profiles.len(), 1); @@ -75,7 +75,7 @@ fn line_dimensions_wrap_both_directions_and_enter_uses_length_and_angle() { tab(&mut h, true); assert_focus(&h, 0); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(sketch.sketch.curves.len(), 1); let points: Vec<_> = sketch.sketch.points.iter().map(|point| point.pos).collect(); @@ -92,7 +92,7 @@ fn single_dimension_keeps_focus_for_tab_and_shift_tab() { } assert_eq!(h.app.tool.as_ref().unwrap().dims[0].value, "8"); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(sketch.profiles.len(), 1); assert!((sketch.profiles[0].area - std::f64::consts::PI * 16.0).abs() < 1e-6); @@ -122,7 +122,7 @@ fn forward_tab_completes_expression_then_cycles_and_shift_tab_moves_back() { assert_focus(&h, 0); assert_eq!(h.app.tool.as_ref().unwrap().dims[0].value, "width"); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(sketch.profiles.len(), 1); assert!((sketch.profiles[0].area - 120.0).abs() < 1e-6); @@ -191,7 +191,7 @@ fn inch_live_lengths_use_design_units_and_typed_four_digits_commit_in_inches() { assert!((crate::sketch_dims::locked_value(&h.app, tool, "Width").unwrap() - 31.3563).abs() < 1e-6); assert!((crate::sketch_dims::locked_value(&h.app, tool, "Height").unwrap() - 12.7).abs() < 1e-6); h.step(&json!({"key":"Enter"})).unwrap(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!(sk.constraints.iter().any(|c| c.kind.value().is_some_and(|v| (v - 31.3563).abs() < 1e-6))); } @@ -220,7 +220,7 @@ fn a_typed_rho_shapes_the_conic_whose_apex_is_placed_next() { assert!(h.app.tool.as_ref().unwrap().dims[0].locked); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let (apex, rho) = sketch .curves @@ -247,7 +247,7 @@ fn a_rho_outside_zero_to_one_is_refused_before_it_reaches_the_command() { type_value(&mut h, "5"); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!(sketch.curves.is_empty(), "a refused rho must place nothing"); let tool = h.app.tool.as_ref().expect("the tool stays active for a correction"); @@ -270,7 +270,7 @@ fn rounded_rectangle_takes_typed_width_height_and_radius() { type_value(&mut h, "4"); let undo = h.app.session.undo.len(); h.step(&json!({"key": "Enter"})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); let kinds: Vec<_> = sketch.sketch.curves.iter().map(|c| matches!(c.kind, solidcraft_engine::sketch::CurveKind::Arc { .. })).collect(); assert_eq!(kinds.iter().filter(|arc| **arc).count(), 4, "four corner arcs"); @@ -289,7 +289,7 @@ fn rounded_rectangle_clicks_use_a_default_radius() { h.step(&json!({"start": "sketch.rectangle.rounded"})).unwrap(); h.step(&json!({"click": {"sketch": [0, 0]}})).unwrap(); h.step(&json!({"click": {"sketch": [40, 20]}})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(sketch.profiles.len(), 1, "{:?}", h.app.status); let (w, hh) = (40.0, 20.0); @@ -321,7 +321,7 @@ fn a_line_end_on_a_circle_within_the_axis_snap_lands_on_the_quadrant_the_preview let shown = crate::sketch_dims::shown(&h.app, tool, &hover); assert!(shown.dist(end) < 1e-9, "{deg}: preview at {shown:?}"); h.step(&json!({"click": {"world": [at.x, at.y, 0]}})).unwrap(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let sk = &st.sketch(sid).unwrap().sketch; let (line, a, b) = sk .curves @@ -358,7 +358,7 @@ fn a_line_end_on_a_circle_outside_the_axis_snap_stays_at_the_cursor() { let at = Vec2::from_angle(20f64.to_radians()) * 30.0; h.step(&json!({"move": {"world": [at.x, at.y, 0]}})).unwrap(); h.step(&json!({"click": {"world": [at.x, at.y, 0]}})).unwrap(); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let sk = &st.sketch(sid).unwrap().sketch; let b = sk.curves.iter().find_map(|c| if let CurveKind::Line { b, .. } = c.kind { Some(b) } else { None }).unwrap(); let end = sk.point(b).unwrap(); diff --git a/crates/ui-egui/src/sketch_display.rs b/crates/ui-egui/src/sketch_display.rs index 15959bece..aae677edd 100644 --- a/crates/ui-egui/src/sketch_display.rs +++ b/crates/ui-egui/src/sketch_display.rs @@ -281,7 +281,7 @@ impl DisplayCache { } pub fn profile_region(app: &SolveApp, sketch: u64, index: usize, plane: &Plane, proj: &Proj) -> Arc> { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let ppp = app.viewport.pixels_per_point(); match app.viewport.display.lock() { Ok(mut cache) => cache.profile(state, sketch, index, plane, proj, ppp), @@ -290,7 +290,7 @@ pub fn profile_region(app: &SolveApp, sketch: u64, index: usize, plane: &Plane, } pub fn curve_sample(app: &SolveApp, sketch: u64, index: usize, plane: &Plane, proj: &Proj) -> Arc { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let ppp = app.viewport.pixels_per_point(); match app.viewport.display.lock() { Ok(mut cache) => cache.curve(state, sketch, index, plane, proj, ppp), diff --git a/crates/ui-egui/src/sketch_display_preview_tests.rs b/crates/ui-egui/src/sketch_display_preview_tests.rs index d133e2c5c..1156f1b87 100644 --- a/crates/ui-egui/src/sketch_display_preview_tests.rs +++ b/crates/ui-egui/src/sketch_display_preview_tests.rs @@ -90,7 +90,7 @@ fn pixel_preview_temporary_curves_match_committed_geometry_and_sampling() { let mut h = Harness::new(); h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.app.run(command, params).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let committed = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let a = spans(&preview); let b = spans(committed); @@ -215,7 +215,7 @@ fn slot_preview_matches_every_committed_side_and_cap() { "{command}: paint all four outline curves" ); h.app.run(command, params).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let committed = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert_eq!(preview.curves.len(), committed.curves.len(), "{command}"); for index in 0..committed.curves.len() { @@ -262,12 +262,12 @@ fn typed_small_slot_width_preview_matches_the_final_click() { .collect::>() }; let preview = paths(output); - assert!(h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.is_empty()); + assert!(h.app.session.world_state().unwrap().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.is_empty()); let click = crate::sketch_dims::placed(&h.app, &t, t.hover.as_ref().unwrap()); h.app.tool = Some(t); super::place(&mut h.app, click); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let committed = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert_eq!(committed.curves.len(), 4, "{command}: final click commits the typed width"); let solidcraft_engine::geom::Seg2::Arc { radius, .. } = committed.segs(1)[0] else { panic!("missing slot cap") }; diff --git a/crates/ui-egui/src/sketch_display_ui_tests.rs b/crates/ui-egui/src/sketch_display_ui_tests.rs index 9aab5d151..23e42d48a 100644 --- a/crates/ui-egui/src/sketch_display_ui_tests.rs +++ b/crates/ui-egui/src/sketch_display_ui_tests.rs @@ -51,7 +51,7 @@ fn pixel_circle_fit_exact_half_chord_hover_click_and_model_invariance() { let sid = circle(&mut h); let baseline = h.app.session.doc.to_json(); let history = (h.app.session.undo.len(), h.app.session.redo.len()); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let ss = state.sketch(sid).unwrap(); let plane = ss.plane; let index = ss.sketch.curve_index("c1").unwrap(); @@ -97,7 +97,7 @@ fn pixel_cache_full_view_resize_and_hidpi_invalidate_within_same_grid_bucket() { h.app.cam.target = Vec3::ZERO; let baseline = h.app.session.doc.to_json(); let history = (h.app.session.undo.len(), h.app.session.redo.len()); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); assert_eq!(state.bodies.len(), 1, "body batch invariance needs an actual mesh"); let ss = state.sketch(sid).unwrap(); let index = ss.sketch.curve_index("c1").unwrap(); @@ -159,7 +159,7 @@ fn pixel_adapter_uses_exact_ellipse_periodic_fit_and_control_spline_spans() { h.settle(); let baseline = h.app.session.doc.to_json(); let sid = h.app.session.active_sketch.unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let ss = state.sketch(sid).unwrap(); let exact = ss.sketch.exact_segs(0).unwrap(); assert!( @@ -202,7 +202,7 @@ fn pixel_curve_second_nested_rotated_occurrence_uses_its_world_plane() { h.app.run("browser.visibility", json!({"paths":[[first]],"visible":false})).unwrap(); let sid = circle(&mut h); let baseline = h.app.session.doc.to_json(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let ss = state.sketch(sid).unwrap(); assert!(ss.plane.origin.dist(Vec3::new(20.0, 30.0, 40.0)) < 1e-8); let tilt = 35.0f64.to_radians(); @@ -227,7 +227,7 @@ fn pixel_annulus_fill_keeps_hole_and_cpu_bridge_matches_cached_boundaries() { h.app.run("sketch.circle.center", json!({"center":[0,0],"radius":0.5})).unwrap(); h.settle(); let baseline = h.app.session.doc.to_json(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let ss = state.sketch(sid).unwrap(); let proj = projection(&h.app, h.app.viewport.rect.unwrap()); let ppp = h.app.viewport.pixels_per_point(); @@ -271,7 +271,7 @@ fn pixel_frame_budget_does_not_cache_unbounded_empty_curve_results() { let mut h = Harness::new(); let sid = circle(&mut h); let baseline = h.app.session.doc.to_json(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let mut plane = state.sketch(sid).unwrap().plane; let proj = projection(&h.app, h.app.viewport.rect.unwrap()); let mut limited = 0; @@ -343,7 +343,7 @@ fn zoomed_in_ring_fill_fits_the_hover_highlight_budget() { h.settle(); let baseline = h.app.session.doc.to_json(); let sid = h.app.session.active_sketch.unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let ss = state.sketch(sid).unwrap(); let proj = projection(&h.app, h.app.viewport.rect.unwrap()); let ppp = h.app.viewport.pixels_per_point(); diff --git a/crates/ui-egui/src/sketch_drag_ui_tests.rs b/crates/ui-egui/src/sketch_drag_ui_tests.rs index 742fa5d94..a1487c8b4 100644 --- a/crates/ui-egui/src/sketch_drag_ui_tests.rs +++ b/crates/ui-egui/src/sketch_drag_ui_tests.rs @@ -67,7 +67,7 @@ fn screen(h: &mut Harness, x: f64, y: f64) -> egui::Pos2 { fn point(h: &Harness, id: &str) -> Vec2 { let sid = h.app.session.active_sketch.expect("sketch mode"); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let sk = &st.sketch(sid).expect("the sketch").sketch; sk.resolve_point(id).and_then(|i| sk.point(i)).unwrap_or_else(|| panic!("no point {id}")) } @@ -237,7 +237,7 @@ fn associated_spline_offset_hides_fit_nodes_and_follows_a_source_drag_live() { h.app.cam.distance = 65.0; h.frames(3); let sid = h.app.session.active_sketch.unwrap(); - let original = h.app.session.world_state().sketch(sid).unwrap().sketch.clone(); + let original = h.app.session.world_state().unwrap().sketch(sid).unwrap().sketch.clone(); let source = original.curve_index("s1").unwrap(); let derived = original.curve_index(&output).unwrap(); let source_points = original.curves[source].kind.point_ids(); @@ -280,7 +280,7 @@ fn associated_spline_offset_hides_fit_nodes_and_follows_a_source_drag_live() { play(&mut h); assert!(h.app.viewport.point_drag.is_some()); assert!(h.app.session.model.is_stale(), "the drag has not been released"); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(sid).unwrap().sketch; assert!(sk.points[source_points[1]].pos.dist(target) < 0.1, "source follows the held pointer: {:?}", sk.points[source_points[1]].pos); assert_ne!(sk.exact_segs(derived), original.exact_segs(derived), "the offset follows before release"); @@ -303,11 +303,11 @@ fn associated_spline_offset_hides_fit_nodes_and_follows_a_source_drag_live() { assert_eq!(h.app.session.doc.to_json(), before); run(&mut h, "edit.redo", json!({})); run(&mut h, "sketch.offset.break", json!({"curve":output})); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(sid).unwrap().sketch; assert!(sk.curves[derived].kind.point_ids().iter().all(|i| solidcraft_engine::view::sketch_point_visible(sk, *i))); run(&mut h, "edit.undo", json!({})); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(sid).unwrap().sketch; assert!(sk.curves[derived].kind.point_ids().iter().all(|i| !solidcraft_engine::view::sketch_point_visible(sk, *i))); } @@ -324,7 +324,7 @@ fn dragging_a_selected_line_moves_the_whole_selection() { run(&mut h, "sketch.dimension", json!({"entities": ["l4"], "value": 5})); run(&mut h, "sketch.line", json!({"points": [[80, 10], [80, 30]], "connect": false})); let sid = h.app.session.active_sketch.expect("sketch mode"); - let before = h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone(); + let before = h.app.session.world_state().unwrap().sketch(sid).expect("the sketch").sketch.clone(); let lines = ["l1", "l2", "l3", "l4"]; let mut selected: Vec = lines.iter().flat_map(|l| before.curves[before.curve_index(l).unwrap()].kind.point_ids()).collect(); selected.sort_unstable(); @@ -340,7 +340,7 @@ fn dragging_a_selected_line_moves_the_whole_selection() { path.extend(steps(a, b, 8)); press_and_move(&mut h, &path); release(&mut h, b); - let after = &h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone(); + let after = &h.app.session.world_state().unwrap().sketch(sid).expect("the sketch").sketch.clone(); for &p in &selected { let moved = after.points[p].pos - before.points[p].pos; assert!(moved.dist(Vec2::new(10.0, -10.0)) < 0.05, "{} moved by {moved:?}", before.points[p].id); @@ -369,7 +369,7 @@ fn a_window_selected_circle_still_takes_its_radius_from_a_drag_on_its_edge() { release(&mut h, b); assert!(point(&h, "c1.center").dist(Vec2::new(20.0, 20.0)) < 1e-9); let sid = h.app.session.active_sketch.expect("sketch mode"); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let sk = &st.sketch(sid).expect("the sketch").sketch; let r = sk.radius(sk.curve_index("c1").expect("the circle")).expect("a radius"); assert!((r - 15.0).abs() < 0.05, "{r}"); diff --git a/crates/ui-egui/src/sketch_guidance_ui_tests.rs b/crates/ui-egui/src/sketch_guidance_ui_tests.rs index 1dd92524c..60ad0752c 100644 --- a/crates/ui-egui/src/sketch_guidance_ui_tests.rs +++ b/crates/ui-egui/src/sketch_guidance_ui_tests.rs @@ -77,7 +77,7 @@ fn sketch_dialog_patterns_update_counts_and_place_an_unsnapped_centre() { h.frames(3); preview(&mut h, 7); step(&mut h, json!({"click":{"handle":"dialog:OK"}})); - assert_eq!(h.app.session.world_state().sketch(1).unwrap().sketch.curves.len(), 10); + assert_eq!(h.app.session.world_state().unwrap().sketch(1).unwrap().sketch.curves.len(), 10); step(&mut h, json!({"start":"sketch.pattern.circular"})); pick(&mut h, [-22.5, 10.0], false); step(&mut h, json!({"call":"ui.dialogInput","params":{"index":1}})); @@ -89,7 +89,7 @@ fn sketch_dialog_patterns_update_counts_and_place_an_unsnapped_centre() { h.frames(3); preview(&mut h, 3); step(&mut h, json!({"click":{"handle":"dialog:OK"}})); - assert_eq!(h.app.session.world_state().sketch(1).unwrap().sketch.curves.len(), 13); + assert_eq!(h.app.session.world_state().unwrap().sketch(1).unwrap().sketch.curves.len(), 13); } #[test] @@ -109,7 +109,7 @@ fn sketch_dialog_offset_precise_distance_flip_and_editable_dimension() { step(&mut h, json!({"click":{"handle":"dialog:OK"}})); let param = h.app.session.doc.params.iter().find(|p| p.name.starts_with('d')).unwrap().name.clone(); step(&mut h, json!({"call":"engine.execute","params":{"command":"parameters.change","params":{"name":param,"expression":"3 mm"}}})); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; assert_eq!(sk.offsets[0].distance, -3.0); assert!(sk.constraints.iter().any(|c| matches!(c.kind, solidcraft_engine::sketch::ConstraintKind::OffsetDistance { .. }))); @@ -183,7 +183,7 @@ fn sketch_modify_inputs_refuse_other_sketches_without_changing_hole_points() { #[test] fn sketch_preselected_points_toggle_once_and_empty_shift_box_keeps_reference() { let mut h = fixture(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let point = state.sketch(1).unwrap().sketch.points[1].id.clone(); h.app.session.selection = vec![Sel::SketchPoint { id: point.clone() }]; h.app.start("sketch.mirror"); @@ -224,7 +224,7 @@ fn sketch_modify_previews_use_the_active_occurrences_world_placement() { let built = crate::preview::compute(&h.app.session, &[(command.into(), params.clone())], colors).unwrap(); let mut scratch = h.app.session.scratch(); scratch.execute(command, ¶ms).unwrap(); - let state = scratch.world_state(); + let state = scratch.world_state().unwrap(); let expected = state.sketch(sid).unwrap().plane; assert!(expected.origin.len() > 50.0, "the fixture must exercise a moved occurrence"); assert_eq!(built.sketches.len(), 1); @@ -237,7 +237,7 @@ fn sketch_modify_previews_use_the_active_occurrences_world_placement() { #[test] fn sketch_corner_preselected_point_uses_the_same_identity_as_corner_picking() { let mut h = fixture(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(1).unwrap().sketch; let index = sk.resolve_point("l1.end").unwrap(); let point = sk.points[index].id.clone(); @@ -261,5 +261,5 @@ fn sketch_modify_keeps_custom_point_ids_that_contain_colons() { for (command, params) in commands { h.app.run(&command, params).unwrap(); } - assert_eq!(h.app.session.world_state().sketch(1).unwrap().sketch.curves.len(), 8); + assert_eq!(h.app.session.world_state().unwrap().sketch(1).unwrap().sketch.curves.len(), 8); } diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index 0b4d281df..58d340b63 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -265,7 +265,7 @@ pub fn candidate(d: &Dialog, session: &solidcraft_engine::Session, hit: &Hit) -> pub fn edit_pattern(app: &mut SolveApp, id: &str) -> bool { use solidcraft_engine::sketch::SketchPatternKind; let Some(sid) = app.session.active_sketch else { return false }; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let Some(sk) = state.sketch(sid).map(|s| &s.sketch) else { return false }; let Some(pattern) = sk.patterns.iter().find(|p| p.id == id) else { return false }; let input = |key: &str, fallback: String| pattern.expressions.get(key).cloned().unwrap_or(fallback); @@ -325,9 +325,7 @@ pub fn edit_pattern(app: &mut SolveApp, id: &str) -> bool { pub fn double_click_pattern(app: &mut SolveApp, pos: Pos2) -> bool { let Some(glyph) = crate::sketch_tools::glyph_at(pos) else { return false }; let Some(sid) = app.session.active_sketch else { return false }; - let id = app - .session - .world_state() + let id = crate::open_meshing::session_world(&app.session) .sketch(sid) .and_then(|ss| ss.sketch.patterns.iter().find(|p| p.instances.iter().any(|i| i.constraints.contains(&glyph))).map(|p| p.id.clone())); id.is_some_and(|id| edit_pattern(app, &id)) @@ -498,7 +496,7 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Mod, doc: &Document) -> bool { /// in it. fn sketch_dir(app: &SolveApp, sel: &Sel) -> Option { let dir = crate::dialogs::axis_of(app, sel)?.1; - let plane = app.session.world_state().sketch(app.session.active_sketch?)?.plane; + let plane = crate::open_meshing::session_world(&app.session).sketch(app.session.active_sketch?)?.plane; Vec2::new(dir.dot(plane.x), dir.dot(plane.y)).normalized() } @@ -511,7 +509,7 @@ pub fn arrow(app: &SolveApp, d: &Dialog) -> Option { let Kind::SketchModify(k) = &d.kind else { return None }; match k { Mod::PatternRect { alignment, reversed, .. } => { - let plane = app.session.world_state().sketch(app.session.active_sketch?)?.plane; + let plane = crate::open_meshing::session_world(&app.session).sketch(app.session.active_sketch?)?.plane; let dir = pattern_dir(app, d)?; Some(plane.dir_to_world(if (*alignment == PatternAlignment::Left) ^ *reversed { -dir } else { dir })) } @@ -535,7 +533,7 @@ fn pattern_dir(app: &SolveApp, d: &Dialog) -> Option { /// the first, as the command does. pub fn arrow2(app: &SolveApp, d: &Dialog) -> Option { let Kind::SketchModify(Mod::PatternRect { alignment2, reversed2, .. }) = &d.kind else { return None }; - let plane = app.session.world_state().sketch(app.session.active_sketch?)?.plane; + let plane = crate::open_meshing::session_world(&app.session).sketch(app.session.active_sketch?)?.plane; let dir = match d.inputs.get(2).and_then(|i| i.items.first()) { Some(sel) => sketch_dir(app, sel)?, None => match d.extra.get("dir2").and_then(|v| serde_json::from_value::(v.clone()).ok()).and_then(Vec2::normalized) { @@ -585,7 +583,7 @@ pub(crate) fn point_id<'a>(session: &solidcraft_engine::Session, sel: &'a Sel) - let active = session.active_sketch?; // Custom local ids may themselves contain ':'. Preserve them before interpreting a // legacy qualified selection, whose owner must match the sketch being edited. - if session.world_state().sketch(active).is_some_and(|sk| sk.sketch.point_index(id).is_some()) { + if crate::open_meshing::session_world(session).sketch(active).is_some_and(|sk| sk.sketch.point_index(id).is_some()) { Some(id) } else { (owner.parse::().ok() == Some(active)).then_some(point) @@ -706,7 +704,7 @@ fn corner_ref(app: &SolveApp, point: &str, flip: bool) -> Result } let gone = || "that corner is no longer in the sketch".to_string(); let sketch = app.session.active_sketch.ok_or("open a sketch first")?; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let sk = &state.sketch(sketch).ok_or_else(gone)?.sketch; let index = sk.resolve_point(point).ok_or_else(gone)?; let (a, b) = crate::sketch_tools::corner_curves(sk, index, false).ok_or("a chamfer needs a corner of exactly two lines")?; @@ -857,8 +855,10 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map { - let plane = - app.session.world_state().sketch(app.session.active_sketch.ok_or("open a sketch first")?).ok_or("sketch is missing")?.plane; + let plane = crate::open_meshing::session_world(&app.session) + .sketch(app.session.active_sketch.ok_or("open a sketch first")?) + .ok_or("sketch is missing")? + .plane; let p = plane.to_local(*point); json!([p.x, p.y]) } diff --git a/crates/ui-egui/src/sketch_modify_ui_tests.rs b/crates/ui-egui/src/sketch_modify_ui_tests.rs index 551329a9e..65c938bad 100644 --- a/crates/ui-egui/src/sketch_modify_ui_tests.rs +++ b/crates/ui-egui/src/sketch_modify_ui_tests.rs @@ -436,7 +436,7 @@ fn the_x_distance_gets_a_drag_arrow_along_the_sketch_x_axis() { d.inputs[0].items = picks; } let sid = h.app.session.active_sketch.unwrap(); - let x = h.app.session.world_state().sketch(sid).unwrap().plane.x; + let x = h.app.session.world_state().unwrap().sketch(sid).unwrap().plane.x; let d = h.app.dialog.as_ref().unwrap(); let (_, dir) = crate::canvas::anchor(&h.app, d).expect("a picked sketch curve anchors the manipulator"); let dir = dir.expect("a sketch move's X Distance has a direction to drag along"); @@ -528,7 +528,7 @@ fn rectangular_sections_flip_and_center_independently_and_restore_even_counts_wh h.settle(); assert!(h.app.dialog.is_none()); let sid = h.app.session.active_sketch.unwrap(); - let pattern = h.app.session.world_state().sketch(sid).unwrap().sketch.patterns[0].id.clone(); + let pattern = h.app.session.world_state().unwrap().sketch(sid).unwrap().sketch.patterns[0].id.clone(); assert!(crate::sketch_modify_ui::edit_pattern(&mut h.app, &pattern)); assert!(matches!( h.app.dialog.as_ref().unwrap().kind, @@ -828,7 +828,7 @@ fn circular_flip_and_center_buttons_apply_and_reopen_the_saved_placement() { h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); let sid = h.app.session.active_sketch.unwrap(); let id = { - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let pattern = &state.sketch(sid).unwrap().sketch.patterns[0]; assert!(matches!(pattern.kind, SketchPatternKind::Circular { alignment: PatternAlignment::Center, reversed: true, .. })); pattern.id.clone() diff --git a/crates/ui-egui/src/sketch_neutral_click_tests.rs b/crates/ui-egui/src/sketch_neutral_click_tests.rs index ede9b88de..ee02a3880 100644 --- a/crates/ui-egui/src/sketch_neutral_click_tests.rs +++ b/crates/ui-egui/src/sketch_neutral_click_tests.rs @@ -35,7 +35,7 @@ fn repeated_first_point_is_neutral_and_drawing_can_continue() { } } assert!(!h.app.status.as_ref().is_some_and(|s| s.2), "{command}: {:?}", h.app.status); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); assert!(!state.sketches[0].sketch.curves.is_empty(), "{command}: {:?}; {:?}", h.app.tool, h.app.status); assert_eq!(h.app.session.undo.len(), undo + 1, "{command}"); h.app.run("edit.undo", json!({})).unwrap(); diff --git a/crates/ui-egui/src/sketch_palette.rs b/crates/ui-egui/src/sketch_palette.rs index cd91c2bc0..a2b6ce95d 100644 --- a/crates/ui-egui/src/sketch_palette.rs +++ b/crates/ui-egui/src/sketch_palette.rs @@ -157,7 +157,7 @@ fn selected_linetypes(app: &SolveApp) -> [bool; 4] { if curves.is_empty() { return types; } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return types }; for c in curves.iter().filter_map(|id| ss.sketch.curve_index(id).and_then(|i| ss.sketch.curves.get(i))) { let k = if c.infinite { @@ -185,7 +185,7 @@ pub fn set_linetype(app: &mut SolveApp, kind: u8) { return; } let lines: Vec = { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return }; curves .iter() @@ -242,7 +242,7 @@ fn viewport(app: &SolveApp, ctx: &egui::Context) -> egui::Rect { /// Is a sketch being edited? That is the palette's own condition. pub fn editing(app: &SolveApp) -> bool { - app.session.active_sketch.and_then(|s| app.session.world_state().sketch(s).map(|_| ())).is_some() + app.session.active_sketch.and_then(|s| crate::open_meshing::session_world(&app.session).sketch(s).map(|_| ())).is_some() } /// Has the viewport room for the palette and a command dialog side by side? A narrow view has @@ -317,7 +317,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { return; } let (opts, name, remaining, solved, total, geometry, open_ends, untied_ends) = { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)) else { return }; ( ss.sketch.view.clone(), @@ -585,7 +585,7 @@ mod tests { h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.app.run("sketch.circle.center", json!({"center":[10,10],"radius":5})).unwrap(); h.settle(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = state.sketch(h.app.session.active_sketch.unwrap()).unwrap(); assert_eq!(unconstrained_total(&sketch.sketch), 3); assert_eq!(sketch.report.dof, 3); @@ -648,12 +648,12 @@ mod tests { assert_eq!(after.dims.iter().map(|d| &d.value).collect::>(), before.dims.iter().map(|d| &d.value).collect::>()); assert_eq!(h.app.session.undo.len(), history); h.step(&json!({"click":{"sketch":[20,10]}})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!(!sketch.curves.is_empty(), "{command}"); assert!(sketch.curves.iter().all(|c| c.construction), "{command}"); h.app.run("edit.undo", json!({})).unwrap(); - assert!(h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.is_empty()); + assert!(h.app.session.world_state().unwrap().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.is_empty()); set_mode(&mut h.app, 0); } } @@ -684,7 +684,7 @@ mod tests { assert!(options.contains(egui::pos2(x as f32, y as f32)), "lower option must be visible after scrolling"); h.call("ui.click", json!({"x":x,"y":y})); h.settle(); - assert!(h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.view.three_d); + assert!(h.app.session.world_state().unwrap().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.view.three_d); assert_eq!(h.app.session.undo.len(), undo + 1); h.app.run("edit.undo", json!({})).unwrap(); assert_eq!(h.app.session.doc.to_json(), baseline); @@ -833,7 +833,7 @@ mod tests { h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.settle(); let active = h.app.session.active_sketch.unwrap(); - let slice_on = |h: &mut crate::scenario::Harness| h.app.session.world_state().sketch(active).unwrap().sketch.view.slice; + let slice_on = |h: &mut crate::scenario::Harness| h.app.session.world_state().unwrap().sketch(active).unwrap().sketch.view.slice; assert!(!slice_on(&mut h)); // Clicking the row's label (not just the checkbox) toggles the option, same as before // the checkbox and the label became separate widgets in their own column. @@ -961,7 +961,7 @@ mod tests { h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); h.settle(); let line = |h: &crate::scenario::Harness| { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let ss = h.app.session.active_sketch.and_then(|s| st.sketch(s)).unwrap(); dof_text(ss.report.dof, ss.report.ok(), has_geometry(&ss.sketch)) }; diff --git a/crates/ui-egui/src/sketch_shortcut_tests.rs b/crates/ui-egui/src/sketch_shortcut_tests.rs index 2b2fce954..342d07a2b 100644 --- a/crates/ui-egui/src/sketch_shortcut_tests.rs +++ b/crates/ui-egui/src/sketch_shortcut_tests.rs @@ -9,7 +9,7 @@ fn tool(h: &Harness) -> Option<&str> { fn normal(h: &Harness) -> solidcraft_engine::geom::Vec3 { let active = h.app.session.active_sketch; - h.app.session.world_state().sketches.iter().find(|s| Some(s.feature) == active).map(|s| s.plane.normal()).unwrap_or_default() + h.app.session.world_state().unwrap().sketches.iter().find(|s| Some(s.feature) == active).map(|s| s.plane.normal()).unwrap_or_default() } fn press(h: &mut Harness, key: &str) { @@ -79,7 +79,7 @@ fn sketch_keys_outside_a_sketch_sketch_on_the_selected_plane_and_start_their_too h.app.session.selection = vec![Sel::Plane { name: "XZ".into() }]; press(&mut h, key); assert!(h.app.session.active_sketch.is_some(), "{key}: no sketch opened"); - assert_eq!(h.app.session.world_state().sketches.len(), 1, "{key}"); + assert_eq!(h.app.session.world_state().unwrap().sketches.len(), 1, "{key}"); assert!(normal(&h).y.abs() > 0.999, "{key}: not on XZ: {:?}", normal(&h)); assert_eq!(tool(&h), Some(cmd), "{key}"); assert!(h.app.dialog.is_none(), "{key}: dialog left open"); @@ -173,7 +173,7 @@ fn construction_key_outside_a_sketch_opens_nothing_and_keys_in_a_sketch_keep_it( assert!(h.app.session.active_sketch.is_none()); h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); press(&mut h, "C"); - assert_eq!(h.app.session.world_state().sketches.len(), 1); + assert_eq!(h.app.session.world_state().unwrap().sketches.len(), 1); assert_eq!(tool(&h), Some("sketch.circle.center")); } diff --git a/crates/ui-egui/src/sketch_side_ui_tests.rs b/crates/ui-egui/src/sketch_side_ui_tests.rs index bb62fa614..cfd029aed 100644 --- a/crates/ui-egui/src/sketch_side_ui_tests.rs +++ b/crates/ui-egui/src/sketch_side_ui_tests.rs @@ -15,7 +15,7 @@ fn sketch_from(yaw: f64, pitch: f64, name: &str) -> (Harness, Vec3, Plane) { h.step(&json!({"start":"sketch.create"})).unwrap(); h.step(&json!({"click":{"plane":name}})).unwrap(); h.settle(); - let plane = h.app.session.world_state().sketches.first().map(|s| s.plane).expect("a sketch on the plane"); + let plane = h.app.session.world_state().unwrap().sketches.first().map(|s| s.plane).expect("a sketch on the plane"); (h, eye, plane) } @@ -61,7 +61,7 @@ fn a_flipped_sketch_extrudes_toward_the_viewer_and_reopens_the_same() { let sketch = h.app.session.active_sketch.unwrap(); h.app.finish_sketch(); h.app.run("solid.extrude", json!({"sketch":sketch,"distance":4,"operation":"new_body","body_name":"Block"})).unwrap(); - let bounds = |h: &Harness| h.app.session.world_state().body("Block").map(|b| b.mesh().bounds()).expect("an extruded body"); + let bounds = |h: &Harness| h.app.session.world_state().unwrap().body("Block").map(|b| b.mesh().bounds()).expect("an extruded body"); let before = bounds(&h); assert!(before.min.y < -3.9 && before.max.y < 1e-6, "extruded away from the viewer: {before:?}"); let path = h.dir.join("flipped-sketch.solidcraft"); @@ -81,7 +81,7 @@ fn a_construction_plane_seen_from_below_gets_a_sketch_facing_down() { h.step(&json!({"key":"L"})).unwrap(); h.settle(); let sketch = h.app.session.active_sketch.expect("a sketch on P"); - let plane = h.app.session.world_state().sketch(sketch).map(|s| s.plane).unwrap(); + let plane = h.app.session.world_state().unwrap().sketch(sketch).map(|s| s.plane).unwrap(); assert!(plane.normal().z < -0.999 && (plane.origin.z - 5.0).abs() < 1e-9, "{plane:?}"); assert!(h.app.cam.eye().z < 5.0, "the view stays below the plane"); } diff --git a/crates/ui-egui/src/sketch_text.rs b/crates/ui-egui/src/sketch_text.rs index 40f459fa7..a738aa830 100644 --- a/crates/ui-egui/src/sketch_text.rs +++ b/crates/ui-egui/src/sketch_text.rs @@ -80,7 +80,7 @@ const PLACEHOLDER: &str = "Text"; /// Resolve an outline or filled letter only when all its boundaries belong to one text. pub(crate) fn entity_for_selection(app: &SolveApp, selection: &Sel) -> Option { let sid = app.session.active_sketch?; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let ss = state.sketch(sid)?; let ids = match selection { Sel::SketchCurve { id, .. } => vec![id.clone()], @@ -126,7 +126,7 @@ pub(crate) fn one_letter() -> bool { /// letter is picked whole. The letters' counters (the inside of an O) are left out; inside one, /// a letter is a letter again. The picked profile comes first when it is a letter. pub(crate) fn text_profiles(s: &solidcraft_engine::Session, sketch: u64, index: usize) -> Option> { - let state = s.world_state(); + let state = crate::open_meshing::session_world(s); let ss = state.sketch(sketch)?; // The text bounding a profile, with or without other curves; whether only it bounds it. let text_of = |profile: &solidcraft_engine::sketch::Profile| -> Option<(String, bool)> { @@ -701,7 +701,7 @@ mod tests { h.app.cam.distance = 25.0; h.frames(3); let sid = h.app.session.active_sketch.unwrap(); - let at = h.app.session.world_state().sketch(sid).unwrap().profiles[0].centroid; + let at = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles[0].centroid; let [x, y] = h.at(&json!({"sketch":[at.x,at.y]})).unwrap(); h.call("ui.menu", json!({"x":x,"y":y})); h.frames(3); @@ -736,7 +736,7 @@ mod tests { }; let before = outline(&h); assert!(before.len() > 4 && before.iter().all(|(_, l)| l.as_deref() == Some(link.as_str()))); - let profiles = h.app.session.world_state().sketch(sid).unwrap().profiles.len(); + let profiles = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles.len(); h.app.session.selection = vec![Sel::SketchCurve { id: before[0].0.clone(), sketch: None }]; let undo = h.app.session.undo.len(); let item = crate::context_menu::items(&h.app, &crate::context_menu::Target::Viewport) @@ -751,7 +751,7 @@ mod tests { assert!(after.iter().all(|(_, l)| l.is_none()), "no outline belongs to the text"); let sk = h.app.session.doc.sketch(sid).unwrap(); assert!(sk.link(&link).is_none(), "the text is gone"); - assert_eq!(h.app.session.world_state().sketch(sid).unwrap().profiles.len(), profiles, "the letters still make the same profiles"); + assert_eq!(h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles.len(), profiles, "the letters still make the same profiles"); assert_eq!(h.app.session.undo.len(), undo + 1); // No longer text: nothing to edit or explode. assert!(selected_entity(&h.app).is_none()); @@ -768,7 +768,7 @@ mod tests { h.app.cam.distance = 25.0; h.frames(3); let sid = h.app.session.active_sketch.unwrap(); - let at = h.app.session.world_state().sketch(sid).unwrap().profiles[0].centroid; + let at = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles[0].centroid; h.step(&json!({"start":"sketch.edit_text"})).unwrap(); h.step(&json!({"click":{"sketch":[at.x,at.y]}})).unwrap(); assert_eq!(tx(&h.app).link, link); @@ -779,12 +779,12 @@ mod tests { let (mut h, link, _) = setup(); h.app.run("sketch.edit_text", json!({"link":link,"text":"O"})).unwrap(); let sid = h.app.session.active_sketch.unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let profile = state.sketch(sid).unwrap().profiles.iter().position(|p| !p.hole_curves.is_empty()).unwrap(); let selection = Sel::Profile { sketch: sid, index: profile }; assert!(entity_for_selection(&h.app, &selection).is_some()); h.app.run("sketch.text", json!({"text":"I","at":[20,0],"height":10})).unwrap(); - let profiles = h.app.session.world_state().sketch(sid).unwrap().profiles.len(); + let profiles = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles.len(); h.app.session.selection = (0..profiles).map(|index| Sel::Profile { sketch: sid, index }).collect(); assert!(selected_entity(&h.app).is_none()); assert!(entity_for_selection(&h.app, &Sel::Profile { sketch: sid + 1, index: 0 }).is_none()); @@ -795,7 +795,7 @@ mod tests { let (mut h, _, _) = setup(); h.app.run("sketch.line", json!({"points":[[-10,3],[10,3]]})).unwrap(); let sid = h.app.session.active_sketch.unwrap(); - let count = h.app.session.world_state().sketch(sid).unwrap().profiles.len(); + let count = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles.len(); assert!(count >= 2); for index in 0..count { assert!(entity_for_selection(&h.app, &Sel::Profile { sketch: sid, index }).is_none()); @@ -848,7 +848,7 @@ mod tests { exprs: Default::default(), }; assert_eq!(sk.link(&link).unwrap().source, expected); - assert!(!h.app.session.world_state().sketch(sid).unwrap().profiles.is_empty()); + assert!(!h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles.is_empty()); let changed = h.app.session.doc.to_json(); let reopened = solidcraft_engine::Session::new(solidcraft_engine::doc::Document::from_json(&changed).unwrap()); assert_eq!(reopened.doc.sketch(sid).unwrap().link(&link).unwrap().source, expected); @@ -909,7 +909,7 @@ mod tests { }; let area = |h: &Harness| -> f64 { let sid = h.app.session.active_sketch.unwrap(); - h.app.session.world_state().sketch(sid).unwrap().profiles.iter().map(|p| p.area).sum() + h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles.iter().map(|p| p.area).sum() }; assert!((area(&h) - 13.5557).abs() < 2e-3); h.app.start("sketch.edit_text"); @@ -1295,7 +1295,7 @@ mod tests { h.app.cam.distance = 60.0; h.frames(3); let sid = h.app.session.active_sketch.unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let profiles = &state.sketch(sid).unwrap().profiles; assert_eq!(profiles.len(), 3); let sorted = |v: &[String]| { @@ -1331,15 +1331,15 @@ mod tests { fn a_text_crossed_by_an_edge_is_picked_whole() { let (mut h, sid, i, _, _) = letters(); let area = |h: &Harness, picked: &[usize]| { - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let profiles = &state.sketch(sid).unwrap().profiles; picked.iter().map(|&k| profiles[k].region.area()).sum::() }; let whole = area(&h, &text_profiles(&h.app.session, sid, i).unwrap()); // The I's stem, below where the rectangle's top will cross it. - let stem = solidcraft_engine::geom::Vec2::new(h.app.session.world_state().sketch(sid).unwrap().profiles[i].centroid.x, 2.0); + let stem = solidcraft_engine::geom::Vec2::new(h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles[i].centroid.x, 2.0); h.app.run("sketch.rectangle.two_point", json!({"p0":[-5,-5],"p1":[40,8]})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let profiles = &state.sketch(sid).unwrap().profiles; let below = solidcraft_engine::sketch::profile_at_point(profiles, stem).unwrap(); let picked = text_profiles(&h.app.session, sid, below).unwrap(); @@ -1353,7 +1353,7 @@ mod tests { #[test] fn clicking_a_letter_selects_the_whole_text_for_an_extrude() { let (mut h, sid, i, ring, _) = letters(); - let at = h.app.session.world_state().sketch(sid).unwrap().profiles[i].centroid; + let at = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles[i].centroid; h.step(&json!({"click":{"sketch":[at.x,at.y]}})).unwrap(); h.frames(2); let has = |sel: &[Sel], index: usize| sel.iter().any(|s| matches!(s, Sel::Profile { sketch, index: x } if *sketch == sid && *x == index)); @@ -1381,7 +1381,7 @@ mod tests { #[test] fn shift_clicking_a_letter_selects_that_letter_alone() { let (mut h, sid, i, ring, _) = letters(); - let at = h.app.session.world_state().sketch(sid).unwrap().profiles[i].centroid; + let at = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles[i].centroid; h.step(&json!({"click":{"sketch":[at.x,at.y]},"shift":true})).unwrap(); h.frames(2); assert_eq!(h.app.session.selection, vec![Sel::Profile { sketch: sid, index: i }]); @@ -1480,7 +1480,7 @@ mod tests { h.frames(3); assert_eq!(tx(&h.app).style.path.as_deref(), Some(line.as_str())); assert_eq!(style_of(&h, &link).path.as_deref(), Some(line.as_str())); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(sid).unwrap().sketch; let low = sk.link_curves(&link).into_iter().flat_map(|ci| sk.polyline(ci)).map(|p| p.y).fold(f64::MAX, f64::min); assert!((low + 30.0).abs() < 1e-6, "on the line: {low}"); diff --git a/crates/ui-egui/src/sketch_text_handles.rs b/crates/ui-egui/src/sketch_text_handles.rs index 9ee81b438..d958248a0 100644 --- a/crates/ui-egui/src/sketch_text_handles.rs +++ b/crates/ui-egui/src/sketch_text_handles.rs @@ -102,7 +102,7 @@ fn target(app: &SolveApp) -> Option { /// The frame of text `link` in the active sketch, as shown (solved). fn frame(app: &SolveApp, link: &str) -> Option { let sid = app.session.active_sketch?; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let sk = &state.sketch(sid)?.sketch; let source = sk.link(link).filter(|l| l.kind == LinkKind::Text)?; let LinkSource::Text { at, height, angle, style, .. } = &source.source else { return None }; @@ -147,7 +147,7 @@ struct Screen { fn screen(app: &SolveApp, proj: &Proj, f: &Frame) -> Option { let sid = app.session.active_sketch?; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let plane = state.sketch(sid)?.plane; let to_screen = |local: Vec2| proj.to_screen(plane.to_world(f.to_sketch(local))); let [a, b, c, d] = f.corners(); @@ -178,7 +178,7 @@ pub(crate) fn over(app: &SolveApp, proj: &Proj, pos: Pos2) -> bool { /// Where the pointer is on the active sketch's plane. fn on_plane(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option { - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let ss = state.sketch(app.session.active_sketch?)?; let (o, d) = proj.ray(pos); ss.plane.intersect_ray(o, d).map(|w| ss.plane.to_local(w)) @@ -409,7 +409,7 @@ mod tests { h.app.session.selection.clear(); h.frames(2); let sid = h.app.session.active_sketch.unwrap(); - let inside = h.app.session.world_state().sketch(sid).unwrap().profiles[0].centroid; + let inside = h.app.session.world_state().unwrap().sketch(sid).unwrap().profiles[0].centroid; h.step(&json!({"click":{"sketch":[inside.x,inside.y]},"double":true})).unwrap(); h.frames(2); match h.app.dialog.as_ref().map(|d| &d.kind) { diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index ecc73632c..be8a8d594 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -97,7 +97,7 @@ const TRIM_STEP_PX: f32 = 4.0; /// The sketch-plane position under screen position `pos`. fn on_sketch_plane(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let ss = st.sketch(active_sketch(app)?)?; let (o, d) = proj.ray(pos); ss.plane.intersect_ray(o, d).map(|w| ss.plane.to_local(w)) @@ -725,7 +725,7 @@ pub(crate) fn corner_curves(sk: &solidcraft_engine::sketch::Sketch, pi: usize, a /// Corner tools accept endpoints shared by two editable curves. Pick among those endpoints /// directly so the origin, a circle centre or an overlapping loose point cannot hide a corner. pub(crate) fn corner_point(app: &SolveApp, proj: &Proj, pos: Pos2, arcs_ok: bool) -> Option<(Vec2, String)> { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let ss = st.sketch(active_sketch(app)?)?; let sk = &ss.sketch; sk.points @@ -756,7 +756,7 @@ fn arg(p: &(Vec2, Option)) -> Value { /// Length of a curve (for default sizes). fn curve_len(app: &SolveApp, id: &str) -> f64 { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = active_sketch(app).and_then(|s| st.sketch(s)) else { return 10.0 }; ss.sketch.curve_index(id).map(|c| ss.sketch.polyline(c).windows(2).map(|w| w[0].dist(w[1])).sum::()).unwrap_or(10.0) } @@ -797,7 +797,7 @@ pub fn periodic_start_snap(app: &SolveApp, tool: &Tool, proj: &Proj, pos: Pos2) if distinct.len() < 3 { return None; } - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let plane = &state.sketch(app.session.active_sketch?)?.plane; let screen = proj.to_screen(plane.to_world(first))?; (screen.distance(pos) <= 8.0).then_some(first) @@ -874,7 +874,7 @@ pub fn on_click(app: &mut SolveApp, tool: &mut Tool, proj: &Proj, pos: Pos2) { }); // Empty space while sketching: the sketch plane. let target = target.or_else(|| { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let ss = st.sketch(app.session.active_sketch?)?; let (o, d) = proj.ray(pos); let w = ss.plane.intersect_ray(o, d)?; @@ -1146,7 +1146,7 @@ pub(crate) fn trim_hover_piece(app: &SolveApp, sketch: u64, id: &str) -> Option< if let Some(piece) = TRIM_PIECE.with(|c| c.borrow().as_ref().filter(|(k, _)| *k == key).map(|(_, p)| p.clone())) { return piece; } - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let piece = solidcraft_engine::cmd::trim_piece(&st.sketch(sketch)?.sketch, id, *at); TRIM_PIECE.with(|c| *c.borrow_mut() = Some((key, piece.clone()))); piece @@ -1180,7 +1180,7 @@ fn extend_preview_piece(app: &SolveApp, sketch: u64, id: &str) -> Option) { let Some(sid) = active_sketch(app) else { return }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = st.sketch(sid) else { return }; if ss.sketch.view.hide_constraints { GLYPHS.with(|g| g.borrow_mut().clear()); @@ -1492,7 +1492,7 @@ fn snap_hint(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { return; } let Some((label, p)) = SNAP.with(|s| *s.borrow()) else { return }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = active_sketch(app).and_then(|s| st.sketch(s)) else { return }; let Some(sp) = proj.to_screen(ss.plane.to_world(p)) else { return }; let tk = crate::theme::Tokens::get(); diff --git a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs index a0a56c02a..347f2fa22 100644 --- a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs +++ b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs @@ -117,7 +117,7 @@ fn run(h: &mut Harness, id: &str, p: Value) -> Value { fn sketch(h: &Harness) -> solidcraft_engine::sketch::Sketch { let sid = h.app.session.active_sketch.expect("sketch mode"); - h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone() + h.app.session.world_state().unwrap().sketch(sid).expect("the sketch").sketch.clone() } fn screen(h: &mut Harness, x: f64, y: f64) -> egui::Pos2 { diff --git a/crates/ui-egui/src/sketch_typed_intent_tests.rs b/crates/ui-egui/src/sketch_typed_intent_tests.rs index ca21bfe47..e141d68df 100644 --- a/crates/ui-egui/src/sketch_typed_intent_tests.rs +++ b/crates/ui-egui/src/sketch_typed_intent_tests.rs @@ -19,7 +19,17 @@ fn enter(h: &mut Harness) { h.step(&json!({"key":"Enter"})).unwrap(); } fn constraints(h: &Harness) -> Vec { - h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.constraints.iter().map(|c| c.kind.clone()).collect() + h.app + .session + .world_state() + .unwrap() + .sketch(h.app.session.active_sketch.unwrap()) + .unwrap() + .sketch + .constraints + .iter() + .map(|c| c.kind.clone()) + .collect() } #[test] @@ -42,7 +52,7 @@ fn typed_arc_radius_and_signed_sweep_survive_stages_parameter_edit_and_reopen() let path = h.dir.join("typed-arc.solidcraft"); h.app.run("file.save", json!({"path":path})).unwrap(); h.app.run("doc.open", json!({"path":path})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketches[0].sketch; let curve = &sketch.curves[0]; assert!(curve.reversed, "negative typed sweep must remain clockwise"); @@ -181,7 +191,7 @@ fn polygon_radius_is_persistent_and_fractional_sides_are_rejected() { type_value(&mut h, "5"); enter(&mut h); assert!(constraints(&h).iter().any(|c| matches!(c,ConstraintKind::Radius{value,..} if (*value-10.0).abs()<1e-7))); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert_eq!(sketch.curves.iter().filter(|c| !c.construction).count(), 5); } @@ -199,7 +209,7 @@ fn line_angle_survives_drag_and_one_undo_removes_geometry_and_dimensions() { h.step(&json!({"key":"Escape"})).unwrap(); h.step(&json!({"key":"Escape"})).unwrap(); h.step(&json!({"drag":[{"world":[8.660254037844386,5,0]},{"world":[16,14,0]}]})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let CurveKind::Line { a, b } = sketch.curves[0].kind else { panic!("expected line") }; let vector = sketch.points[b].pos - sketch.points[a].pos; @@ -211,7 +221,7 @@ fn line_angle_survives_drag_and_one_undo_removes_geometry_and_dimensions() { } h.app.run("edit.undo", json!({})).unwrap(); assert!(constraints(&h).is_empty()); - assert!(h.app.session.world_state().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.is_empty()); + assert!(h.app.session.world_state().unwrap().sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.is_empty()); } #[test] @@ -226,12 +236,12 @@ fn typed_drawing_preserves_construction_and_centerline_modes_at_undo_limit() { type_value(&mut h, "30 deg"); enter(&mut h); assert_eq!(h.app.session.undo.len(), 200); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert_eq!(sketch.curves[0].construction, mode == 1); assert_eq!(sketch.curves[0].centerline, mode == 2); h.app.run("edit.undo", json!({})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!(sketch.curves.is_empty()); assert!(sketch.constraints.is_empty()); @@ -270,7 +280,7 @@ fn the_arc_end_pick_snaps_to_a_point_under_the_value_box() { if command != "sketch.arc.center_point" { continue; } - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; let line_end = sketch.curves.iter().find(|c| c.id == "l1").and_then(|c| match c.kind { CurveKind::Line { b, .. } => Some(b), diff --git a/crates/ui-egui/src/smart_extrude_ui_tests.rs b/crates/ui-egui/src/smart_extrude_ui_tests.rs index aa15dbb94..1ec2d3679 100644 --- a/crates/ui-egui/src/smart_extrude_ui_tests.rs +++ b/crates/ui-egui/src/smart_extrude_ui_tests.rs @@ -16,13 +16,13 @@ fn state(h: &Harness) -> (usize, usize, bool) { } fn bounds_z(h: &Harness) -> (f64, f64) { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let b = st.bodies.last().expect("a body").mesh().bounds(); (b.min.z, b.max.z) } fn volume(h: &Harness) -> f64 { - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); st.bodies.iter().map(|b| solidcraft_engine::doc::kernel::measure(&b.body).unwrap().volume).sum() } diff --git a/crates/ui-egui/src/stand_up.rs b/crates/ui-egui/src/stand_up.rs index d00b02f46..ac6f5034a 100644 --- a/crates/ui-egui/src/stand_up.rs +++ b/crates/ui-egui/src/stand_up.rs @@ -25,7 +25,8 @@ pub fn offer(app: &mut SolveApp, path: &str, before: &[String], result: Option<& if text("system") == Some("SolidCraft") || text("exporter_up") == Some("z") { return; } - let bodies: Vec = app.session.world_state().bodies.iter().map(|b| b.name.clone()).filter(|n| !before.contains(n)).collect(); + let bodies: Vec = + crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).filter(|n| !before.contains(n)).collect(); if bodies.is_empty() { return; } diff --git a/crates/ui-egui/src/thin_extrude_tests.rs b/crates/ui-egui/src/thin_extrude_tests.rs index df47c9dde..6ff9bb952 100644 --- a/crates/ui-egui/src/thin_extrude_tests.rs +++ b/crates/ui-egui/src/thin_extrude_tests.rs @@ -13,7 +13,7 @@ fn rectangle(h: &mut Harness) -> u64 { } fn volume(h: &Harness) -> f64 { - h.app.session.world_state().bodies.iter().map(|b| solidcraft_engine::doc::kernel::measure(&b.body).unwrap().volume).sum() + h.app.session.world_state().unwrap().bodies.iter().map(|b| solidcraft_engine::doc::kernel::measure(&b.body).unwrap().volume).sum() } #[test] diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 4fa7dda6b..5f19e3ef7 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -498,7 +498,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { // Find in Timeline: scroll the found feature into the strip on this frame (#5850). let reveal = app.tree.timeline_reveal.take(); // The feature whose body is under the cursor in the viewport. - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let from_view = match &app.viewport.hover { Some( crate::viewport::Hit::Face { body, .. } | crate::viewport::Hit::Edge { body, .. } | crate::viewport::Hit::Vertex { body, .. }, @@ -711,7 +711,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { /// Select what a feature made, so the browser shows it. fn find_in_browser(app: &mut SolveApp, id: u64) { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let bodies: Vec = st.bodies.iter().filter(|b| b.feature == id).map(|b| json!({"type": "body", "name": b.name})).collect(); let items = if bodies.is_empty() { vec![json!({"type": "feature", "id": id})] } else { bodies }; let _ = app.run("select.set", json!({ "items": items })); diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index c3f7403b8..99660247e 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -1032,7 +1032,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { .collect(); let from_view = match &app.viewport.hover { Some(crate::viewport::Hit::Face { body, .. } | crate::viewport::Hit::Edge { body, .. } | crate::viewport::Hit::Vertex { body, .. }) => { - app.session.world_state().body(body).map(|body| body.feature) + crate::open_meshing::session_world(&app.session).body(body).map(|body| body.feature) } _ => None, }; diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 4e2af4da2..5e5ef6ae9 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -180,7 +180,7 @@ fn xy(p: &(Vec2, Option)) -> Value { /// Shift exposes a line midpoint as a point target, only in the alignment tool. fn midpoint_at(app: &SolveApp, proj: &Proj, pos: Pos2, radius: f32) -> Option<(Vec2, String)> { let sid = app.session.active_sketch?; - let state = app.session.world_state(); + let state = crate::open_meshing::session_world(&app.session); let ss = state.sketch(sid)?; pick(app, proj, pos).into_iter().find_map(|hit| { let Hit::SketchCurve { sketch, id, straight: true, .. } = hit else { return None }; @@ -683,7 +683,7 @@ fn sketch_axis_of(app: &SolveApp, name: &str) -> Option<&'static str> { "Z" => Vec3::Z, _ => return None, }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let plane = st.sketch(app.session.active_sketch?)?.plane; let o = plane.origin; if (o - dir * o.dot(dir)).len() > 1e-6 { @@ -1036,7 +1036,7 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) { return crate::sketch_tools::preview(app, t, painter, proj); } let Some(sid) = app.session.active_sketch else { return }; - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let Some(ss) = st.sketch(sid) else { return }; let to = |p: Vec2| proj.to_screen(ss.plane.to_world(p)); // Drawn straight onto the view: its side's colours (#4146). diff --git a/crates/ui-egui/src/view_home_tests.rs b/crates/ui-egui/src/view_home_tests.rs index 685d59217..bc2ea6647 100644 --- a/crates/ui-egui/src/view_home_tests.rs +++ b/crates/ui-egui/src/view_home_tests.rs @@ -11,7 +11,7 @@ fn moved_block(h: &mut Harness) { h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})).unwrap(); h.app.run("sketch.finish", json!({})).unwrap(); h.app.run("solid.extrude", json!({"distance": 5})).unwrap(); - let body = h.app.session.world_state().bodies[0].name.clone(); + let body = h.app.session.world_state().unwrap().bodies[0].name.clone(); h.app.run("solid.move", json!({"bodies": [body], "translate": [500, 0, 0]})).unwrap(); h.app.preferences.look_at_anim = false; h.settle(); @@ -124,7 +124,7 @@ fn middle_double_click_preference_fit_or_off() { assert_eq!((h.app.cam.yaw, h.app.cam.pitch), (yaw, pitch), "Fit keeps the orientation"); assert!(h.app.cam.target.dist(Vec3::new(505.0, 5.0, 2.5)) < 5.0, "{:?}", h.app.cam.target); // Fit frames everything shown, not the selection. - let body = h.app.session.world_state().bodies[0].name.clone(); + let body = h.app.session.world_state().unwrap().bodies[0].name.clone(); h.app.run("select.set", json!({"items": [{"type": "body", "name": body}]})).unwrap(); let fitted = h.app.cam; h.app.cam.pan(60.0, 0.0, 500.0); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4ed29e673..993c860d5 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -390,7 +390,7 @@ pub(crate) fn in_view_centre(app: &SolveApp, proj: &Proj) -> Option { let b = body_bounds(app, &st) .iter() .filter(|(name, b)| !b.is_empty() && app.session.body_visible(name) && in_view(proj, b)) - .fold(solidcraft_engine::geom::Aabb3::EMPTY, |a, (_, b)| a.union(b)); + .fold(solidcraft_engine::geom::Aabb3::EMPTY, |a, (_, b)| a.union(b)).unwrap_or(solidcraft_engine::geom::Aabb3::EMPTY); (!b.is_empty()).then(|| b.center()) } @@ -1444,7 +1444,8 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { let s = &app.session; let st = crate::open_meshing::shown_world(app); let mut fill_budget = 131_072; - let sketch_plane = solidcraft_engine::view::open_sketch_plane(s); + // The open sketch's plane in the model this frame shows. + let sketch_plane = s.active_sketch.and_then(|id| st.sketch(id)).map(|ss| ss.plane); if sketch_plane.is_some() || (app.ui.show_grid && !active_view(app).hide_grid) { let (minor, major) = grid_step(app.cam.half_height()); // An open sketch always has its grid on its own plane; otherwise the ground plane: XY with @@ -2570,6 +2571,15 @@ fn analysis_uniform(app: &SolveApp) -> [f32; 8] { /// While Draft, Accessibility or Curvature Map analysis is on, what each of its colours means and /// the values it stands for, at the bottom left of the viewport (#973). The colours alone don't /// say, and with colour vision loss they can be hard to tell apart. +/// Why the model cannot be placed, across the bottom of the viewport, while it cannot: the +/// viewport then shows no placed bodies (see `open_meshing::session_world`). +fn placement_note(app: &SolveApp, painter: &egui::Painter, rect: Rect) { + let Some(why) = crate::open_meshing::placement_error(&app.session) else { return }; + let t = Tokens::get(); + let text = format!("The model cannot be placed: {why}"); + painter.text(pos2(rect.center().x, rect.bottom() - 24.0), Align2::CENTER_BOTTOM, text, FontId::proportional(t.font_button), t.error); +} + fn analysis_legend(app: &SolveApp, painter: &egui::Painter, rect: Rect) { use solidcraft_engine::SurfaceAnalysis as A; let t = Tokens::get(); @@ -3857,7 +3867,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); } let overlay_rect = crate::shell::bottom_overlay_rect(app, rect); - analysis_legend(app, &painter, overlay_rect); + analysis_legend(app, &painter, rect); + placement_note(app, &painter, overlay_rect); crate::frame_rate::paint(app, ui, &painter, overlay_rect); // ---- interaction ---- @@ -4724,7 +4735,7 @@ fn dragged_with(app: &SolveApp, id: &str) -> Vec { let rest: Vec = selected().filter(|s| *s != id).map(str::to_owned).collect(); // A curve's own points, selected with it by a window, are not a group: a circle grabbed on // its edge still takes its radius from the drag. - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let own: Vec<&str> = app .session .active_sketch @@ -4756,7 +4767,7 @@ pub(crate) fn picked_selection(s: &solidcraft_engine::Session, sel: &Sel) -> Vec /// Expand a visible rim or surface into the kernel pieces a command needs. The original /// face pick keeps its point (used by tools such as Hole and construction geometry). pub(crate) fn grouped_selection(s: &solidcraft_engine::Session, sel: &Sel) -> Vec { - let st = s.world_state(); + let st = crate::open_meshing::session_world(s); match sel { Sel::Edge { body, index, .. } => { if let Some(b) = st.body(body) { @@ -5126,7 +5137,7 @@ fn midpoint_marker(painter: &egui::Painter, at: Pos2, color: Color32) { /// drawn too (#3267). Not the sketch's origin, projected points, or a sketch's points while it /// hides them. pub(crate) fn standalone_points(app: &SolveApp) -> Vec { - let st = app.session.world_state(); + let st = crate::open_meshing::session_world(&app.session); let mut out = Vec::new(); for sid in visible_sketches(app) { if app.session.active_sketch == Some(sid) { @@ -6211,7 +6222,7 @@ mod tests { app.fit_view(); const SIZE: u32 = 256; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); - let body = app.session.world_state().bodies[0].clone(); + let body = app.session.world_state().unwrap().bodies[0].clone(); let faces = body.body.face_count(); let mut render = |tess: bool, hover: Option| { app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false }); @@ -6511,7 +6522,7 @@ mod tests { } let mut h = crate::scenario::Harness::new(); h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap(); - h.app.cam = solidcraft_engine::view::home_camera(&h.app.session); + h.app.cam = solidcraft_engine::view::home_camera(&h.app.session).unwrap(); for dark in [false, true, false] { h.app.ui.dark = dark; let img = crate::control::view_rgba(&h.app, 160, 120).unwrap(); @@ -6583,7 +6594,7 @@ mod tests { } let mut h = crate::scenario::Harness::new(); h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); - let cam = solidcraft_engine::view::home_camera(&h.app.session); + let cam = solidcraft_engine::view::home_camera(&h.app.session).unwrap(); let whole = pixels(&mut h, cam); let before = h.app.session.doc.clone(); let undo = h.app.session.undo.len(); @@ -6623,7 +6634,7 @@ mod tests { let geometry = feature_geometry(&h.app, id); assert_eq!(geometry.len(), 1, "{command}: {geometry:?}"); let Sel::Face { body, index, .. } = &geometry[0] else { panic!("a modifier must highlight its face") }; - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let m = st.body(body).unwrap().mesh(); let triangles = m.tri_face.iter().filter(|f| **f as usize == *index).count(); assert!(triangles > 0 && triangles < m.triangles.len()); @@ -7383,7 +7394,7 @@ mod tests { app.cam.distance = 500.0; hover_frame(&mut app, &ctx, vec![]); let proj = projection(&app, app.viewport.rect.unwrap()); - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let m = st.body("Body1").unwrap().mesh(); let mut checked = 0; for (ei, e) in m.edges.iter().enumerate() { @@ -8076,7 +8087,7 @@ mod tests { for tess in [true, false] { let mut app = cylinder_app(); app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false }); - let body = app.session.world_state().bodies[0].clone(); + let body = app.session.world_state().unwrap().bodies[0].clone(); let before = build_scene(&app).merged(); let key = scene_key(&app); assert!(app.viewport.lod.lock().unwrap().force(&body, current(), 2)); @@ -8192,7 +8203,7 @@ mod tests { #[test] fn whole_body_highlight_preserves_each_triangle_and_selected_face_once() { let mut app = cylinder_app(); - let body = app.session.world_state().bodies[0].clone(); + let body = app.session.world_state().unwrap().bodies[0].clone(); let expected = shown_mesh(&app, &body, &None).triangles.len() * 3 * crate::gpu::TRI_SIZE; app.viewport.hover_bodies = vec![body.name.clone()]; for selected in @@ -8357,7 +8368,7 @@ mod tests { .unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); app.ui.ground_shadow = false; - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let b = st.bodies.first().unwrap(); let mesh = b.mesh(); assert_eq!(mesh.edges.len(), 1536); @@ -8380,14 +8391,14 @@ mod tests { let mut without_display_mask = (*mesh).clone(); without_display_mask.smooth_edges.clear(); assert_eq!(mesh.surface_patch(mesh.edge_faces[smooth][0] as usize), without_display_mask.surface_patch(mesh.edge_faces[smooth][0] as usize)); - let cam = solidcraft_engine::view::home_camera(&app.session); - let cpu = solidcraft_engine::view::scene(&app.session, &cam); + let cam = solidcraft_engine::view::home_camera(&app.session).unwrap(); + let cpu = solidcraft_engine::view::scene(&app.session, &cam).unwrap(); let actual_edges = cpu.lines.iter().filter(|line| line.color == solidcraft_engine::view::colors::EDGE).count(); assert_eq!(actual_edges, mesh.edges.iter().enumerate().filter(|(i, _)| mesh.shaded_edge_visible(*i)).count()); if let Ok(directory) = solidcraft_engine::geom::env::var("SMOOTH_SCREENSHOTS").ok_or(()) { std::fs::create_dir_all(&directory).unwrap(); for (name, old_edges, wireframe) in [("after", false, false), ("before", true, false), ("wireframe", true, true)] { - let mut scene = solidcraft_engine::view::scene(&app.session, &cam); + let mut scene = solidcraft_engine::view::scene(&app.session, &cam).unwrap(); scene.lines.retain(|line| line.color == solidcraft_engine::view::colors::EDGE); if old_edges { scene.lines.clear(); @@ -8435,7 +8446,7 @@ mod tests { } s.execute("solid.extrude", &json!({"sketch":sketch,"distance":3})).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let body = st.bodies.first().unwrap(); let mesh = body.mesh(); let crease = mesh @@ -8466,7 +8477,7 @@ mod tests { #[test] fn circular_items_measure_as_whole_rims_and_surfaces() { let mut app = cylinder_app(); - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); let edges: Vec = m @@ -8547,7 +8558,7 @@ mod tests { #[test] fn circular_rim_hover_click_and_dialog_pick_include_both_halves() { let mut app = cylinder_app(); - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); let top = m.edges.iter().position(|e| e.len() > 3 && e.iter().all(|p| (p.z - 20.0).abs() < 1e-6)).unwrap(); @@ -8594,7 +8605,7 @@ mod tests { #[test] fn curved_face_hover_selection_and_dialogs_cross_the_seam() { let mut app = cylinder_app(); - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let b = &st.bodies[0]; let m = b.mesh(); let faces = m.edge_faces.iter().zip(&m.seams).find(|(_, seam)| **seam).unwrap().0; @@ -8627,7 +8638,7 @@ mod tests { let cap = (0..b.body.face_count()).find(|&i| m.surface_patch(i).len() == 1).unwrap(); assert_eq!(m.surface_patch(cap), vec![cap]); app.session.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); - let st = app.session.world_state(); + let st = app.session.world_state().unwrap(); let box_body = st.bodies.last().unwrap(); for i in 0..box_body.body.face_count() { assert_eq!(box_body.mesh().surface_patch(i), vec![i]); @@ -9808,7 +9819,7 @@ mod tests { h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); let made = h.app.run("sketch.line", json!({"points": [[-30, -20], [30, 20]]})).unwrap(); h.app.run("sketch.constraint.fix", json!({"entity": made["created"]["curves"][0]})).unwrap(); - let mut cam = solidcraft_engine::view::home_camera(&h.app.session); + let mut cam = solidcraft_engine::view::home_camera(&h.app.session).unwrap(); cam.set_view(solidcraft_engine::render::StandardView::Top); h.app.cam = cam; let count = |h: &crate::scenario::Harness, c: Color32| { diff --git a/crates/ui-egui/src/viewport_appearance_tests.rs b/crates/ui-egui/src/viewport_appearance_tests.rs index ab9d180a7..16fcdfccf 100644 --- a/crates/ui-egui/src/viewport_appearance_tests.rs +++ b/crates/ui-egui/src/viewport_appearance_tests.rs @@ -99,7 +99,7 @@ fn placed_step_body_uses_imported_opacity_until_a_design_look_overrides_it() { let mut app = SolveApp::new(session, Services::default()); app.ui.ground_shadow = false; app.set_origin_shown(false); - let placed = app.session.world_state().bodies.iter().find(|b| b.name != source).unwrap().name.clone(); + let placed = app.session.world_state().unwrap().bodies.iter().find(|b| b.name != source).unwrap().name.clone(); app.session.selection = vec![solidcraft_engine::Sel::Body { name: placed }]; app.start("appearance.assign"); let crate::dialogs::Kind::Appearance(appearance) = &app.dialog.as_ref().unwrap().kind else { panic!("appearance dialog") }; @@ -112,7 +112,7 @@ fn placed_step_body_uses_imported_opacity_until_a_design_look_overrides_it() { scene.tris.is_empty(), "opaque triangles {}, bodies {:?}", scene.tris.len(), - app.session.world_state().bodies.iter().map(|b| (&b.name, b.body.paint(), &b.imported)).collect::>() + app.session.world_state().unwrap().bodies.iter().map(|b| (&b.name, b.body.paint(), &b.imported)).collect::>() ); let (vertices, remainder) = scene.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>(); assert!(remainder.is_empty()); diff --git a/crates/ui-egui/src/viewport_plane_target_tests.rs b/crates/ui-egui/src/viewport_plane_target_tests.rs index 72344c3b4..1ffe78dab 100644 --- a/crates/ui-egui/src/viewport_plane_target_tests.rs +++ b/crates/ui-egui/src/viewport_plane_target_tests.rs @@ -13,7 +13,7 @@ fn clicking_an_origin_plane_target_sketches_on_that_plane() { h.app.cam.pitch = pitch; h.step(&json!({"start":"sketch.create"})).unwrap(); h.step(&json!({"click":{"plane":plane}})).unwrap(); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let n = state.sketches.first().map(|s| s.plane.normal()).unwrap_or_default(); let along = (n.x * normal[0] + n.y * normal[1] + n.z * normal[2]).abs(); assert!(along > 0.999, "yaw {yaw} pitch {pitch} {plane}: sketched on a plane with normal {n:?}"); diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index e8ae6cdaa..9c8180c6b 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -1036,16 +1036,16 @@ mod tests { h.frames(3); let links = h.app.session.execute("component.links", &json!({})).unwrap(); assert_eq!(links["links"][0]["name"], "part1", "{links}"); - assert_eq!(h.app.session.world_state().bodies.len(), 1); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1); h.step(&json!({"choose_file": "part2.step"})).unwrap(); h.step(&json!({"start": "component.insert_design"})).unwrap(); for _ in 0..600 { - if h.app.session.world_state().bodies.len() == 2 { + if h.app.session.world_state().unwrap().bodies.len() == 2 { break; } h.frames(1); } - assert_eq!(h.app.session.world_state().bodies.len(), 2, "the STEP file's body is inserted"); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 2, "the STEP file's body is inserted"); } /// Every way into a sketch (New Sketch on the ribbon then a plane, a double-click in the diff --git a/crates/ui-egui/tests/constraint_preselection.rs b/crates/ui-egui/tests/constraint_preselection.rs index a6daeb2dc..5b8b5eb65 100644 --- a/crates/ui-egui/tests/constraint_preselection.rs +++ b/crates/ui-egui/tests/constraint_preselection.rs @@ -215,7 +215,7 @@ fn curvature_polygon_and_fix_consume_clicked_operands_atomically() { assert!(h.app.tool.is_none()); assert!(h.app.session.selection.is_empty()); assert_eq!(h.app.session.undo.len(), undo + 1); - let st = h.app.session.world_state(); + let st = h.app.session.world_state().unwrap(); let sk = &st.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!(sk.constraints.iter().any(|c| match command { "fix" => matches!(c.kind, ConstraintKind::Fix { .. }), diff --git a/crates/ui-egui/tests/icon_audit.rs b/crates/ui-egui/tests/icon_audit.rs index b05896d18..06ab5783c 100644 --- a/crates/ui-egui/tests/icon_audit.rs +++ b/crates/ui-egui/tests/icon_audit.rs @@ -193,7 +193,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() { h.frames(3); let body = h.app.session.model.state().bodies.first().unwrap().name.clone(); - let sketch = h.app.session.world_state().sketches.first().unwrap().feature; + let sketch = h.app.session.world_state().unwrap().sketches.first().unwrap().feature; for target in [ json!({"type":"viewport"}), json!({"type":"body","name":body}), diff --git a/crates/ui-egui/tests/point_constraint_preselection.rs b/crates/ui-egui/tests/point_constraint_preselection.rs index 7f569260d..b6f7355f0 100644 --- a/crates/ui-egui/tests/point_constraint_preselection.rs +++ b/crates/ui-egui/tests/point_constraint_preselection.rs @@ -36,7 +36,7 @@ fn clicked_point_constraint_preselection_applies_and_undoes_once() { assert!(h.app.tool.is_none()); assert!(h.app.session.selection.is_empty()); assert_eq!(h.app.session.undo.len(), undo + 1); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert!(sk.constraints.iter().any(|c| match command { "coincident" => matches!(c.kind, ConstraintKind::Coincident { .. } | ConstraintKind::PointOnCurve { .. }), diff --git a/crates/ui-egui/tests/projection_preselection.rs b/crates/ui-egui/tests/projection_preselection.rs index 28ffdef42..6a277ef3d 100644 --- a/crates/ui-egui/tests/projection_preselection.rs +++ b/crates/ui-egui/tests/projection_preselection.rs @@ -32,7 +32,7 @@ fn clicked_external_curve_and_point_project_with_source_identity_and_one_undo() assert!(h.app.session.selection.is_empty()); assert!(h.app.tool.is_none()); assert_eq!(h.app.session.undo.len(), undo + 1); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert_eq!(sk.curves.len(), 2); assert!(sk.curves.iter().any(|curve| curve.link.is_some())); @@ -84,7 +84,7 @@ fn axis_and_plane_preselection_projects_as_one_command() { h.step(&json!({"start":"sketch.project"})).unwrap(); assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); assert_eq!(h.app.session.undo.len(), undo + 1); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; assert_eq!(sk.curves.iter().filter(|c| c.link.is_some()).count(), 2); assert!(h.app.session.selection.is_empty()); @@ -104,7 +104,7 @@ fn mixed_local_and_external_selection_keeps_ordinary_project_picking() { assert_eq!(h.app.session.undo.len(), undo); h.step(&json!({"click":{"world":[20,10,10]}})).unwrap(); assert_eq!(h.app.session.undo.len(), undo + 1); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); assert!(state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch.curves.iter().any(|curve| curve.link.is_some())); } @@ -143,7 +143,7 @@ fn a_rectangle_put_onto_a_projected_edge_is_still_a_profile_to_click() { h.call("ui.view", json!({"view":"bottom"})); h.step(&json!({"click":{"sketch":[15,12]}})).unwrap(); assert_eq!(h.app.session.selection, vec![Sel::Profile { sketch, index: 0 }]); - let state = h.app.session.world_state(); + let state = h.app.session.world_state().unwrap(); let ss = state.sketch(sketch).unwrap(); assert_eq!(ss.profiles.len(), 1); let mut bounded_by = ss.profiles[0].outer_curves.clone(); diff --git a/crates/ui-egui/tests/stand_up_offer.rs b/crates/ui-egui/tests/stand_up_offer.rs index e450011eb..3e220210b 100644 --- a/crates/ui-egui/tests/stand_up_offer.rs +++ b/crates/ui-egui/tests/stand_up_offer.rs @@ -29,7 +29,7 @@ fn opened_from(programs: &str, prepare: impl FnOnce(&mut Harness)) -> Harness { } fn height(h: &Harness) -> f64 { - let b = solidcraft_engine::view::bounds(&h.app.session); + let b = solidcraft_engine::view::bounds(&h.app.session).unwrap(); b.max.z - b.min.z }