Skip to content

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

Keep raised models’ ground shadows on the ground (#9838) (#10257)

Colin Faulkingham18b698ffa8e0
diff --git a/assets/locales/pending/ground-shadow-placement.json b/assets/locales/pending/ground-shadow-placement.json
new file mode 100644
index 0000000000..145e83d57f
--- /dev/null
+++ b/assets/locales/pending/ground-shadow-placement.json
@@ -0,0 +1,34 @@
+{
+ "ar": {
+ "prefs.ground_shadow_follows_model": "ظل الأرض يتبع النموذج",
+ "prefs.ground_shadow_follows_model_help": "ضع الظل أسفل أدنى جسم مرئي. عند التعطيل، يبقى ظل النماذج المرفوعة على مستوى الأرض عند نقطة الأصل."
+ },
+ "de": {
+ "prefs.ground_shadow_follows_model": "Bodenschatten folgt dem Modell",
+ "prefs.ground_shadow_follows_model_help": "Den Schatten unter dem niedrigsten sichtbaren Körper platzieren. Wenn deaktiviert, bleibt der Schatten angehobener Modelle auf der Bodenebene durch den Ursprung."
+ },
+ "en": {
+ "prefs.ground_shadow_follows_model": "Ground shadow follows the model",
+ "prefs.ground_shadow_follows_model_help": "Place the shadow below the lowest visible body. When off, raised models keep their shadow on the origin ground plane."
+ },
+ "he": {
+ "prefs.ground_shadow_follows_model": "צל הקרקע עוקב אחר המודל",
+ "prefs.ground_shadow_follows_model_help": "מקם את הצל מתחת לגוף הגלוי הנמוך ביותר. כשהאפשרות כבויה, הצל של מודלים מוגבהים נשאר במישור הקרקע העובר בראשית הצירים."
+ },
+ "ja": {
+ "prefs.ground_shadow_follows_model": "地面の影をモデルに追従させる",
+ "prefs.ground_shadow_follows_model_help": "表示中のボディの最下部に影を配置します。オフの場合、持ち上げたモデルの影は原点を通る地面上に残ります。"
+ },
+ "ko": {
+ "prefs.ground_shadow_follows_model": "지면 그림자가 모델을 따라 이동",
+ "prefs.ground_shadow_follows_model_help": "표시된 바디의 가장 낮은 지점 아래에 그림자를 배치합니다. 끄면 위로 이동한 모델의 그림자가 원점을 지나는 지면에 유지됩니다."
+ },
+ "vi": {
+ "prefs.ground_shadow_follows_model": "Bóng trên mặt đất di chuyển theo mô hình",
+ "prefs.ground_shadow_follows_model_help": "Đặt bóng bên dưới khối hiển thị thấp nhất. Khi tắt, bóng của mô hình được nâng lên vẫn nằm trên mặt phẳng đất đi qua gốc tọa độ."
+ },
+ "zh": {
+ "prefs.ground_shadow_follows_model": "地面阴影跟随模型",
+ "prefs.ground_shadow_follows_model_help": "将阴影放在可见实体的最低点下方。关闭时,抬高模型的阴影仍位于经过原点的地面上。"
+ }
+}
diff --git a/attribution/pending/ground-shadow-placement.md b/attribution/pending/ground-shadow-placement.md
new file mode 100644
index 0000000000..d6414b4d65
--- /dev/null
+++ b/attribution/pending/ground-shadow-placement.md
@@ -0,0 +1 @@
+| assets/locales/pending/ground-shadow-placement.json | SolidCraft contributors | Original ground-shadow placement preference messages and translations | MIT OR Apache-2.0 |
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index c1e83ae97f..524ab8534a 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1149,6 +1149,8 @@ preference_settings! {
graphics_adapter: String = String::new(), PAGE_GRAPHICS;
/// Soft contact shading in the GPU viewport; optional and applied immediately.
ambient_occlusion: bool = false, PAGE_GRAPHICS;
+ /// Restore the shadow plane at the lowest visible body, including above the origin (#9838).
+ ground_shadow_follows_model: bool = false, PAGE_GRAPHICS => check_id("prefs.ground_shadow_follows_model");
/// Shade the viewport in linear light with a sky fill, so dark parts keep their shape
/// (#7974). Off by default: the viewport shades as it always has.
dark_parts_shading: bool = false, PAGE_GRAPHICS => check_id("prefs.dark_parts_shading");
@@ -9852,6 +9854,43 @@ mod tests {
assert!(h.app.preferences.select_hidden_edges);
}
+ #[test]
+ fn ground_shadow_placement_follows_preferences_transactions() {
+ assert!(!Prefs::default().ground_shadow_follows_model);
+ let old: Prefs = serde_json::from_value(json!({"msaa":4})).unwrap();
+ assert!(!old.ground_shadow_follows_model);
+ assert!(!lenient(&json!({"ground_shadow_follows_model":"yes"})).ground_shadow_follows_model);
+ let mut h = crate::scenario::Harness::new();
+ h.app.ui.ground_shadow = true;
+ let camera = h.app.cam;
+ let design = h.app.session.doc.to_json();
+ h.call("ui.prefs", json!({"open":"Graphics"}));
+ super::reveal_preference(&mut h, "prefs:ground_shadow_follows_model");
+ let checkbox = crate::scenario::handle_at("prefs:ground_shadow_follows_model").unwrap();
+ h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y}));
+ assert!(h.app.preferences.ground_shadow_follows_model);
+ let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
+ restored.load_prefs(&h.app.prefs());
+ assert!(!restored.preferences.ground_shadow_follows_model, "an unapplied change is not saved");
+ h.call("ui.prefs", json!({"button":"cancel"}));
+ assert!(!h.app.preferences.ground_shadow_follows_model);
+ h.call("ui.prefs", json!({"ground_shadow_follows_model":true}));
+ assert!(!h.app.prefs_window.open, "programmatic changes do not open Preferences");
+ restored.load_prefs(&h.app.prefs());
+ assert!(restored.preferences.ground_shadow_follows_model);
+ h.call("ui.prefs", json!({"open":"Graphics", "button":"defaults"}));
+ assert!(!h.app.preferences.ground_shadow_follows_model);
+ h.call("ui.prefs", json!({"button":"cancel"}));
+ assert!(h.app.preferences.ground_shadow_follows_model, "Cancel restores the saved choice");
+ h.call("ui.prefs", json!({"open":"Graphics", "button":"defaults"}));
+ h.call("ui.prefs", json!({"button":"apply"}));
+ restored.load_prefs(&h.app.prefs());
+ assert!(!restored.preferences.ground_shadow_follows_model, "Graphics defaults can be saved");
+ assert_eq!(h.app.cam, camera);
+ assert_eq!(h.app.session.doc.to_json(), design);
+ assert!(h.app.session.undo.is_empty());
+ }
+
#[test]
fn tool_modifier_prefs_default_classic_and_persist() {
let d = Prefs::default();
diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rs
index e1adf7e3c3..7c5b4bf84a 100644
--- a/crates/ui-egui/src/prefs/graphics.rs
+++ b/crates/ui-egui/src/prefs/graphics.rs
@@ -199,6 +199,10 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
});
+ ui.add_enabled_ui(app.ui.ground_shadow, |ui| {
+ let response = setting::ground_shadow_follows_model(app, ui).on_hover_text(app.tr("prefs.ground_shadow_follows_model_help"));
+ crate::scenario::publish_handle("prefs:ground_shadow_follows_model", response.rect.center());
+ });
ui_kit::settings_form(ui, t.form_label_width + t.space_24, |ui| {
ui_kit::row(ui, app.tr_label("Visual style"), |ui| {
let options = crate::navigation_bar::VISUAL_STYLES.map(|(_, label)| crate::i18n::tr_label(label));
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 4e627f8113..6f2e7df483 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -596,6 +596,8 @@ fn scene_key(app: &SolveApp) -> u64 {
(std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h);
app.ui.visual_style.hash(&mut h);
app.preferences.vertex_markers.hash(&mut h);
+ // The cached ground AO receiver and the ellipse share the selected ground plane.
+ app.preferences.ground_shadow_follows_model.hash(&mut h);
solidcraft_engine::doc::display_quality::current().hash(&mut h);
lod_generation(app).hash(&mut h);
app.viewport.mesh_lods.generation().hash(&mut h);
@@ -1735,7 +1737,7 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
if app.ui.visual_style != 2 {
let bounds = ground_bounds(app, &st);
let radius = (bounds.diagonal() * 0.04).clamp(1e-4, 1e6) as f32;
- sc.ground_ao = solidcraft_gpu::view::GroundAo::new(bounds, ground_height(bounds), app.cam.up, radius);
+ sc.ground_ao = solidcraft_gpu::view::GroundAo::new(bounds, ground_height(app, bounds), app.cam.up, radius);
}
// Section: the outline of each body where the plane cuts it, in the view's text colour (#4146).
if let Some((o, n)) = section_plane(app) {
@@ -2073,9 +2075,12 @@ fn ground_bounds(app: &SolveApp, st: &std::sync::Arc<solidcraft_engine::doc::Mod
b
}
-/// Both ground effects use the original ellipse's plane, independent of the origin grid.
-fn ground_height(bounds: solidcraft_engine::geom::Aabb3) -> f64 {
- bounds.min.z - 1e-3 * (1.0 + bounds.diagonal())
+/// Both ground effects share the selected plane, independent of the origin grid.
+fn ground_height(app: &SolveApp, bounds: solidcraft_engine::geom::Aabb3) -> f64 {
+ // Raised bodies cast onto the origin. Keep the plane below lower bodies, and
+ // retain the former floating ground when requested.
+ let ground = if app.preferences.ground_shadow_follows_model { bounds.min.z } else { bounds.min.z.min(0.0) };
+ ground - 1e-3 * (1.0 + bounds.diagonal())
}
fn ground_shadow(sc: &mut GpuScene, app: &SolveApp, b: solidcraft_engine::geom::Aabb3) {
@@ -2084,7 +2089,7 @@ fn ground_shadow(sc: &mut GpuScene, app: &SolveApp, b: solidcraft_engine::geom::
}
let size = b.size();
let c = b.center();
- let z = ground_height(b);
+ let z = ground_height(app, b);
let (rx, ry) = (size.x * 0.62 + size.z * 0.15, size.y * 0.62 + size.z * 0.15);
if !(rx > 0.0 && ry > 0.0) {
return;
@@ -7240,6 +7245,69 @@ mod tests {
use super::*;
use crate::navigation::*;
+ #[test]
+ fn raised_bodies_cast_ground_shadows_at_the_origin() -> Result<(), Box<dyn std::error::Error>> {
+ use solidcraft_engine::render::UpAxis;
+ for (up, translate, coordinate) in [(UpAxis::Z, [0, 0, 13], 2), (UpAxis::Y, [0, 13, 0], 1)] {
+ let mut session = solidcraft_engine::Session::default();
+ session.execute("solid.box", &json!({"length": 12, "width": 12, "height": 30, "body_name": "Raised"}))?;
+ session.execute("solid.move", &json!({"bodies": ["Raised"], "translate": translate}))?;
+ let mut app = SolveApp::new(session, crate::Services::default());
+ app.cam.up = up;
+ let mut scene = GpuScene::default();
+ ground_shadow(&mut scene, &app, ground_bounds(&app, &app.session.world_state()?));
+ assert!(!scene.shadow.is_empty());
+ for vertex in scene.shadow.as_chunks::<{ crate::gpu::TRI_SIZE }>().0 {
+ let height = f32::from_le_bytes(vertex[coordinate * 4..coordinate * 4 + 4].try_into()?);
+ assert!((-0.1..=0.0).contains(&height), "{up:?}: shadow must stay just below the origin ground plane, got {height}");
+ }
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn ground_shadow_keeps_legacy_placement_and_stays_below_low_bodies() -> Result<(), Box<dyn std::error::Error>> {
+ use solidcraft_engine::render::UpAxis;
+ for (up, coordinate) in [(UpAxis::Z, 2), (UpAxis::Y, 1)] {
+ for (height, follows_model, expected) in [(13, true, 13.0), (-7, false, -7.0), (-7, true, -7.0), (0, false, 0.0)] {
+ let mut session = solidcraft_engine::Session::default();
+ session.execute("solid.box", &json!({"length": 12, "width": 12, "height": 30, "body_name": "Box"}))?;
+ let mut translate = [0; 3];
+ translate[coordinate] = height;
+ session.execute("solid.move", &json!({"bodies": ["Box"], "translate": translate}))?;
+ let mut app = SolveApp::new(session, crate::Services::default());
+ app.cam.up = up;
+ let state = app.session.world_state()?;
+ let proj = projection(&app, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)));
+ let model_key = scene_key(&app);
+ let view_key = sketch_scene_key(&app, &proj);
+ let before = shadow_geometry(&app, &state);
+ crate::prefs::set(&mut app, &json!({"ground_shadow_follows_model": true}))?;
+ assert_ne!(scene_key(&app), model_key, "the cached ground AO receiver is refreshed");
+ assert_ne!(sketch_scene_key(&app, &proj), view_key, "the visible shadow is refreshed");
+ let after = shadow_geometry(&app, &state);
+ assert!(!std::sync::Arc::ptr_eq(&before.bytes, &after.bytes), "changing placement rebuilds the shadow");
+ assert!(std::sync::Arc::ptr_eq(&after.bytes, &shadow_geometry(&app, &state).bytes), "unchanged placement stays cached");
+ crate::prefs::set(&mut app, &json!({"ground_shadow_follows_model": follows_model}))?;
+ let mut scene = GpuScene::default();
+ ground_shadow(&mut scene, &app, ground_bounds(&app, &app.session.world_state()?));
+ assert!(!scene.shadow.is_empty());
+ for vertex in scene.shadow.as_chunks::<{ crate::gpu::TRI_SIZE }>().0 {
+ let actual = f32::from_le_bytes(vertex[coordinate * 4..coordinate * 4 + 4].try_into()?);
+ assert!(
+ (expected - 0.1..=expected).contains(&actual),
+ "{up:?}, follows model {follows_model}: expected {expected}, got {actual}"
+ );
+ }
+ app.session.visibility.hidden_bodies.push("Box".into());
+ let mut hidden = GpuScene::default();
+ ground_shadow(&mut hidden, &app, ground_bounds(&app, &app.session.world_state()?));
+ assert!(hidden.shadow.is_empty(), "hidden bodies cast no shadow");
+ }
+ }
+ Ok(())
+ }
+
#[test]
fn ground_shadow_does_not_enter_see_through_geometry() -> Result<(), Box<dyn std::error::Error>> {
let mut session = solidcraft_engine::Session::default();
diff --git a/crates/ui-egui/src/viewport_ground_tests.rs b/crates/ui-egui/src/viewport_ground_tests.rs
index 88b89c74d0..fc4faa24be 100644
--- a/crates/ui-egui/src/viewport_ground_tests.rs
+++ b/crates/ui-egui/src/viewport_ground_tests.rs
@@ -2,26 +2,30 @@ use super::*;
use solidcraft_engine::{Session, geom::Aabb3, render::UpAxis};
#[test]
-fn ground_ao_follows_the_existing_plane_in_both_up_axes_without_origin_clamping() {
+fn ground_ao_shares_the_selected_ground_plane_in_both_up_axes() {
+ let mut app = SolveApp::new(Session::default(), crate::Services::default());
for up in [UpAxis::Z, UpAxis::Y] {
let cam = Camera { up, ..Default::default() };
- for bottom in [-20.0, 20.0] {
+ app.cam = cam;
+ for (bottom, follows_model) in [(-20.0, false), (20.0, false), (-20.0, true), (20.0, true)] {
+ app.preferences.ground_shadow_follows_model = follows_model;
// A 3 x 4 x 12 box has diagonal 13: the original ground offset is .014 mm.
let bounds = Aabb3 { min: Vec3::new(-1.5, -2.0, bottom), max: Vec3::new(1.5, 2.0, bottom + 12.0) };
- let ground = solidcraft_gpu::view::GroundAo::new(bounds, ground_height(bounds), cam.up, 2.0).unwrap();
+ let ground = solidcraft_gpu::view::GroundAo::new(bounds, ground_height(&app, bounds), cam.up, 2.0).unwrap();
let bytes = ground.vertices(None);
assert_eq!(bytes.len(), 6 * crate::gpu::TRI_SIZE);
for vertex in bytes.as_chunks::<{ crate::gpu::TRI_SIZE }>().0 {
let read = |i| f64::from(f32::from_le_bytes(vertex[i..i + 4].try_into().unwrap()));
let point = cam.to_frame(Vec3::new(read(0), read(4), read(8)));
- assert!((point.z - (bottom - 0.014)).abs() < 1e-5);
+ let expected = if follows_model { bottom } else { bottom.min(0.0) };
+ assert!((point.z - (expected - 0.014)).abs() < 1e-5);
assert!(point.x >= -5.5 && point.x <= 5.5 && point.y >= -6.0 && point.y <= 6.0);
assert_eq!(cam.to_frame(Vec3::new(read(12), read(16), read(20))), Vec3::Z);
}
}
}
for (bounds, radius) in [(Aabb3::EMPTY, 2.0), (Aabb3 { min: Vec3::ZERO, max: Vec3::X }, f32::NAN)] {
- assert!(solidcraft_gpu::view::GroundAo::new(bounds, ground_height(bounds), Camera::default().up, radius).is_none());
+ assert!(solidcraft_gpu::view::GroundAo::new(bounds, ground_height(&app, bounds), Camera::default().up, radius).is_none());
}
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index a27107af91..63e46f9867 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -717,6 +717,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own
- `extrude_auto_to_object` (default true: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object, unless the Profiles box was clicked into; it applies to Extrude dialogs opened afterwards)
- `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it)
- `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence)
+- `ground_shadow_follows_model` (Graphics, default false): raised models cast their ground shadow on the origin ground plane; true restores the shadow below the lowest visible body. Both modes keep the shadow below bodies extending beneath the origin, and follow the selected up axis.
- `hidden_toolbar_tabs` (default `[]`: all existing tabs, including Sheet Metal and Weldments, stay visible; lists tabs to hide, each once, e.g. `["SURFACE", "SHEET METAL"]`; hidden tabs stay hidden regardless of the design's features; [ribbon layout](ribbon-layout.md))
- `history_sketches` (`in_order` (default), `under_feature`: the History at the left lists a sketch under the first feature built from it, #6489; the timeline at the bottom keeps the creation order)
- `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there)