Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Viewport: bodies stay visible after switching to perspective and back (#5422) (#5614)

raykholoac53fc1e6fab
diff --git a/crates/render/src/camera.rs b/crates/render/src/camera.rs
index 9b1e366438..e2f641cbe8 100644
--- a/crates/render/src/camera.rs
+++ b/crates/render/src/camera.rs
@@ -290,6 +290,37 @@ impl Camera {
(self.distance - r * 4.0 - 1.0, self.distance + r * 4.0 + 1.0)
}
}
+ /// Clip a known scene, retaining the radius-based margin for grids and overlays.
+ /// In perspective the orbit distance is not the nearest geometry's depth: a deep assembly
+ /// can reach almost to the eye. Cap the usual near plane at half that nearest depth so the
+ /// distance-based precision floor cannot clip its front components after a projection change.
+ pub fn clip_bounds(&self, bounds: &Aabb3) -> (f64, f64) {
+ let fallback = self.clip((self.half_height() * 2.0).max(50.0));
+ if bounds.is_empty() || !bounds.min.is_finite() || !bounds.max.is_finite() {
+ return fallback;
+ }
+ let radius = bounds.diagonal() * 0.5 + bounds.center().dist(self.target);
+ if !radius.is_finite() {
+ return fallback;
+ }
+ let (near, far) = self.clip(radius.max(self.half_height() * 2.0).max(10.0));
+ if self.fov <= 0.0 {
+ return (near, far);
+ }
+ let back = self.back();
+ let nearest = Vec3::new(
+ if back.x >= 0.0 { bounds.max.x } else { bounds.min.x },
+ if back.y >= 0.0 { bounds.max.y } else { bounds.min.y },
+ if back.z >= 0.0 { bounds.max.z } else { bounds.min.z },
+ );
+ let depth = self.distance + (self.target - nearest).dot(back);
+ if !depth.is_finite() {
+ return (near, far);
+ }
+ // A box crossing the eye uses the minimum positive near plane; points behind the eye
+ // still cannot be projected. Keep the existing one-micrometre lower limit.
+ (near.min((depth * 0.5).max(1e-3)), far)
+ }
/// Projection to clip space (OpenGL/wgpu style, depth 0..1).
pub fn proj(&self, aspect: f64, near: f64, far: f64) -> Mat4 {
let aspect = if aspect.is_finite() && aspect > 1e-6 { aspect } else { 1.0 };
@@ -307,6 +338,11 @@ impl Camera {
let (n, f) = self.clip(radius);
self.proj(aspect, n, f).mul(&self.view())
}
+ /// View-projection using the current scene bounds to admit nearby components.
+ pub fn view_proj_bounds(&self, aspect: f64, bounds: &Aabb3) -> Mat4 {
+ let (n, f) = self.clip_bounds(bounds);
+ self.proj(aspect, n, f).mul(&self.view())
+ }
/// World point → pixel coordinates (x right, y down) and depth (0 near … 1 far).
pub fn to_screen(&self, p: Vec3, w: f64, h: f64, radius: f64) -> Option<(f64, f64, f64)> {
let c = self.view_proj(w / h.max(1.0), radius).apply(p);
@@ -630,6 +666,58 @@ mod tests {
assert!((sx - 600.0).abs() < 1e-6 && (sy - 300.0).abs() < 1e-6);
}
+ #[test]
+ fn large_scene_projection_toggle_keeps_near_and_far_components_in_clip_range() {
+ for scale in [1.0, 100.0] {
+ let bounds = Aabb3 { min: Vec3::new(-0.25, -10_000.0, -0.25) * scale, max: Vec3::new(0.25, 10_000.0, 0.25) * scale };
+ let mut cam = Camera { yaw: 0.0, pitch: 0.0, distance: 10_002.0 * scale, ..Default::default() };
+ let original = cam.view_proj_bounds(16.0 / 9.0, &bounds);
+ for fov in [0.0, 0.6, 0.0, 0.6, 0.0] {
+ cam.fov = fov;
+ let vp = cam.view_proj_bounds(16.0 / 9.0, &bounds);
+ let gpu = vp.to_f32();
+ assert!(gpu.iter().flatten().all(|v| v.is_finite()));
+ for x in [bounds.min.x, bounds.max.x] {
+ for y in [bounds.min.y, bounds.max.y] {
+ for z in [bounds.min.z, bounds.max.z] {
+ let p = Vec3::new(x, y, z);
+ let c = vp.apply(p);
+ assert!(c[3] > 0.0 && (0.0..=c[3]).contains(&c[2]), "scale={scale}, fov={fov}, {p:?}: {c:?}");
+ assert!(c[0].abs() <= c[3] && c[1].abs() <= c[3]);
+ let p = p.to_f32();
+ let c: [f32; 4] = std::array::from_fn(|r| gpu[0][r] * p[0] + gpu[1][r] * p[1] + gpu[2][r] * p[2] + gpu[3][r]);
+ assert!(c[3] > 0.0 && (0.0..=c[3]).contains(&c[2]), "GPU scale={scale}, fov={fov}: {c:?}");
+ }
+ }
+ }
+ if fov == 0.0 {
+ assert_eq!(vp, original);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn bounds_clipping_handles_eye_crossing_and_invalid_bounds() {
+ let cam = Camera { yaw: 0.0, pitch: 0.0, distance: 10_000.0, fov: 0.6, ..Default::default() };
+ let crossing = Aabb3 { min: Vec3::new(-1.0, -10_001.0, -1.0), max: Vec3::new(1.0, 10_001.0, 1.0) };
+ let (near, far) = cam.clip_bounds(&crossing);
+ assert_eq!(near, 1e-3);
+ assert!(far.is_finite() && far > near);
+ let c = cam.view_proj_bounds(1.0, &crossing).apply(Vec3::new(0.0, -9_999.0, 0.0));
+ assert!(c[3] > 0.0 && (0.0..=c[3]).contains(&c[2]));
+ let fallback = cam.clip((cam.half_height() * 2.0).max(50.0));
+ for bounds in [
+ Aabb3::EMPTY,
+ Aabb3 { min: Vec3::new(f64::NAN, 0.0, 0.0), max: Vec3::ZERO },
+ Aabb3 { min: Vec3::ZERO, max: Vec3::new(f64::INFINITY, 1.0, 1.0) },
+ Aabb3 { min: Vec3::new(-f64::MAX, -1.0, -1.0), max: Vec3::new(f64::MAX, 1.0, 1.0) },
+ ] {
+ assert_eq!(cam.clip_bounds(&bounds), fallback);
+ assert!(cam.view_proj_bounds(1.0, &bounds).0.iter().flatten().all(|v| v.is_finite()));
+ }
+ }
+
#[test]
fn fit_and_hostile() {
let mut c = Camera::default();
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 02e119463e..50b22b114e 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -306,11 +306,16 @@ fn rgba(c: Rgb) -> [u8; 4] {
[c.0, c.1, c.2, 255]
}
-pub fn scene_radius(app: &SolveApp) -> f64 {
+fn scene_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 {
let mut b = model_bounds(app);
if !app.preview.bounds.is_empty() {
b = b.union(&app.preview.bounds);
}
+ b
+}
+
+pub fn scene_radius(app: &SolveApp) -> f64 {
+ let b = scene_bounds(app);
let r = if b.is_empty() { 50.0 } else { b.diagonal() * 0.5 + b.center().dist(app.cam.target) };
r.max(app.cam.half_height() * 2.0).max(10.0)
}
@@ -319,7 +324,7 @@ pub fn projection(app: &SolveApp, rect: Rect) -> Proj {
let mut cam = app.cam;
cam.fov = if app.perspective_view() { 0.6 } else { 0.0 };
let aspect = rect.width() as f64 / rect.height().max(1.0) as f64;
- Proj { cam, vp: cam.view_proj(aspect, scene_radius(app)), rect }
+ Proj { cam, vp: cam.view_proj_bounds(aspect, &scene_bounds(app)), rect }
}
/// Sketches drawn in the viewport: the active one, and finished ones not yet used by a feature.
@@ -8664,6 +8669,54 @@ mod grid_plane_tests {
assert!(!grid(&app).is_empty());
}
+ #[test]
+ fn imported_scene_projection_toggle_keeps_front_components_in_clip_range() {
+ use solidcraft_engine::doc::{Document, FeatureKind, MeshData};
+ let mut doc = Document::default();
+ let meshes = [-10_000.0, 10_000.0]
+ .into_iter()
+ .enumerate()
+ .map(|(i, y)| MeshData {
+ name: format!("Panel {i}"),
+ positions: vec![-0.25, y, -0.25, 0.25, y, -0.25, 0.0, y, 0.25].into(),
+ triangles: vec![0, 1, 2].into(),
+ color: None,
+ })
+ .collect();
+ doc.add_feature(FeatureKind::MeshImport { file: "synthetic.stl".into(), meshes }, Some("Panels")).unwrap();
+ let mut app = SolveApp::new(solidcraft_engine::Session::new(doc), crate::Services::default());
+ app.cam.yaw = 0.0;
+ app.cam.pitch = 0.0;
+ app.fit_view();
+ app.cancel_view_animation();
+ app.cam.distance = 10_002.0;
+ assert_eq!(app.session.world_state().bodies.len(), 2);
+ let camera = app.cam;
+ let rect = Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 720.0));
+ let original = projection(&app, rect).vp;
+ for shadow in [false, true] {
+ app.ui.ground_shadow = shadow;
+ for perspective in [false, true, false] {
+ app.ui.perspective = perspective;
+ let proj = projection(&app, rect);
+ for body in &app.session.world_state().bodies {
+ let (mesh, _) = body.mesh_in_place();
+ assert_eq!(mesh.positions.len(), 3);
+ for p in &mesh.positions {
+ let c = proj.vp.apply(*p);
+ assert!(c.iter().all(|v| v.is_finite()));
+ assert!(c[3] > 0.0 && (0.0..=c[3]).contains(&c[2]), "shadow={shadow}, perspective={perspective}, {p:?}: {c:?}");
+ assert!(c[0].abs() <= c[3] && c[1].abs() <= c[3]);
+ }
+ }
+ assert_eq!(app.cam, camera, "changing projection preserves the orbit camera");
+ if !perspective {
+ assert_eq!(proj.vp, original);
+ }
+ }
+ }
+ }
+
/// A sketch is drawn in a parallel view even when the preference asks for perspective; the
/// preference comes back when the sketch is finished.
#[test]
diff --git a/docs/view-clipping.md b/docs/view-clipping.md
new file mode 100644
index 0000000000..fe3a4177a5
--- /dev/null
+++ b/docs/view-clipping.md
@@ -0,0 +1,27 @@
+# Viewport clipping
+
+The Design viewport computes its clipping planes from the current model and preview
+bounds on every projection, using the effective camera (orthographic while a sketch
+is open, otherwise the selected projection). Changing projection preserves the orbit
+camera's target, orientation and distance.
+
+The bounding sphere around the target, with the existing viewport-scale margin,
+continues to determine the far plane and the orthographic depth range. The margin
+also admits nearby grids and overlays. In perspective, the near plane must additionally
+respect the nearest depth of the scene's axis-aligned bounding box along the camera's
+view direction. It is capped at half that depth, with a minimum of 0.001 mm. A box
+crossing the eye uses that minimum. Geometry behind the perspective eye remains
+outside the view.
+
+Orbit distance alone cannot set a safe near plane. A component can lie close to the
+eye in a deep assembly even when the target and the assembly centre are near the
+origin. A near-plane floor of 0.1% of orbit distance can then clip the entire component.
+Disabling ground shadow does not change these clipping planes.
+
+Empty, non-finite or overflowing bounds use the existing radius-based fallback.
+Callers that only supply a radius retain the existing camera API and clipping policy.
+
+Regression coverage uses synthetic panels at opposite ends of a deep scene. Their
+vertices must remain inside the depth range through orthographic → perspective →
+orthographic toggles, including the viewport's f32 matrix conversion. The viewport
+regression checks both ground-shadow settings and unchanged stored camera state.