View navigator: right-click to choose Axes, Cube or a Custom body (#10266)

* View navigator: a custom body as the navigator, and a right-click menu to switch types

A right-click anywhere on the view navigator opens a menu with its three types: Axes, Cube and
Custom. Custom opens the Custom View Navigator panel (a feature panel with OK and Cancel): pick a
body in the view, its texture (Themed: the cube's colours; Modeled: the body's own appearance and
the view's edge colour), and whether the cube's rotation arrows and Home button go around it. The
navigator previews the panel's choices while it is open; Cancel leaves it as it was.

The custom navigator draws the body at the cube's size through a small depth-buffered raster, so
hidden faces stay hidden; hovering a face highlights it, a click looks straight at it (and frames
the model with navigator_fit on), a drag orbits. Until a body is chosen it draws the cube.

The body is kept as a packed snapshot (16-bit, base64) with the preferences and in settings
profiles, so it stays across runs and designs and travels with an exported profile. Bodies over
10,000 triangles, and long or flat ones (thinnest width under a fifth of the widest), are refused.

New command view.navigator (style, body, texture, arrows, home) does the same without opening
anything; new preferences navigator_texture, navigator_arrows and navigator_home, and a Custom
choice for navigator_style. Defaults are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: a hovered face in Modeled takes the view's selection colours

In the Modeled texture the face under the pointer is filled and outlined the way the view selects
a face of the model (sel_face, sel_edge), not in the cube's hover blue and accent, which Themed
keeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: a hovered face in Modeled lights up as the view's mouse-over does

The face under the pointer keeps its own colour, a little lighter (hover_face_lift) and still
shaded, with its edges in the view's mouse-over edge colour (hover_edge), as the 3D view shows a
face under the pointer; not the selection colours. Themed keeps the cube's hover blue and accent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: rotation arrows and Home on by default

navigator_arrows and navigator_home start on, so a new custom navigator has the cube's arrows and
Home button around it; the Custom View Navigator panel turns either off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: the strings in every complete language, and test fixes

- The new messages in Arabic, Hebrew and Vietnamese (complete catalogs, like Japanese and Chinese).
- The navigator's raster goes through one colour helper, listed with its reason among the files
  allowed colour literals (the design's appearance shaded into pixels).
- nav_settings joins the requested-icon manifest (the view.navigator command's icon).
- A visible edge piece is kept only when the stretch seen with it, across the edge's segments, is
  at least two samples long: a hidden edge no longer shows a sliver at a silhouette corner.
- The navigator layout test treats Custom without a body as the cube it draws; the panel and
  size tests no longer assume an empty undo list, the style before opening, or a coarse sphere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: profiles carry its texture, arrows and Home

Settings profiles keep a fixed set of preference keys (#9907), which the custom navigator's newer
settings are not part of. They travel in the profile's own `view_navigator` entry, next to its
body (`view_gizmo`): captured, checked (a value this version can't read is left out) and applied,
leaving the fixed key set unchanged. The cube's arrow inversion (#10286) applies to the custom
navigator's arrows too, through the shared arrows().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: follow main's Vec3 move and fallible world_state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: list view.navigator in the rig's EXEMPT, refuse a stored body that can't save again, right-click without a widget over the navigator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: keep the body unless picked again, save only a profile that reads back, no navigator menu through a popup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: refuse a stored body with a triangle past its points

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: a stored body meets the triangle and aspect limits a picked one does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Custom view navigator: a body at the 5:1 limit stays inside it once packed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
froglemonade2
2026-11-04 17:12:27 +00:00
committed by GitHub
parent 30842efb22
commit 3e70ad9876
27 changed files with 1926 additions and 49 deletions
@@ -161,6 +161,7 @@ min_radius false
mirror false
motion_link false
move false
nav_settings false
new false
normal false
offset false
@@ -0,0 +1,98 @@
{
"en": {
"cmd.view.navigator": "Custom View Navigator",
"ui.heading_custom_view_navigator": "CUSTOM VIEW NAVIGATOR",
"view_gizmo.arrows": "Rotation arrows",
"view_gizmo.home": "Home button",
"view_gizmo.no_such_body": "This design has no body of that name.",
"view_gizmo.note": "Pick a body in the view. It is kept with your preferences and settings profiles, and shown in every design. Click one of its faces to look straight at it.",
"view_gizmo.texture": "Texture",
"view_gizmo.themed": "Themed",
"view_gizmo.too_detailed": "Too detailed for the view navigator (over 10,000 triangles)",
"view_gizmo.too_thin": "Too long and thin for the view navigator: its thinnest side must be at least a fifth of its longest"
},
"ar": {
"cmd.view.navigator": "متصفح العرض المخصص",
"ui.heading_custom_view_navigator": "متصفح العرض المخصص",
"view_gizmo.arrows": "أسهم التدوير",
"view_gizmo.home": "زر العرض الرئيسي",
"view_gizmo.no_such_body": "لا يوجد في هذا التصميم جسم بهذا الاسم.",
"view_gizmo.note": "اختر جسمًا في العرض. يُحفظ مع تفضيلاتك وملفات تعريف الإعدادات، ويظهر في كل تصميم. انقر أحد أوجهه للنظر إليه مباشرة.",
"view_gizmo.texture": "الخامة",
"view_gizmo.themed": "حسب السمة",
"view_gizmo.too_detailed": "مفصّل أكثر مما يناسب متصفح العرض (أكثر من 10,000 مثلث)",
"view_gizmo.too_thin": "طويل ورفيع أكثر مما يناسب متصفح العرض: يجب ألا يقل أرفع جانب عن خُمس أطول جانب"
},
"de": {
"cmd.view.navigator": "Eigener Ansichtsnavigator",
"ui.heading_custom_view_navigator": "EIGENER ANSICHTSNAVIGATOR",
"view_gizmo.arrows": "Drehpfeile",
"view_gizmo.home": "Schaltfläche „Ausgangsansicht“",
"view_gizmo.no_such_body": "Diese Konstruktion hat keinen Körper mit diesem Namen.",
"view_gizmo.note": "Wählen Sie einen Körper in der Ansicht. Er wird mit Ihren Einstellungen und Einstellungsprofilen gespeichert und in jeder Konstruktion angezeigt. Klicken Sie auf eine seiner Flächen, um direkt darauf zu blicken.",
"view_gizmo.texture": "Textur",
"view_gizmo.themed": "Design",
"view_gizmo.too_detailed": "Zu detailliert für den Ansichtsnavigator (über 10.000 Dreiecke)",
"view_gizmo.too_thin": "Zu lang und dünn für den Ansichtsnavigator: Die dünnste Seite muss mindestens ein Fünftel der längsten sein"
},
"he": {
"cmd.view.navigator": "ניווט תצוגה מותאם אישית",
"ui.heading_custom_view_navigator": "ניווט תצוגה מותאם אישית",
"view_gizmo.arrows": "חיצי סיבוב",
"view_gizmo.home": "לחצן תצוגת בית",
"view_gizmo.no_such_body": "אין בעיצוב הזה גוף בשם הזה.",
"view_gizmo.note": "בחרו גוף בתצוגה. הוא נשמר עם ההעדפות ופרופילי ההגדרות שלכם ומוצג בכל עיצוב. לחצו על אחת מפאותיו כדי להביט בה ישירות.",
"view_gizmo.texture": "מרקם",
"view_gizmo.themed": "לפי ערכת הנושא",
"view_gizmo.too_detailed": "מפורט מדי לניווט התצוגה (יותר מ-10,000 משולשים)",
"view_gizmo.too_thin": "ארוך ודק מדי לניווט התצוגה: הצד הדק ביותר חייב להיות לפחות חמישית מהצד הארוך ביותר"
},
"ja": {
"cmd.view.navigator": "カスタム ビューナビゲーター",
"ui.heading_custom_view_navigator": "カスタム ビューナビゲーター",
"view_gizmo.arrows": "回転矢印",
"view_gizmo.home": "ホーム ボタン",
"view_gizmo.no_such_body": "このデザインにその名前のボディはありません。",
"view_gizmo.note": "ビューでボディを選択してください。ボディは環境設定と設定プロファイルに保存され、すべてのデザインで表示されます。面をクリックすると、その面を正面から見ます。",
"view_gizmo.texture": "テクスチャ",
"view_gizmo.themed": "テーマ",
"view_gizmo.too_detailed": "ビューナビゲーターには細かすぎます (10,000 三角形を超えています)",
"view_gizmo.too_thin": "ビューナビゲーターには細長すぎます: 最も薄い辺が最も長い辺の 5 分の 1 以上である必要があります"
},
"ko": {
"cmd.view.navigator": "사용자 지정 뷰 탐색기",
"ui.heading_custom_view_navigator": "사용자 지정 뷰 탐색기",
"view_gizmo.arrows": "회전 화살표",
"view_gizmo.home": "홈 버튼",
"view_gizmo.no_such_body": "이 디자인에 그런 이름의 바디가 없습니다.",
"view_gizmo.note": "뷰에서 바디를 선택하십시오. 바디는 환경설정과 설정 프로필에 저장되어 모든 디자인에 표시됩니다. 면을 클릭하면 그 면을 정면으로 봅니다.",
"view_gizmo.texture": "텍스처",
"view_gizmo.themed": "테마",
"view_gizmo.too_detailed": "뷰 탐색기에 너무 세밀합니다 (삼각형 10,000개 초과)",
"view_gizmo.too_thin": "뷰 탐색기에 너무 가늘고 깁니다: 가장 얇은 변이 가장 긴 변의 5분의 1 이상이어야 합니다"
},
"vi": {
"cmd.view.navigator": "Khối điều hướng góc nhìn tùy chỉnh",
"ui.heading_custom_view_navigator": "KHỐI ĐIỀU HƯỚNG GÓC NHÌN TÙY CHỈNH",
"view_gizmo.arrows": "Mũi tên xoay",
"view_gizmo.home": "Nút góc nhìn mặc định (Home)",
"view_gizmo.no_such_body": "Thiết kế này không có thân khối nào mang tên đó.",
"view_gizmo.note": "Chọn một thân khối trong khung nhìn. Thân khối được lưu cùng tùy chọn và hồ sơ cài đặt của bạn, và hiển thị trong mọi thiết kế. Nhấp vào một mặt của nó để nhìn thẳng vào mặt đó.",
"view_gizmo.texture": "Kết cấu",
"view_gizmo.themed": "Theo chủ đề",
"view_gizmo.too_detailed": "Quá chi tiết cho khối điều hướng góc nhìn (hơn 10.000 tam giác)",
"view_gizmo.too_thin": "Quá dài và mảnh cho khối điều hướng góc nhìn: cạnh mỏng nhất phải ít nhất bằng một phần năm cạnh dài nhất"
},
"zh": {
"cmd.view.navigator": "自定义视图导航器",
"ui.heading_custom_view_navigator": "自定义视图导航器",
"view_gizmo.arrows": "旋转箭头",
"view_gizmo.home": "主页按钮",
"view_gizmo.no_such_body": "此设计中没有该名称的实体。",
"view_gizmo.note": "在视图中选择一个实体。它随首选项和设置配置文件保存,并在每个设计中显示。单击它的一个面即可正视该面。",
"view_gizmo.texture": "纹理",
"view_gizmo.themed": "主题",
"view_gizmo.too_detailed": "对视图导航器而言过于精细(超过 10,000 个三角形)",
"view_gizmo.too_thin": "对视图导航器而言过于细长:最薄的一边至少要有最长一边的五分之一"
}
}
+18 -1
View File
@@ -6,12 +6,13 @@ use solidcraft_render::{Camera, StandardView};
use super::CommandSpec;
use crate::params::{bad, num, req_vec2, req_vec3, vec3};
use crate::schema::view_navigation::{
CameraReply, NormalToParams, RenderBrowser, RenderFocus, RenderSelect, StandardViewParams, TabStep, TabStepParams,
CameraReply, NavigatorParams, NormalToParams, RenderBrowser, RenderFocus, RenderSelect, StandardViewParams, TabStep, TabStepParams,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Sel, Session};
const FOCUS_CONTRACT: TypedContract<RenderFocus> = TypedContract::new();
const NAVIGATOR_CONTRACT: TypedContract<NavigatorParams> = TypedContract::new();
const BROWSER_CONTRACT: TypedContract<RenderBrowserRequest> = TypedContract::new();
const TAB_STEP_CONTRACT: TypedContract<TabStepParams> = TypedContract::new();
const STANDARD_VIEW_CONTRACT: TypedContract<StandardViewParams> = TypedContract::new();
@@ -64,6 +65,10 @@ CommandSpec::new("view.ground_shadow", "Ground shadow", ground_shadow)
.icon("style").noundo().doc_only().params("on?: bool (omitted: toggle) → on?; show the ground shadow"),
CommandSpec::new("view.navigation_bar", "Navigation bar", navigation_bar)
.icon("pan").noundo().doc_only().params("visible?: bool (omitted: toggle) → visible?; show the navigation bar (window setting)"),
CommandSpec::new("view.navigator", "Custom View Navigator", crate::checked!("view.navigator", navigator))
.icon("nav_settings").noundo().doc_only()
.contract(&NAVIGATOR_CONTRACT).output(output_schema_for::<NavigatorParams>)
.params("style?: axes|cube|custom; body?: body name|null; texture?: themed|modeled; arrows?, home?: bool → the navigator as set; the app's view navigator, never saved in the design; never opens a dialog (a toolbar start opens the Custom View Navigator panel)"),
CommandSpec::new("view.render_focus", "Render Focus View", crate::checked!("view.render_focus", render_focus))
.icon("render_scene").noundo().doc_only()
.contract(&FOCUS_CONTRACT).output(output_schema_for::<RenderFocus>)
@@ -324,6 +329,18 @@ fn status_items(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!(crate::status_items::StatusItems { items: s.status_items() }))
}
/// The app sets the navigator; the engine checks the parameters and that a named body exists.
fn navigator(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "view.navigator";
let request: NavigatorParams = serde_json::from_value(if p.is_null() { json!({}) } else { p.clone() }).map_err(|e| bad(cmd, e.to_string()))?;
if let Some(Some(name)) = &request.body
&& s.world_state()?.body(name).is_none()
{
return Err(bad(cmd, format!("no body named `{name}`")));
}
serde_json::to_value(request).map_err(|e| bad(cmd, e.to_string()))
}
fn render_focus(_s: &mut Session, p: &Value) -> Result<Value> {
let request: RenderFocus = serde_json::from_value(p.clone()).map_err(|e| bad("view.render_focus", e.to_string()))?;
Ok(json!(request))
@@ -226,6 +226,58 @@ pub struct RenderFrame {
pub centre_mark: Option<bool>,
}
/// Set the view navigator at the view's corner: its type, and for the custom one the body it
/// draws, its texture and the controls around it. The navigator is the app's, kept with the
/// preferences and settings profiles, never in the design; without an app the call only checks
/// its parameters. Never opens a dialog.
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NavigatorParams {
/// The navigator: signed axes, the cube, or a custom body (the cube until a body is
/// chosen). Default: unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub style: Option<NavigatorStyle>,
/// A body of the open design for the custom navigator to draw; the app keeps a snapshot of
/// it, so it stays when the design closes. `null`: no body (the cube again). A body over
/// 10,000 triangles, or whose thinnest width is under a fifth of its widest, is refused.
/// Default: unchanged.
#[serde(default, deserialize_with = "nullable", skip_serializing_if = "Option::is_none")]
#[schemars(with = "Option<String>")]
pub body: Option<Option<String>>,
/// The custom navigator's colours: the cube's (`themed`) or the body's own appearance and
/// edge colour (`modeled`). Default: unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub texture: Option<NavigatorTexture>,
/// The cube's orbit and roll arrows around the custom navigator. Default: unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub arrows: Option<bool>,
/// The cube's Home button beside the custom navigator. Default: unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub home: Option<bool>,
}
/// A view navigator type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NavigatorStyle {
Axes,
Cube,
Custom,
}
/// How the custom view navigator colours its body.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NavigatorTexture {
Themed,
Modeled,
}
/// A key that may be given as `null` (`Some(None)`), apart from absent (`None`).
fn nullable<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Option<String>>, D::Error> {
Option::<String>::deserialize(d).map(Some)
}
#[cfg(test)]
#[path = "view_navigation_tests.rs"]
mod tests;
@@ -271,3 +271,35 @@ fn next_and_previous_tab_echo_their_step_without_editing_the_design() {
}
assert_eq!((s.doc.to_json(), s.undo.len()), (before, undo), "nothing in the design changes");
}
#[test]
fn navigator_checks_and_echoes_its_settings_and_refuses_a_missing_body() {
assert_keys(input_schema_for::<super::NavigatorParams>(), &["arrows", "body", "home", "style", "texture"]);
let schema = output_schema_for::<super::NavigatorParams>();
let root = schema.as_value();
let mut s = Session::default();
s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap();
let body = s.world_state().unwrap().bodies[0].name.clone();
let before = (s.revision, s.doc.to_json(), s.undo.len());
for (params, echo) in [
(json!({}), json!({})),
(Value::Null, json!({})),
(
json!({"style": "custom", "body": body, "texture": "modeled", "arrows": true, "home": false}),
json!({"style": "custom", "body": body, "texture": "modeled", "arrows": true, "home": false}),
),
(json!({"body": null}), json!({"body": null})),
] {
let reply = s.execute("view.navigator", &params).unwrap();
assert_eq!(reply, echo, "{params}");
assert!(conforms(root, root, &reply), "{reply} does not match {root}");
}
assert_eq!((s.revision, s.doc.to_json(), s.undo.len()), before, "the navigator is never part of the design");
for bad in
[json!({"style": "sphere"}), json!({"body": "No such body"}), json!({"body": 3}), json!({"texture": "glossy"}), json!({"arrows": "yes"})]
{
assert!(s.execute("view.navigator", &bad).is_err(), "{bad}");
}
let spec = crate::find_command("view.navigator").unwrap();
assert!(!spec.undoable && spec.contract.is_some() && spec.output.is_some());
}
+591
View File
@@ -0,0 +1,591 @@
//! The custom view gizmo: the body chosen in [`crate::view_gizmo`] drawn in place of the navigation
//! cube, made the way the cube is: the same size, each face shaded by how squarely it meets the
//! eye. Its texture is the cube's face and border colours, the hovered face in the cube's hover
//! colour and accent (themed), or the body's own appearance with the view's edge colour, the
//! hovered face lit as the view lights a face under the pointer (modeled); the cube's orbit and roll
//! arrows and its Home button go around it when the `navigator_arrows` and `navigator_home`
//! preferences say so. While the Custom View Navigator panel is open it shows the panel's choices.
//! A click on a face looks straight at it; a drag orbits.
//!
//! A concave body cannot be drawn back to front as the cube's six faces are, so the faces go
//! through a small depth-buffered raster (drawn on the CPU, shown as a texture): hidden faces
//! stay hidden and each sample knows its triangle, so hover and click name the face actually
//! seen. Edges stay crisp vector lines, cut where the raster says something nearer covers them.
use super::*;
use crate::prefs::NavigatorTexture;
use crate::view_gizmo::Shape;
use solidcraft_engine::geom::Mesh;
use std::sync::{Arc, Mutex};
/// The body's bounding sphere, in the navigation cube's design units: the cube's own (half
/// side 40, so its corners lie 40√3 from the centre).
const RADIUS: f32 = 69.28;
/// Samples per pixel along each side: smooth silhouettes.
const SS: usize = 2;
/// Largest raster side in pixels (a guard against hostile UI scales).
const MAX_PIXELS: usize = 512;
/// No triangle.
const NONE: u32 = u32::MAX;
/// Centre, radius (points) of the disc the body fills, and the cube's design scale.
fn disc(app: &SolveApp, rect: Rect) -> (Pos2, f32, f32) {
let scale = axis_rect(app, rect).width() / navigation_cube::DESIGN_SIZE;
(axis_center(app, rect), scale * RADIUS, scale)
}
/// A press anywhere on the body's disc orbits, as a press on the cube does.
pub(super) fn drag_origin(app: &SolveApp, rect: Rect, p: Pos2) -> bool {
let (c, r, _) = disc(app, rect);
c.distance(p) <= r
}
/// The orthographic view of a body along a camera, its bounding sphere filling `side` samples.
struct View {
centre: Vec3,
radius: f64,
half: f64,
k: f64,
basis: (Vec3, Vec3, Vec3),
}
impl View {
fn new(mesh: &Mesh, cam: &Camera, side: usize) -> Option<View> {
let bounds = mesh.bounds();
if bounds.is_empty() || !cam.is_valid() {
return None;
}
let radius = (bounds.diagonal() * 0.5).max(1e-9);
let half = side as f64 * 0.5;
Some(View { centre: bounds.center(), radius, half, k: (half - 1.0).max(0.5) / radius, basis: cam.basis() })
}
/// Sample x and y (y down) and depth toward the eye.
fn project(&self, v: Vec3) -> (f64, f64, f64) {
let (r, u, b) = self.basis;
let d = v - self.centre;
(self.half + d.dot(r) * self.k, self.half - d.dot(u) * self.k, d.dot(b))
}
}
/// The body seen along the camera: per sample, the nearest triangle, its depth and its shade;
/// and the visible pieces of the body's edges.
struct Raster {
/// Samples per side.
side: usize,
depth: Vec<f64>,
/// Triangle index per sample ([`NONE`]: empty).
tri: Vec<u32>,
shade: Vec<f32>,
/// Visible edge pieces: the edge's index and its ends, in samples.
edges: Vec<(usize, [f64; 2], [f64; 2])>,
}
impl Raster {
/// The triangle seen at sample (`x`, `y`).
fn at(&self, x: usize, y: usize) -> Option<usize> {
if x >= self.side || y >= self.side {
return None;
}
self.tri.get(y * self.side + x).filter(|t| **t != NONE).map(|t| *t as usize)
}
/// Nothing nearer than depth `z` at sample (`x`, `y`), within `bias`.
fn clear(&self, x: f64, y: f64, z: f64, bias: f64) -> bool {
let limit = (self.side - 1) as f64;
let (x, y) = (x.floor().clamp(0.0, limit), y.floor().clamp(0.0, limit));
self.depth.get(y as usize * self.side + x as usize).is_none_or(|d| z + bias >= *d)
}
}
/// Orthographic view of `mesh` along `cam`, its bounding sphere filling `side` samples.
fn raster(mesh: &Mesh, cam: &Camera, side: usize) -> Raster {
let side = side.clamp(1, MAX_PIXELS * SS);
let n = side * side;
let mut out = Raster { side, depth: vec![f64::NEG_INFINITY; n], tri: vec![NONE; n], shade: vec![0.0; n], edges: Vec::new() };
let Some(view) = View::new(mesh, cam, side) else { return out };
let back = view.basis.2;
// The cube's shading: a face square to the eye is the full face colour, an edge-on one 72 %.
let shade = |n: Vec3| 0.72 + 0.28 * n.dot(back).clamp(0.0, 1.0) as f32;
let limit = (side - 1) as f64;
for (i, t) in mesh.triangles.iter().enumerate() {
let Some(p) = mesh.tri(t) else { continue };
let Some(normal) = (p[1] - p[0]).cross(p[2] - p[0]).normalized() else { continue };
// A closed body shows only the triangles facing the eye.
if normal.dot(back) <= 0.0 {
continue;
}
let lit: [f32; 3] = std::array::from_fn(|j| {
shade(t.get(j).and_then(|v| mesh.normals.get(*v as usize)).copied().filter(|v| v.dot(normal) > 0.0).unwrap_or(normal))
});
let [a, b, c] = p.map(|v| view.project(v));
let area = (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0);
if !area.is_finite() || area.abs() < 1e-12 {
continue;
}
let x0 = a.0.min(b.0).min(c.0).floor().clamp(0.0, limit) as usize;
let x1 = a.0.max(b.0).max(c.0).ceil().clamp(0.0, limit) as usize;
let y0 = a.1.min(b.1).min(c.1).floor().clamp(0.0, limit) as usize;
let y1 = a.1.max(b.1).max(c.1).ceil().clamp(0.0, limit) as usize;
let edge = |p: (f64, f64, f64), q: (f64, f64, f64), x: f64, y: f64| ((q.0 - p.0) * (y - p.1) - (q.1 - p.1) * (x - p.0)) / area;
for y in y0..=y1 {
for x in x0..=x1 {
let (sx, sy) = (x as f64 + 0.5, y as f64 + 0.5);
let (w0, w1, w2) = (edge(b, c, sx, sy), edge(c, a, sx, sy), edge(a, b, sx, sy));
if w0 < 0.0 || w1 < 0.0 || w2 < 0.0 {
continue;
}
let z = w0 * a.2 + w1 * b.2 + w2 * c.2;
let s = y * side + x;
if out.depth.get(s).is_some_and(|d| z > *d) {
out.depth[s] = z;
out.tri[s] = u32::try_from(i).unwrap_or(NONE);
out.shade[s] = w0 as f32 * lit[0] + w1 as f32 * lit[1] + w2 as f32 * lit[2];
}
}
}
}
out.edges = visible_edges(mesh, &view, &out);
out
}
/// The pieces of the body's edges nothing nearer covers, stepping one sample at a time. A piece
/// is kept only when the stretch of the edge seen with it (across the edge's segments) is at least
/// two samples long: shorter is a sliver where a hidden edge meets the silhouette.
fn visible_edges(mesh: &Mesh, view: &View, r: &Raster) -> Vec<(usize, [f64; 2], [f64; 2])> {
let bias = view.radius * 0.02;
let mut out = Vec::new();
for (e, line) in mesh.edges.iter().enumerate() {
// The stretch seen so far: its pieces and their length.
let mut stretch: (Vec<(usize, [f64; 2], [f64; 2])>, f64) = (Vec::new(), 0.0);
let mut end_stretch = |stretch: &mut (Vec<(usize, [f64; 2], [f64; 2])>, f64)| {
let (pieces, length) = std::mem::take(stretch);
if length >= 2.0 {
out.extend(pieces);
}
};
for w in line.windows(2) {
let (p, q) = (view.project(w[0]), view.project(w[1]));
let steps = (q.0 - p.0).abs().max((q.1 - p.1).abs()).ceil();
if !steps.is_finite() {
continue;
}
let steps = (steps as usize).clamp(1, 4 * r.side);
let at = |s: usize| {
let f = s as f64 / steps as f64;
(p.0 + (q.0 - p.0) * f, p.1 + (q.1 - p.1) * f, p.2 + (q.2 - p.2) * f)
};
let mut run: Option<[f64; 2]> = None;
let piece = |stretch: &mut (Vec<(usize, [f64; 2], [f64; 2])>, f64), start: [f64; 2], end: [f64; 2]| {
stretch.1 += (end[0] - start[0]).hypot(end[1] - start[1]);
stretch.0.push((e, start, end));
};
for s in 0..steps {
// A step is seen when its middle is.
let (a, b) = (at(s), at(s + 1));
let mid = ((a.0 + b.0) * 0.5, (a.1 + b.1) * 0.5, (a.2 + b.2) * 0.5);
if r.clear(mid.0, mid.1, mid.2, bias) {
run.get_or_insert([a.0, a.1]);
// A stretch may go on into the next segment.
if s + 1 == steps
&& let Some(start) = run.take()
{
piece(&mut stretch, start, [b.0, b.1]);
}
} else {
if let Some(start) = run.take() {
piece(&mut stretch, start, [a.0, a.1]);
}
end_stretch(&mut stretch);
}
}
}
end_stretch(&mut stretch);
}
out
}
/// What the faces are painted with: the hovered face, the texture, and the colours used.
#[derive(Clone, Copy, PartialEq)]
struct Look {
hovered: Option<u32>,
texture: NavigatorTexture,
active: bool,
/// Cube face, cube hover, the theme's body colour and the view's background.
colours: [Color32; 4],
/// How much lighter the view draws a face under the pointer (grey levels; modeled).
lift: u8,
}
/// The hovered face's outline: the cube's accent (themed), or the view's mouse-over edge colour
/// (modeled).
fn hover_outline(texture: NavigatorTexture, cube: &Tokens, view: &Tokens) -> Color32 {
match texture {
NavigatorTexture::Themed => cube.accent,
NavigatorTexture::Modeled => view.hover_edge,
}
}
/// A colour of the body's raster: the design's own appearance, or a token, shaded or lit.
fn rgb(r: u8, g: u8, b: u8) -> Color32 {
Color32::from_rgb(r, g, b)
}
/// The colour face `face` is painted before shading.
fn face_colour(shape: &Shape, face: Option<u32>, look: &Look) -> Color32 {
let [cube_face, hover, body, background] = look.colours;
let hovered = face.is_some() && face == look.hovered;
match look.texture {
// As on the cube, the hovered target is one flat colour.
NavigatorTexture::Themed if hovered => hover,
NavigatorTexture::Themed => cube_face,
NavigatorTexture::Modeled => {
let own = shape.colour_of(face).map_or(body, |[r, g, b]| rgb(r, g, b));
if hovered {
// As the view shows a face under the pointer: its own colour, a little lighter.
let k = look.lift;
return rgb(own.r().saturating_add(k), own.g().saturating_add(k), own.b().saturating_add(k));
}
// Idle, it fades into the view as the cube does.
if look.active { own } else { own.lerp_to_gamma(background, 0.55) }
}
}
}
/// The raster's pixels: each face's colour shaded, the hovered face flat, nothing (transparent)
/// around the body.
fn compose(r: &Raster, shape: &Shape, look: &Look) -> egui::ColorImage {
let mesh = &shape.mesh;
let px = r.side / SS;
let dim = |c: Color32, s: f32| rgb((f32::from(c.r()) * s) as u8, (f32::from(c.g()) * s) as u8, (f32::from(c.b()) * s) as u8);
let mut colours: std::collections::HashMap<Option<u32>, Color32> = std::collections::HashMap::new();
let mut pixels = Vec::with_capacity(px * px);
for y in 0..px {
for x in 0..px {
let mut sum = [0.0_f32; 4];
for sy in 0..SS {
for sx in 0..SS {
let i = (y * SS + sy) * r.side + x * SS + sx;
let Some(&tri) = r.tri.get(i).filter(|t| **t != NONE) else { continue };
let face = mesh.tri_face.get(tri as usize).copied();
let base = *colours.entry(face).or_insert_with(|| face_colour(shape, face, look));
let flat = face.is_some() && face == look.hovered && look.texture == NavigatorTexture::Themed;
let colour = if flat { base } else { dim(base, r.shade.get(i).copied().unwrap_or(1.0)) };
for (acc, v) in sum.iter_mut().zip([colour.r(), colour.g(), colour.b(), 255]) {
*acc += f32::from(v);
}
}
}
let n = (SS * SS) as f32;
// Premultiplied: the average of the covered samples, each fully opaque.
pixels.push(Color32::from_rgba_premultiplied((sum[0] / n) as u8, (sum[1] / n) as u8, (sum[2] / n) as u8, (sum[3] / n) as u8));
}
}
egui::ColorImage::new([px, px], pixels)
}
/// Per face seen, the sample nearest the middle of its samples: where automation finds it.
fn face_samples(r: &Raster, mesh: &Mesh) -> Vec<(u32, usize)> {
use std::collections::BTreeMap;
let face = |t: &u32| mesh.tri_face.get(*t as usize).copied();
let xy = |i: usize| ((i % r.side) as f64, (i / r.side) as f64);
let mut sums: BTreeMap<u32, (f64, f64, f64)> = BTreeMap::new();
for (i, t) in r.tri.iter().enumerate() {
if let Some(f) = face(t) {
let (x, y) = xy(i);
let e = sums.entry(f).or_default();
*e = (e.0 + x, e.1 + y, e.2 + 1.0);
}
}
let mut best: BTreeMap<u32, (f64, usize)> = BTreeMap::new();
for (i, t) in r.tri.iter().enumerate() {
let Some(f) = face(t) else { continue };
let Some((sx, sy, n)) = sums.get(&f) else { continue };
let (x, y) = xy(i);
let d = (x - sx / n).powi(2) + (y - sy / n).powi(2);
let e = best.entry(f).or_insert((f64::INFINITY, i));
if d < e.0 {
*e = (d, i);
}
}
best.into_iter().map(|(f, (_, i))| (f, i)).collect()
}
/// The last raster and its texture, kept while the view, body and size stay the same.
struct Cache {
shape: u64,
basis: (Vec3, Vec3, Vec3),
side: usize,
raster: Raster,
faces: Vec<(u32, usize)>,
look: Option<Look>,
texture: Option<egui::TextureHandle>,
}
/// One cache per egui context, kept in its memory.
type Shared = Arc<Mutex<Option<Cache>>>;
/// Draw the custom navigator as `shown` says (the panel's choices while it is open).
pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, shown: crate::view_gizmo::Shown) {
let Some(shape) = shown.shape else { return navigation_cube::show(app, ui, rect) };
let outer = axis_rect(app, rect);
if !outer.is_positive() {
app.viewport.axis_drag = None;
crate::scenario::publish_count("axis_view_highlights", 0.0);
return;
}
crate::scenario::publish_rect("axis_view:outer", outer);
let (c, radius, scale) = disc(app, rect);
let orbiting = axis_view_orbit(app, ui, rect);
let active = orbiting || ui.rect_contains_pointer(outer);
let t = Tokens::get().navigation_cube(active);
crate::scenario::publish_count("navigation_cube:active", f64::from(u8::from(active)));
let ppp = ui.ctx().pixels_per_point();
let px = ((2.0 * radius * ppp).ceil().max(1.0) as usize).min(MAX_PIXELS);
let side = px * SS;
let image = Rect::from_center_size(c, vec2(px as f32, px as f32) / ppp);
let step = image.width() / side as f32;
let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| ui.is_enabled() && ui.rect_contains_pointer(rect) && !crate::shell::covered(app, *p));
let mesh = &shape.mesh;
let key = (shape.id, app.cam.basis());
let cam = app.cam;
let texture = shown.texture;
// The model's own look: its body colour and its edge colour, as the view draws them.
let view = Tokens::view();
let to_screen = |p: [f64; 2]| image.min + vec2(p[0] as f32 * step, p[1] as f32 * step);
let painter = ui.painter_at(outer);
let shared: Shared = ui.ctx().data_mut(|d| d.get_temp_mut_or_default::<Shared>(egui::Id::new("body_gizmo_cache")).clone());
let (hovered, handles) = shared
.lock()
.ok()
.and_then(|mut cell| {
if !cell.as_ref().is_some_and(|k| (k.shape, k.basis) == key && k.side == side) {
let texture = cell.take().and_then(|k| k.texture);
let raster = raster(mesh, &cam, side);
let faces = face_samples(&raster, mesh);
*cell = Some(Cache { shape: key.0, basis: key.1, side, raster, faces, look: None, texture });
}
let cache = cell.as_mut()?;
let tri = hover.filter(|_| !orbiting).and_then(|p| {
let s = (p - image.min) / step;
(s.x >= 0.0 && s.y >= 0.0).then(|| cache.raster.at(s.x as usize, s.y as usize)).flatten()
});
let face = tri.and_then(|t| mesh.tri_face.get(t).copied());
let hover_outline = hover_outline(texture, &t, &view);
let look = Look {
hovered: face,
texture,
active,
colours: [t.cube_face, t.cube_hover, view.body, view.viewport_top],
lift: view.hover_face_lift,
};
if cache.look != Some(look) || cache.texture.is_none() {
let img = compose(&cache.raster, &shape, &look);
match cache.texture.as_mut() {
Some(tex) => tex.set(img, egui::TextureOptions::LINEAR),
None => cache.texture = Some(ui.ctx().load_texture("body_gizmo", img, egui::TextureOptions::LINEAR)),
}
cache.look = Some(look);
}
if let Some(tex) = &cache.texture {
painter.image(tex.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
// The body's edges in the cube's border colour; the hovered face's in the accent, on top.
let of_hovered = |e: usize| face.is_some_and(|f| mesh.edge_faces.get(e).is_some_and(|fs| fs.contains(&f)));
for lit in [false, true] {
for (_, a, b) in cache.raster.edges.iter().filter(|(e, _, _)| of_hovered(*e) == lit) {
let edge = match texture {
NavigatorTexture::Themed => t.cube_border,
// Idle, the model's edges fade into the view with its faces.
NavigatorTexture::Modeled if active => view.body_edge,
NavigatorTexture::Modeled => view.body_edge.lerp_to_gamma(view.viewport_top, 0.55),
};
painter.line_segment([to_screen(*a), to_screen(*b)], Stroke::new(1.0, if lit { hover_outline } else { edge }));
}
}
let w = cache.raster.side;
let handles: Vec<(u32, Pos2)> = cache.faces.iter().map(|(f, i)| (*f, to_screen([(i % w) as f64 + 0.5, (i / w) as f64 + 0.5]))).collect();
Some((tri, handles))
})
.unwrap_or((None, Vec::new()));
for (face, at) in &handles {
crate::scenario::publish_handle(&format!("body_gizmo:face:{face}"), *at);
}
crate::scenario::publish_count("body_gizmo:faces", handles.len() as f64);
crate::scenario::publish_count("axis_view_highlights", f64::from(u8::from(hovered.is_some())));
if let Some(tri) = hovered {
crate::scenario::publish_count("body_gizmo:hovered", f64::from(mesh.tri_face.get(tri).copied().unwrap_or_default()));
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
if ui.input(|i| i.pointer.primary_clicked())
&& let Some(normal) = shape.face_normal(tri)
{
navigation_cube::navigate(app, None, Some(app.cam.to_frame(normal)));
}
}
if shown.arrows {
navigation_cube::arrows(app, ui, &painter, c, scale, active, false, t);
}
if shown.home {
navigation_cube::home(app, ui, &painter, c, scale, active, t);
}
}
#[cfg(test)]
mod tests {
use super::*;
use solidcraft_engine::render::{StandardView, UpAxis};
fn boxed() -> crate::scenario::Harness {
let mut h = crate::scenario::Harness::new();
h.app.preferences.look_at_anim = false;
h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 10})).unwrap();
h.frames(2);
h
}
fn body_name(h: &crate::scenario::Harness) -> String {
h.app.session.world_state().unwrap().bodies[0].name.clone()
}
fn custom(h: &mut crate::scenario::Harness) {
h.call("ui.prefs", json!({"navigator_style": "custom"}));
let name = body_name(h);
h.app.run("view.navigator", json!({"body": name})).unwrap();
h.frames(2);
}
#[test]
fn raster_hides_back_faces_and_sees_the_top_from_above() {
let h = boxed();
let shape = Shape::of_body(&h.app.session, &body_name(&h)).unwrap();
let mesh = &shape.mesh;
for up in [UpAxis::Z, UpAxis::Y] {
let mut cam = Camera { up, ..Default::default() };
cam.set_view(StandardView::Top);
let r = raster(mesh, &cam, 64);
let tri = r.at(32, 32).expect("the box covers the middle");
let p = mesh.tri(&mesh.triangles[tri]).unwrap();
let n = (p[1] - p[0]).cross(p[2] - p[0]).normalized().unwrap();
assert!(n.dot(cam.back()) > 0.99, "{up:?}: the face seen from above faces the eye: {n:?}");
assert!(r.at(0, 0).is_none(), "the corner of the raster is empty");
}
// Isometric: three faces show, never more, and nine of the box's twelve edges.
let r = raster(mesh, &Camera::default(), 128);
let faces: std::collections::BTreeSet<u32> = r.tri.iter().filter_map(|t| mesh.tri_face.get(*t as usize).copied()).collect();
assert_eq!(faces.len(), 3, "{faces:?}");
let edges: std::collections::BTreeSet<usize> = r.edges.iter().map(|(e, _, _)| *e).collect();
assert_eq!(edges.len(), 9, "the three hidden edges stay hidden: {edges:?}");
}
#[test]
fn hostile_raster_sizes_and_cameras_never_panic() {
let h = boxed();
let shape = Shape::of_body(&h.app.session, &body_name(&h)).unwrap();
let look = Look { hovered: Some(0), texture: NavigatorTexture::Modeled, active: false, colours: [Color32::WHITE; 4], lift: u8::MAX };
for side in [0, 1, 2, 3, usize::MAX] {
let r = raster(&shape.mesh, &Camera::default(), side);
assert!(r.side >= 1 && r.side <= MAX_PIXELS * SS);
let _ = compose(&r, &shape, &look);
}
let bad = Camera { distance: f64::NAN, ..Default::default() };
assert!(raster(&shape.mesh, &bad, 16).tri.iter().all(|t| *t == NONE));
let empty = raster(&Mesh::default(), &Camera::default(), 16);
assert!(empty.tri.iter().all(|t| *t == NONE) && empty.edges.is_empty());
}
#[test]
fn hovering_a_face_highlights_it_and_a_click_looks_straight_at_it() {
let mut h = boxed();
custom(&mut h);
let design = h.app.session.doc.to_json();
let mut seen = 0;
for face in 0..6_u32 {
h.call("ui.view", json!({"view": "iso"}));
let Some(p) = crate::scenario::handle_at(&format!("body_gizmo:face:{face}")) else { continue };
seen += 1;
h.call("ui.move", json!({"x": p.x, "y": p.y}));
assert_eq!(crate::scenario::count_of("axis_view_highlights"), Some(1.0));
assert_eq!(crate::scenario::count_of("body_gizmo:hovered"), Some(f64::from(face)));
h.call("ui.click", json!({"x": p.x, "y": p.y}));
let (_, n) = crate::dialogs::planar_face(&h.app.session, &body_name(&h), face as usize).expect("box faces are planar");
let back = h.app.cam.back();
assert!(back.dist(n) < 1e-6, "face {face}: the view looks along its normal {n:?}, not {back:?}");
}
assert_eq!(seen, 3, "three faces of the box show in the isometric view");
assert_eq!(h.app.session.doc.to_json(), design, "looking at a face never edits the design");
assert!(h.app.session.selection.is_empty());
}
#[test]
fn the_rotation_arrows_and_home_follow_their_settings_and_turn_the_view() {
let mut h = boxed();
custom(&mut h);
assert!(crate::scenario::handle_at("navigation_cube:control:left").is_some(), "arrows by default");
assert!(crate::scenario::handle_at("navigation_cube:control:home").is_some(), "Home by default");
h.app.run("view.navigator", json!({"arrows": false, "home": false})).unwrap();
h.frames(2);
assert!(crate::scenario::handle_at("navigation_cube:control:left").is_none(), "arrows off");
assert!(crate::scenario::handle_at("navigation_cube:control:home").is_none(), "Home off");
h.app.run("view.navigator", json!({"arrows": true, "home": true})).unwrap();
h.frames(2);
let p = crate::scenario::handle_at("navigation_cube:control:clockwise").expect("the roll arrows are there");
let camera = h.app.cam;
h.call("ui.click", json!({"x": p.x, "y": p.y}));
assert!((h.app.cam.roll - camera.roll - std::f64::consts::FRAC_PI_2).abs() < 1e-6);
let p = crate::scenario::handle_at("navigation_cube:control:home").expect("Home is there");
h.call("ui.click", json!({"x": p.x, "y": p.y}));
assert!(h.app.cam.back().dist(Camera::default().back()) < 1e-6, "Home turns to the home view");
assert!(crate::scenario::handle_at("navigation_cube:control:fit").is_none(), "Fit stays the cube's");
}
#[test]
fn modeled_texture_paints_the_body_in_its_own_colour_and_themed_in_the_cubes() {
let mut h = boxed();
let name = body_name(&h);
let mut shape = Shape::of_body(&h.app.session, &name).unwrap();
shape.colour = Some([200, 30, 40]);
let r = raster(&shape.mesh, &Camera::default(), 64);
let t = Tokens::light();
let look = |texture| Look {
hovered: None,
texture,
active: true,
colours: [t.cube_face, t.cube_hover, t.body, t.viewport_top],
lift: t.hover_face_lift,
};
assert_ne!(t.body_edge, t.cube_border, "the two textures' edges can be told apart");
// A hovered face: the cube's hover colours when themed, the view's mouse-over when modeled.
assert_eq!(hover_outline(NavigatorTexture::Themed, &t, &t), t.accent);
assert_eq!(hover_outline(NavigatorTexture::Modeled, &t, &t), t.hover_edge);
assert!(t.hover_face_lift > 0);
// The pixel over the middle of one face seen, hovered.
let (face, sample) = face_samples(&r, &shape.mesh)[0];
let at = (sample / r.side / SS) * (r.side / SS) + sample % r.side / SS;
let modeled = look(NavigatorTexture::Modeled);
let (plain, lit) = (compose(&r, &shape, &modeled).pixels[at], compose(&r, &shape, &Look { hovered: Some(face), ..modeled }).pixels[at]);
assert!(
lit.r() > plain.r() && lit.g() > plain.g() && lit.b() > plain.b(),
"the hovered face is lifted as the view lifts it: {plain:?} → {lit:?}"
);
assert_ne!(lit, t.sel_face, "not the selection colour");
let middle = |img: &egui::ColorImage| img.pixels[img.size[1] / 2 * img.size[0] + img.size[0] / 2];
let red = middle(&compose(&r, &shape, &look(NavigatorTexture::Modeled)));
assert!(red.r() > red.g() * 3 && red.r() > red.b() * 3, "the body's red: {red:?}");
let themed = middle(&compose(&r, &shape, &look(NavigatorTexture::Themed)));
let shade = f32::from(themed.r()) / f32::from(t.cube_face.r().max(1));
assert!((0.7..=1.01).contains(&shade), "the cube's face colour, shaded: {themed:?}");
// The gizmo draws without a frame failing in both textures.
custom(&mut h);
for texture in ["modeled", "themed"] {
h.app.run("view.navigator", json!({"texture": texture})).unwrap();
h.frames(2);
assert!(crate::scenario::count_of("body_gizmo:faces").is_some_and(|n| n >= 3.0), "{texture}");
}
}
#[test]
fn custom_without_a_body_draws_the_cube() {
let mut h = boxed();
h.call("ui.prefs", json!({"navigator_style": "custom"}));
h.frames(2);
assert!(crate::scenario::handle_at("navigation_cube:front").is_some() || crate::scenario::handle_at("navigation_cube:top").is_some());
assert_eq!(crate::scenario::count_of("body_gizmo:faces"), None);
}
}
@@ -145,6 +145,11 @@ fn analysis_colours_reach_the_shader_in_its_order() {
const ALLOWED_LITERALS: &[(&str, usize, &str)] = &[
("navigation.rs", 1, "the navigation cube's face shading, made from a token"),
("canvas.rs", 3, "white rings around manipulator handles"),
(
"body_gizmo.rs",
3,
"the custom view navigator's raster: the design's appearance and tokens, shaded, as pixels, drawn with the white image tint",
),
("context_menu.rs", 1, "the radial menu's shadow"),
("dialogs_appearance.rs", 1, "a design appearance: the colour is the fact"),
("dialogs_save_mesh.rs", 1, "an installed slicer's own icon, drawn untinted"),
+12
View File
@@ -88,6 +88,8 @@ pub enum Target {
HistoryControls,
/// The workspace switcher.
Workspace,
/// The view gizmo (axes, cube or a custom body) at the viewport's corner.
ViewGizmo,
/// The Named Views folder, and one view (saved or standard) in it.
NamedViews,
NamedView {
@@ -403,6 +405,7 @@ pub fn items(app: &SolveApp, target: &Target) -> Vec<Item> {
Target::PointCloud { id } => crate::browser::point_cloud_items(app, *id),
Target::Origin => crate::browser::origin_items(app),
Target::NamedViews => vec![act("ui.newView", "New Named View", "perspective")],
Target::ViewGizmo => crate::view_gizmo::menu_items(app),
Target::Section => crate::browser::section_items(app),
Target::Joint { id } => joint_items(app, *id),
Target::ToolbarCommand { id } => crate::toolbar_custom::command_items(app, id),
@@ -1705,6 +1708,11 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {
"ui.toolbarPin" | "ui.toolbarRemove" | "ui.toolbarReset" | "ui.toolbarCustomize" | "ui.toolbarTab" | "ui.shortcutPin" => {
crate::toolbar_custom::run(app, &item.id, &p)
}
"ui.navigatorStyle" => {
if let Some(style) = p.get("style").and_then(|s| serde_json::from_value(s.clone()).ok()) {
crate::view_gizmo::pick_style(app, style);
}
}
"ui.navPreset" => {
// Picked here, a preset sets what Preferences › Navigation sets for it.
if let Some(preset) = crate::prefs::NAV_PRESETS.iter().find(|preset| p.get("preset").and_then(Value::as_str) == Some(preset.id)) {
@@ -2107,7 +2115,11 @@ fn in_selection(app: &SolveApp, sel: &Sel) -> bool {
/// Open the viewport menu at a screen position. A right-click on something not selected
/// selects it first, so the menu is about what is under the cursor; a face or edge already in a
/// multi-selection keeps the whole selection (#3733), as does one of a selected body (#5849). `held`: the keys held at that click.
/// On the view gizmo it opens the gizmo's own menu and leaves the selection alone.
pub fn open(app: &mut SolveApp, at: Pos2, held: crate::tool_modifiers::Held) {
if crate::viewport::view_gizmo_at(app, at) {
return open_for(app, at, Target::ViewGizmo);
}
app.menu.opened = Some((at, held));
app.menu.picked = None;
let before = app.session.selection.clone();
+8 -1
View File
@@ -390,6 +390,8 @@ crate::dialog_descriptor::dialog_descriptors! {
/// Surface tools and Split Face (`dialogs_surface`).
Surface(crate::dialogs_surface::Surf),
SaveMesh(crate::dialogs_save_mesh::SaveMesh),
/// The Custom View Navigator panel (`view_gizmo`): the app's navigator, not the design.
ViewNavigator(crate::view_gizmo::Form),
ViewDxf {
dashed: bool,
tolerance: f64,
@@ -1104,6 +1106,7 @@ impl Dialog {
.or_else(|| crate::dialogs_surface::start(app, id))
.or_else(|| crate::dialogs_save_mesh::start(app, id))
.or_else(|| crate::dialogs_view_dxf::start(app, id))
.or_else(|| crate::view_gizmo::start(app, id))
.or_else(|| crate::dialogs_plastic::start(app, id))
.or_else(|| crate::dialogs_frame::start(app, id))
.or_else(|| crate::dialogs_appearance::start(app, id))
@@ -2566,6 +2569,7 @@ fn title(k: &Kind) -> &'static str {
Kind::Surface(k) => k.title(),
Kind::SaveMesh(_) => "SAVE AS MESH",
Kind::ViewDxf { .. } => "Export Current View as DXF",
Kind::ViewNavigator(_) => "CUSTOM VIEW NAVIGATOR",
Kind::InsertDrawing(p) => crate::dialogs_insert_drawing::title(p),
Kind::Plastic(k) => k.title(),
Kind::Frame(_) => "FRAME MEMBER",
@@ -4554,6 +4558,9 @@ pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> {
if let Kind::ViewDxf { dashed, tolerance } = &d.kind {
return crate::dialogs_view_dxf::run(app, *dashed, *tolerance);
}
if let Kind::ViewNavigator(form) = &d.kind {
return crate::view_gizmo::run_dialog(app, form, &d.inputs);
}
// Saving asks for a file name first; `Err("")` is the user backing out of that.
if let Kind::SaveMesh(k) = &d.kind {
return crate::dialogs_save_mesh::run(app, k, &d.inputs);
@@ -5624,7 +5631,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
Kind::Surface(k) => return crate::dialogs_surface::commands(app, k, &d.inputs, &d.extra),
Kind::SketchModify(k) => return crate::sketch_modify_ui::commands(app, k, &d.inputs, &d.extra),
Kind::SaveMesh(k) => return crate::dialogs_save_mesh::commands(k, &d.inputs),
Kind::ViewDxf { .. } => return Ok(Vec::new()),
Kind::ViewDxf { .. } | Kind::ViewNavigator(_) => return Ok(Vec::new()),
Kind::InsertDrawing(p) => return crate::dialogs_insert_drawing::commands(p),
Kind::Plastic(k) => return crate::dialogs_plastic::commands(app, k, &d.inputs, &d.extra),
Kind::Frame(k) => return crate::dialogs_frame::commands(app, k, &d.inputs, &d.extra),
+2
View File
@@ -18,6 +18,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> {
Kind::PartSize(_) => Some("parts.resize"),
Kind::SaveMesh(k) => Some(crate::dialogs_save_mesh::command_id(k)),
Kind::ViewDxf { .. } => Some("file.export_view_dxf"),
Kind::ViewNavigator(_) => Some("view.navigator"),
Kind::InsertDrawing(p) => Some(if p.command.ends_with("dxf") { "sketch.insert_dxf" } else { "sketch.insert_svg" }),
Kind::Sketch => Some("sketch.create"),
Kind::SketchIntersect { .. } => Some("sketch.intersect"),
@@ -393,6 +394,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
Kind::PartSize(k) => enter |= crate::dialogs_part_size::rows(app, ui, k),
Kind::SaveMesh(k) => enter |= crate::dialogs_save_mesh::rows(app, ui, k, &mut d.inputs),
Kind::ViewDxf { dashed, tolerance } => crate::dialogs_view_dxf::rows(app, ui, dashed, tolerance),
Kind::ViewNavigator(form) => crate::view_gizmo::rows(app, ui, form, &d.inputs),
Kind::InsertDrawing(p) => crate::dialogs_insert_drawing::rows(ui, p),
Kind::Sketch => {
if d.error.is_some() && matches!(d.inputs.first().and_then(|i| i.items.first()), Some(Sel::Face { .. })) {
+1
View File
@@ -41,6 +41,7 @@ fn take(app: &SolveApp, out: &mut BTreeSet<String>) {
Target::HistoryControls,
Target::Workspace,
Target::NamedViews,
Target::ViewGizmo,
Target::InsertDesign,
Target::VisualStyle,
Target::ViewTool,
+8
View File
@@ -314,6 +314,7 @@ pub mod update;
mod value_step;
pub(crate) mod view_angles;
mod view_confirm;
pub mod view_gizmo;
pub mod view_pick;
pub mod viewport;
mod viewport_details;
@@ -529,6 +530,8 @@ pub struct SolveApp {
pub cam: Camera,
/// A view change in progress (axis view, Home, Fit); any mouse navigation cancels it.
pub cam_anim: Option<CameraAnim>,
/// The custom view navigator's body (kept with the preferences).
pub view_gizmo: view_gizmo::State,
/// Seconds since start, as of this frame.
pub now: f64,
/// The views around opening the open sketch. Leaving it goes back to the earlier one as the
@@ -805,6 +808,7 @@ impl SolveApp {
shell: Default::default(),
cam: Camera::default(),
cam_anim: None,
view_gizmo: view_gizmo::State::default(),
now: 0.0,
pre_sketch_cam: None,
pre_extrude_cam: None,
@@ -1054,6 +1058,7 @@ impl SolveApp {
"agent_cursor": self.ui.agent_cursor,
"recent_colors": self.ui.recent_colors,
"preferences": self.preferences,
"view_gizmo": self.view_gizmo.stored(),
"gpu_path_setup_seconds": self.render_workspace.setup_seconds,
});
// While the Preferences dialog is open the file holds what Cancel would restore: a change
@@ -1135,6 +1140,7 @@ impl SolveApp {
if let Some(p) = v.get("settings_profiles") {
self.settings_profiles.load(p);
}
self.view_gizmo.load(v.get("view_gizmo"));
if let Some(mut p) = v.get("preferences").filter(|p| p.is_object()).map(prefs::lenient) {
if !prefs::MSAA.contains(&p.msaa) {
p.msaa = prefs::Prefs::default().msaa;
@@ -1424,6 +1430,8 @@ impl SolveApp {
// Settings profiles live in the app: the engine only checked the parameters.
let r = match r {
Ok(v) if id.starts_with("settings.profile.") => settings_profiles::command(self, id, &v),
// The view navigator is the app's too.
Ok(v) if id == "view.navigator" => view_gizmo::command(self, &v),
r => r,
};
self.finish_command(id, &r);
+1
View File
@@ -1576,6 +1576,7 @@ fn every_context_target_has_identified_icon_rows_including_submenus() {
Target::HistoryControls,
Target::Workspace,
Target::NamedViews,
Target::ViewGizmo,
Target::NamedView { name: "Top".into() },
Target::Canvas { id: 1 },
Target::Section,
+41 -22
View File
@@ -153,7 +153,7 @@ pub(super) fn drag_origin(app: &SolveApp, centre: Pos2, pointer: Pos2, scale: f3
hit(&facets(&camera(app), centre, HALF * f64::from(scale)), pointer).is_some()
}
fn navigate(app: &mut SolveApp, action: Option<&str>, dir: Option<Vec3>) {
pub(super) fn navigate(app: &mut SolveApp, action: Option<&str>, dir: Option<Vec3>) {
// Same as arrow-key steps (#8912): turn from where a glide in flight is going, so rapid
// clicks add full turns instead of restarting from a mid-animation camera.
let from = app.cam_anim.map_or(app.cam, |a| a.to);
@@ -178,6 +178,13 @@ fn control(app: &mut SolveApp, ui: &mut egui::Ui, bounds: Rect, action: &str, to
if response.clicked() {
navigate(app, Some(action), None);
}
// The control takes the right-click from the viewport under it: open the gizmo's menu.
if response.secondary_clicked()
&& app.dialog.is_none()
&& let Some(at) = response.interact_pointer_pos()
{
crate::context_menu::open_for(app, at, crate::context_menu::Target::ViewGizmo);
}
hover
}
@@ -263,6 +270,37 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) {
}
}
let square_on = faces.iter().filter(|f| f.text_axes.is_some()).count() == 1;
arrows(app, ui, &painter, c, scale, active, square_on, t);
home(app, ui, &painter, c, scale, active, t);
let fit = Rect::from_center_size(c + vec2(67.0, 67.0) * scale, vec2(22.0, 22.0) * scale);
let fit_hover = control(app, ui, fit, "fit", "Fit model in view");
if active {
painter.circle(fit.center(), 6.0 * scale, if fit_hover { t.accent_soft } else { t.cube_face }, Stroke::new(1.0, t.cube_border));
}
// Small world-axis triad below the cube; it follows the selected up-axis frame.
let origin = c + vec2(-60.0, 52.0) * scale;
for (d, color, label) in [(Vec3::X, t.axis_x, "X"), (Vec3::Y, t.axis_y, "Y"), (Vec3::Z, t.axis_z, "Z")] {
let (r, u, _) = app.cam.basis();
let tip = origin + vec2((d.dot(r) * 17.0) as f32, -(d.dot(u) * 17.0) as f32) * scale;
painter.line_segment([origin, tip], Stroke::new(1.5, color));
painter.text(tip, Align2::CENTER_CENTER, label, FontId::proportional(crate::theme::Tokens::get().font_triad), color);
}
}
/// The Home button at the top left of a gizmo centred at `c`, painted while it is `active`.
pub(super) fn home(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, c: Pos2, scale: f32, active: bool, t: Tokens) {
let home = Rect::from_center_size(c + vec2(-65.0, -65.0) * scale, vec2(26.0, 26.0) * scale);
crate::scenario::publish_target("axis_view:home", home);
let home_hover = control(app, ui, home, "home", "Home: isometric view and fit model");
if active {
icons::paint_icon(painter, home.shrink(4.0 * scale), "home", f32::from((if home_hover { t.accent } else { t.cube_face }).a()) / 255.0);
}
}
/// The four orbit arrows and the two roll arrows around a gizmo centred at `c`: nearer and larger
/// while a cube face is square on, painted while the gizmo is `active`.
#[allow(clippy::too_many_arguments)]
pub(super) fn arrows(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, c: Pos2, scale: f32, active: bool, square_on: bool, t: Tokens) {
let (distance, button_size) = if square_on { (54.0, 20.0) } else { (74.0, 16.0) };
for (action, offset, direction, tooltip) in [
("left", vec2(-distance, 0.0), vec2(1.0, 0.0), "Orbit left 90°"),
@@ -285,7 +323,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) {
let at = c + offset * scale;
let hovered = control(app, ui, Rect::from_center_size(at, vec2(button_size, button_size) * scale), action, tooltip);
if active {
arrow(&painter, at, direction * scale, hovered, t);
arrow(painter, at, direction * scale, hovered, t);
}
}
for (action, offset, size, clockwise, tooltip) in [
@@ -298,28 +336,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) {
};
let hovered = control(app, ui, Rect::from_center_size(c + offset * scale, size * scale), action, tooltip);
if active {
curved_arrow(&painter, c + vec2(42.0, -42.0) * scale, clockwise, hovered, t, scale);
curved_arrow(painter, c + vec2(42.0, -42.0) * scale, clockwise, hovered, t, scale);
}
}
let home = Rect::from_center_size(c + vec2(-65.0, -65.0) * scale, vec2(26.0, 26.0) * scale);
crate::scenario::publish_target("axis_view:home", home);
let home_hover = control(app, ui, home, "home", "Home: isometric view and fit model");
if active {
icons::paint_icon(&painter, home.shrink(4.0 * scale), "home", f32::from((if home_hover { t.accent } else { t.cube_face }).a()) / 255.0);
}
let fit = Rect::from_center_size(c + vec2(67.0, 67.0) * scale, vec2(22.0, 22.0) * scale);
let fit_hover = control(app, ui, fit, "fit", "Fit model in view");
if active {
painter.circle(fit.center(), 6.0 * scale, if fit_hover { t.accent_soft } else { t.cube_face }, Stroke::new(1.0, t.cube_border));
}
// Small world-axis triad below the cube; it follows the selected up-axis frame.
let origin = c + vec2(-60.0, 52.0) * scale;
for (d, color, label) in [(Vec3::X, t.axis_x, "X"), (Vec3::Y, t.axis_y, "Y"), (Vec3::Z, t.axis_z, "Z")] {
let (r, u, _) = app.cam.basis();
let tip = origin + vec2((d.dot(r) * 17.0) as f32, -(d.dot(u) * 17.0) as f32) * scale;
painter.line_segment([origin, tip], Stroke::new(1.5, color));
painter.text(tip, Align2::CENTER_CENTER, label, FontId::proportional(crate::theme::Tokens::get().font_triad), color);
}
}
#[cfg(test)]
+23 -1
View File
@@ -608,19 +608,35 @@ pub enum NavigatorStyle {
#[default]
Axes,
Cube,
/// A body of the user's choice, drawn the cube's size ([`crate::view_gizmo`]); the cube
/// until one is chosen.
Custom,
}
impl NavigatorStyle {
pub const ALL: [Self; 2] = [Self::Axes, Self::Cube];
pub const ALL: [Self; 3] = [Self::Axes, Self::Cube, Self::Custom];
pub fn label(self) -> &'static str {
match self {
Self::Axes => "Signed axes",
Self::Cube => "Cube",
Self::Custom => "Custom",
}
}
}
/// How the custom view gizmo colours its body.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NavigatorTexture {
/// The navigation cube's colours. Also what a value this version doesn't know reads as
/// (`lenient`).
#[default]
Themed,
/// The body's own appearance, as the viewport shows it.
Modeled,
}
/// How the History at the left lists sketches (Preferences: "Sketches", #6489). The timeline
/// along the bottom always keeps the creation order.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -1045,6 +1061,12 @@ preference_settings! {
right_drag_orbits: bool = true, PAGE_NAVIGATION => check_tr("nav.right_drag_orbits.label");
/// View orientation widget: original signed axes (default) or compact cube.
navigator_style: NavigatorStyle = NavigatorStyle::default(), PAGE_NAVIGATION;
/// The custom view gizmo's colours: the cube's (themed) or the body's own (modeled).
navigator_texture: NavigatorTexture = NavigatorTexture::default(), PAGE_NAVIGATION;
/// The custom view gizmo has the cube's orbit and roll arrows around it.
navigator_arrows: bool = true, PAGE_NAVIGATION;
/// The custom view gizmo has the cube's Home button beside it.
navigator_home: bool = true, PAGE_NAVIGATION;
/// Show the radial ring and enable hold/flick gestures for viewport context menus.
radial_context_menu: bool = false, PAGE_NAVIGATION => check("Radial context menu");
/// Work on the model directly in the viewport (pull a face to extrude or cut); off by default.
+10 -4
View File
@@ -275,20 +275,26 @@ fn view(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
let options = [
ui_kit::PictureChoice { key: "Signed axes", label: app.tr("prefs.navigation.axes_signed"), figure: ui_kit::paint_navigation_axes },
ui_kit::PictureChoice { key: "Cube", label: app.tr("prefs.navigation.cube_compact"), figure: ui_kit::paint_navigation_cube },
ui_kit::PictureChoice { key: "Custom", label: crate::i18n::tr_label("Custom"), figure: ui_kit::paint_navigation_custom },
];
if let Some(index) = ui_kit::settings_picture_choices_sized(
ui,
"navigator",
app.tr("View navigator"),
&options,
usize::from(app.preferences.navigator_style == NavigatorStyle::Cube),
NavigatorStyle::ALL.iter().position(|s| *s == app.preferences.navigator_style).unwrap_or_default(),
true,
ui_kit::PictureChoiceSize { width: t.space_24 * 8.0 - t.space_2, aspect: 178.0 / 115.0, caption: true },
) {
app.preferences.navigator_style = if index == 0 { NavigatorStyle::Axes } else { NavigatorStyle::Cube };
app.preferences.navigator_style = NavigatorStyle::ALL.get(index).copied().unwrap_or_default();
}
if let (Some(a), Some(b)) = (crate::scenario::rect_of("prefs:navigator:Signed axes"), crate::scenario::rect_of("prefs:navigator:Cube")) {
crate::scenario::publish_target("prefs:navigator", a.union(b));
if let Some(all) = ["Signed axes", "Cube", "Custom"]
.into_iter()
.map(|key| crate::scenario::rect_of(&format!("prefs:navigator:{key}")))
.collect::<Option<Vec<_>>>()
.and_then(|rects| rects.into_iter().reduce(egui::Rect::union))
{
crate::scenario::publish_target("prefs:navigator", all);
}
setting::look_at_anim(app, ui);
let width =
+2 -1
View File
@@ -2607,7 +2607,8 @@ fn render_workspace_view_keys_double_middle_click_and_navigators_work() {
off(&mut h);
let handle = match style {
crate::prefs::NavigatorStyle::Axes => "axis_view:home",
crate::prefs::NavigatorStyle::Cube => "navigation_cube:control:home",
// Custom draws the cube until a body is chosen.
crate::prefs::NavigatorStyle::Cube | crate::prefs::NavigatorStyle::Custom => "navigation_cube:control:home",
};
h.step(&json!({"click":{"handle":handle}})).unwrap();
h.settle();
+39 -6
View File
@@ -1,8 +1,9 @@
//! Settings profiles (#6237): the input and interface settings kept together under a name, such
//! as "Laptop" and "Large monitor", and switched at once. A profile holds the original Interface,
//! Navigation and Sketch preference keys and the language, keyboard shortcuts, toolbar,
//! S box favourites, and imported theme it uses. Page moves preserve that stored key set;
//! device-specific 3D mouse keys, graphics, recent files and Assistant settings stay out.
//! S box favourites, imported theme it uses, and the custom view navigator's texture, arrows and
//! Home, and its body (when one is chosen; a profile without one leaves the current body alone). Page moves preserve that stored
//! key set; device-specific 3D mouse keys, graphics, recent files and Assistant settings stay out.
//!
//! A profile is kept, exported and imported as one `solidcraft-profile/1` document. Every
//! document is checked by [`sanitize`] first: unknown keys are dropped, sizes are capped, and a
@@ -240,7 +241,7 @@ pub fn capture(app: &SolveApp, name: &str) -> Value {
let all = serde_json::to_value(&app.preferences).unwrap_or_default();
let preferences: Map<String, Value> = keys().filter_map(|key| Some((key.to_string(), all.get(key)?.clone()))).collect();
let themes: Vec<Value> = app.preferences.custom_themes.iter().filter(|t| t.id == app.preferences.theme).map(theme_document).collect();
json!({
let mut doc = json!({
"format": FORMAT,
"name": name,
"preferences": preferences,
@@ -248,7 +249,17 @@ pub fn capture(app: &SolveApp, name: &str) -> Value {
"favourites": app.sbox.pinned,
"toolbar": app.toolbar_custom.prefs(),
"themes": themes,
})
});
// The custom view navigator's own settings ride in their own entry: they are newer than the
// profile key set above, which never changes.
if let Some(o) = doc.as_object_mut() {
o.insert("view_navigator".into(), crate::view_gizmo::profile_settings(app));
}
let gizmo = app.view_gizmo.stored();
if let Some(o) = doc.as_object_mut().filter(|_| gizmo.is_object()) {
o.insert("view_gizmo".into(), gizmo);
}
doc
}
/// An imported theme as a theme file that also keeps the id the profile's `theme` names.
@@ -322,7 +333,7 @@ pub fn sanitize(v: &Value) -> Result<Value, String> {
Err(e) => log::warn!("settings profile `{name}`: a theme is left out: {e}"),
}
}
let doc = json!({
let mut doc = json!({
"format": FORMAT,
"name": name,
"preferences": preferences,
@@ -331,6 +342,21 @@ pub fn sanitize(v: &Value) -> Result<Value, String> {
"toolbar": toolbar.prefs(),
"themes": themes,
});
if let Some(settings) = o.get("view_navigator").map(crate::view_gizmo::checked_profile_settings)
&& let Some(d) = doc.as_object_mut()
{
d.insert("view_navigator".into(), settings);
}
if let Some(v) = o.get("view_gizmo") {
match crate::view_gizmo::Shape::from_json(v) {
Some(shape) => {
if let Some(d) = doc.as_object_mut() {
d.insert("view_gizmo".into(), shape.to_json());
}
}
None => log::warn!("settings profile `{name}`: the view navigator's body can't be read; left out"),
}
}
if doc.to_string().len() > MAX_PROFILE_BYTES {
return Err(format!("a settings profile is at most {} KiB", MAX_PROFILE_BYTES / 1024));
}
@@ -416,6 +442,12 @@ fn apply(app: &mut SolveApp, doc: &Value) -> Vec<String> {
if let Some(t) = doc.get("toolbar") {
app.toolbar_custom.load(t);
}
if let Some(v) = doc.get("view_navigator") {
crate::view_gizmo::apply_profile_settings(app, v);
}
if let Some(v) = doc.get("view_gizmo") {
app.view_gizmo.load(Some(v));
}
skipped
}
@@ -448,7 +480,8 @@ pub fn command(app: &mut SolveApp, id: &str, v: &Value) -> Result<Value, String>
match id {
"settings.profile.list" => Ok(json!({ "profiles": app.settings_profiles.names(), "active": app.settings_profiles.active })),
"settings.profile.save" => {
let doc = capture(app, name);
// The checks a profile meets when it is read back, so none is saved only to be dropped.
let doc = sanitize(&capture(app, name))?;
match app.settings_profiles.find(name) {
Some(i) => {
if let Some(old) = app.settings_profiles.list.get_mut(i) {
@@ -1002,3 +1002,42 @@ fn profile_sidebar_switches_saves_and_marks_edits_with_existing_commands() {
"sidebar Save preserves typed input and saves the selected profile"
);
}
#[test]
fn a_profile_carries_the_view_navigators_body_and_one_without_leaves_it_alone() {
let mut h = Harness::new();
h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 10})).unwrap();
let body = h.app.session.world_state().unwrap().bodies[0].name.clone();
// Not the defaults, so the profile has something to carry.
run(&mut h, "view.navigator", json!({"style": "custom", "body": body, "texture": "modeled", "arrows": false, "home": false}));
run(&mut h, "settings.profile.save", json!({"name": "Gizmo"}));
let exported = capture(&h.app, "Gizmo");
assert!(exported["view_gizmo"]["v"].is_string(), "the body is packed into the profile: {}", exported["view_gizmo"]);
assert!(exported.to_string().len() < 64 * 1024, "a box costs little");
// Elsewhere: a design without that body, the cube, and no custom body yet.
let mut other = Harness::new();
run(&mut other, "settings.profile.save", json!({"name": "Plain"}));
assert_eq!(run(&mut other, "settings.profile.import", json!({"profile": exported})), json!({"name": "Gizmo"}));
assert!(other.app.preferences.navigator_arrows && other.app.preferences.navigator_home, "before the profile: the defaults");
run(&mut other, "settings.profile.apply", json!({"name": "Gizmo"}));
let shape = other.app.view_gizmo.shape.as_ref().expect("the profile brings the body along");
assert!(!other.app.preferences.navigator_arrows && !other.app.preferences.navigator_home, "and the arrows and Home");
assert_eq!(shape.name, body);
assert_eq!(shape.mesh.triangles.len(), h.app.view_gizmo.shape.as_ref().unwrap().mesh.triangles.len());
assert_eq!(other.app.preferences.navigator_style, crate::prefs::NavigatorStyle::Custom);
assert_eq!(other.app.preferences.navigator_texture, crate::prefs::NavigatorTexture::Modeled);
// A profile saved before a body was chosen keeps the current body.
run(&mut other, "settings.profile.apply", json!({"name": "Plain"}));
assert_eq!(other.app.view_gizmo.shape.as_ref().map(|s| s.name.as_str()), Some(body.as_str()));
// An unreadable body is left out of the profile; the rest of it still applies.
let mut broken = capture(&h.app, "Broken");
broken["view_gizmo"] = json!({"name": "x", "v": "not base64!"});
let checked = sanitize(&broken).unwrap();
assert!(checked.get("view_gizmo").is_none());
broken["view_navigator"] = json!({"texture": "glossy", "arrows": "yes", "home": true, "extra": 1});
assert_eq!(sanitize(&broken).unwrap()["view_navigator"], json!({"home": true}), "only what this version reads");
assert_eq!(checked["preferences"]["navigator_style"], "custom");
}
@@ -340,6 +340,29 @@ pub(crate) fn paint_navigation_cube(p: &Painter, rect: Rect) {
paint_with_tokens(p, rect, &super::preferences_figure_data::NAVIGATOR_CUBE, None, None, &Tokens::get(), Palette::Navigator);
}
/// A generic body (a hexagonal prism) in the navigator palette: the user's own body stands in its place.
pub(crate) fn paint_navigation_custom(p: &Painter, rect: Rect) {
let Some((p, scale)) = navigation_canvas(p, rect) else { return };
let t = Tokens::get();
let ctx = Ctx { t: &t, sample: None, palette: Palette::Navigator, origin: rect.min, scale };
let c = rect.center();
let (radius, height) = (34.0 * scale, 26.0 * scale);
let top: Vec<Pos2> = (0..6)
.map(|i| {
let a = std::f32::consts::FRAC_PI_3 * i as f32;
c + vec2(a.cos() * radius, a.sin() * radius * 0.5 - height * 0.5)
})
.collect();
let line = Stroke::new(1.4 * scale, ctx.ink(Ink::Line, 1.0));
// The three faces toward the viewer, then the top over them.
for (i, ink) in [(0, Ink::Right), (1, Ink::Left), (2, Ink::Left)] {
let (a, b) = (top[i], top[i + 1]);
let side = vec![a, b, b + vec2(0.0, height), a + vec2(0.0, height)];
p.add(Shape::convex_polygon(side, ctx.ink(ink, 1.0), line));
}
p.add(Shape::convex_polygon(top, ctx.ink(Ink::Top, 1.0), line));
}
/// Preserve the mouse's figure palette, with slightly stronger lettering.
pub(super) fn paint_mouse(p: &Painter, rect: Rect) {
paint_with_tokens(p, rect, &super::preferences_figure_data::MOUSE_MAPPING, None, None, &Tokens::get(), Palette::Mouse);
@@ -1,6 +1,6 @@
//! Compact navigation preference compositions and explanatory figures.
pub(crate) use super::preferences_figure_data::{paint_orbit_centre, paint_orbit_cursor, paint_orbit_origin};
pub(crate) use super::preferences_figure_ops::{paint_navigation_axes, paint_navigation_cube};
pub(crate) use super::preferences_figure_ops::{paint_navigation_axes, paint_navigation_cube, paint_navigation_custom};
use super::{metrics::dimension, text::paint_text};
use crate::theme::Tokens;
use crate::ui_kit::BackingTooltipExt as _;
+850
View File
@@ -0,0 +1,850 @@
//! The custom view navigator: a body of the user's choice drawn in place of the navigation cube
//! (`viewport::body_gizmo` draws it). A right-click on any view navigator offers Axes, Cube and
//! Custom ([`menu_items`]); Custom opens the Custom View Navigator panel, a feature panel with OK
//! and Cancel ([`start`], [`rows`], [`run_dialog`]): the body is picked in the view, then its
//! texture (the cube's colours, or the body's own) and whether the cube's rotation arrows and
//! Home button go around it. The navigator previews the panel's choices while it is open. OK
//! runs `view.navigator` ([`command`]), which scripts and the control channel run too.
//!
//! The body is kept as a snapshot of its display mesh, stored with the preferences and in
//! settings profiles, so it stays across runs and designs and travels with an exported profile.
//! The snapshot is scaled so its longest side is 2 and packed as 16-bit whole numbers of
//! 1/10000 ([`snapshot`]): every body is the same size in the gizmo, and the stored form stays
//! small. Faces and edges keep their identities, so the gizmo can light one face and outline it.
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use serde_json::{Value, json};
use solidcore_record::Vec3;
use solidcraft_engine::geom::{Mesh, Vec3Geom};
use crate::SolveApp;
use crate::context_menu::{Item, act};
use crate::dialogs::Kind;
use crate::prefs::{NavigatorStyle, NavigatorTexture};
use crate::selection::{BODIES, SelInput};
use crate::ui_kit;
use solidcraft_engine::Sel;
/// Bodies with more triangles cannot be the gizmo: the snapshot of one at the limit stays well
/// inside a settings profile (about 300 KiB of its 1 MiB), and the gizmo redraws every triangle
/// while the view turns.
pub const MAX_TRIANGLES: usize = 10_000;
/// Caps on what a stored snapshot may hold (the preferences file is input like any other).
const MAX_EDGES: usize = 10_000;
const MAX_EDGE_POINTS: usize = 50_000;
/// The most a body's widest way across may be to its thinnest: a long stick or a thin sheet is
/// a line from some sides, too thin to see or click.
const MAX_ASPECT: f64 = 5.0;
/// Slack on [`MAX_ASPECT`] for the packing's rounding (at most about 2e-4 of a width), so a body
/// at the limit is still at it once stored and read back.
const ASPECT_SLACK: f64 = 1e-3;
/// A face number that names no face, in a packed snapshot.
const NO_FACE: u16 = u16::MAX;
const MAX_NAME: usize = 256;
/// Stored units per half longest side.
const UNIT: f64 = 10_000.0;
/// The custom navigator's body.
#[derive(Default)]
pub struct State {
/// The body drawn in place of the cube (`None`: the cube is drawn).
pub shape: Option<Shape>,
/// The stored form of `shape`, made once when it is chosen.
stored: Option<Value>,
}
impl State {
/// What the preferences file keeps (`null`: no body).
pub fn stored(&self) -> Value {
self.stored.clone().unwrap_or(Value::Null)
}
/// Read what the preferences file kept; anything unreadable leaves no body.
pub fn load(&mut self, v: Option<&Value>) {
self.shape = v.and_then(Shape::from_json);
self.stored = self.shape.as_ref().map(Shape::to_json);
}
fn set(&mut self, shape: Option<Shape>) {
self.stored = shape.as_ref().map(Shape::to_json);
self.shape = shape;
}
}
/// A body's shape as the gizmo draws it.
#[derive(Clone, Debug)]
pub struct Shape {
/// The body it was taken from (for the window and automation).
pub name: String,
/// Different for every snapshot read or taken (what the gizmo's drawing is cached by).
pub id: u64,
/// Centred, longest side 2; one vertex per triangle corner, normals smooth within a face.
pub mesh: Arc<Mesh>,
/// The body's colour (appearance, material or imported); `None`: the theme's body colour.
pub colour: Option<[u8; 3]>,
/// Faces with colours of their own (B-rep face index → colour).
pub face_colours: BTreeMap<u32, [u8; 3]>,
}
impl Shape {
/// The snapshot of `mesh` with its colours (`None` when it is empty, flat to a point, or
/// too large).
pub fn of(name: &str, mesh: &Mesh, colour: Option<[u8; 3]>, face_colours: &BTreeMap<u32, [u8; 3]>) -> Option<Shape> {
if !fits(mesh) {
return None;
}
Shape::from_json(&snapshot(name, mesh, colour, face_colours)?)
}
/// The snapshot of a body of the session's design, in the colours the viewport draws it.
pub fn of_body(session: &solidcraft_engine::Session, name: &str) -> Option<Shape> {
let st = session.world_state().ok()?;
let b = st.body(name)?;
let to8 = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8;
let colour = session.doc.body_color(b).map(|c| c.map(to8));
let faces =
session.doc.face_colors(b).into_iter().filter_map(|(f, look)| Some((u32::try_from(f).ok()?, look.color))).take(MAX_TRIANGLES).collect();
Shape::of(name, &b.mesh(), colour, &faces)
}
/// The stored form, as [`Shape::from_json`] reads it.
pub fn to_json(&self) -> Value {
snapshot(&self.name, &self.mesh, self.colour, &self.face_colours).unwrap_or(Value::Null)
}
/// The colour of face `face` (`None`: the theme's body colour).
pub fn colour_of(&self, face: Option<u32>) -> Option<[u8; 3]> {
face.and_then(|f| self.face_colours.get(&f).copied()).or(self.colour)
}
/// Read a stored snapshot ([`snapshot`] packs it); `None` for anything malformed or over the
/// caps.
pub fn from_json(v: &Value) -> Option<Shape> {
let name: String = v.get("name")?.as_str()?.chars().take(MAX_NAME).collect();
let points: Vec<i16> = unpack(v, "v", 9 * MAX_TRIANGLES * 2)?.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect();
let words = |key: &str, cap: usize| -> Option<Vec<u16>> {
Some(unpack(v, key, cap * 2)?.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect())
};
let tris = words("t", 3 * MAX_TRIANGLES)?;
let faces = words("f", MAX_TRIANGLES)?;
let point = |p: &[i16; 3]| Vec3::new(f64::from(p[0]) / UNIT, f64::from(p[1]) / UNIT, f64::from(p[2]) / UNIT);
let points = points.as_chunks::<3>().0;
let mut corners: Vec<([Vec3; 3], u32)> = Vec::new();
for (t, face) in tris.as_chunks::<3>().0.iter().zip(faces.iter().chain(std::iter::repeat(&0))) {
let at = |i: u16| points.get(usize::from(i)).map(point);
// A corner past the points is a damaged snapshot: refuse it rather than draw part of it.
let (Some(a), Some(b), Some(c)) = (at(t[0]), at(t[1]), at(t[2])) else { return None };
corners.push(([a, b, c], u32::from(*face)));
}
if corners.is_empty() {
return None;
}
// Normals smooth across a face's shared corners, sharp between faces.
let mut sums: HashMap<(u32, [u64; 3]), Vec3> = HashMap::new();
let key = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()];
for (p, face) in &corners {
let n = (p[1] - p[0]).cross(p[2] - p[0]);
for v in p {
let e = sums.entry((*face, key(*v))).or_insert(Vec3::ZERO);
*e += n;
}
}
let mut mesh = Mesh::default();
for (p, face) in &corners {
let flat = (p[1] - p[0]).cross(p[2] - p[0]).normalized().unwrap_or(Vec3::Z);
let base = u32::try_from(mesh.positions.len()).unwrap_or(u32::MAX);
for v in p {
mesh.positions.push(*v);
mesh.normals.push(sums.get(&(*face, key(*v))).and_then(|n| n.normalized()).unwrap_or(flat));
}
mesh.triangles.push([base, base.saturating_add(1), base.saturating_add(2)]);
mesh.tri_face.push(*face);
}
// Edges are optional: a snapshot without readable ones is drawn without its lines.
let edge_points: Vec<i16> =
unpack(v, "e", MAX_EDGE_POINTS * 6).unwrap_or_default().as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect();
let mut edge_points = edge_points.as_chunks::<3>().0.iter().map(point);
let edge_faces = words("ef", 2 * MAX_EDGES).unwrap_or_default();
let lengths = v.get("en").and_then(Value::as_array).map(|a| a.iter().take(MAX_EDGES).collect::<Vec<_>>()).unwrap_or_default();
for (i, n) in lengths.into_iter().enumerate() {
let Some(n) = n.as_u64().and_then(|n| usize::try_from(n).ok()) else { break };
let line: Vec<Vec3> = edge_points.by_ref().take(n).collect();
if line.len() < n {
break;
}
let faces = [2 * i, 2 * i + 1].into_iter().filter_map(|j| edge_faces.get(j).filter(|f| **f != NO_FACE).map(|f| u32::from(*f))).collect();
mesh.edges.push(line);
mesh.edge_faces.push(faces);
}
let colour = v.get("c").and_then(rgb);
let face_colours = v
.get("fc")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.take(MAX_TRIANGLES)
.filter_map(|e| {
let e = e.as_array()?;
let face = u32::try_from(e.first()?.as_u64()?).ok()?;
Some((face, rgb(&Value::from(e.get(1..)?.to_vec()))?))
})
.collect()
})
.unwrap_or_default();
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let shape = Shape { name, id, mesh: Arc::new(mesh), colour, face_colours };
// A stored body meets the limits a picked one does (a hand-edited file or an imported
// profile could hold a stick), and is kept only if it saves again: a face number or
// bounds the packer refuses would be drawn now and dropped at the next save.
(refusal(&shape.mesh).is_none() && shape.to_json().is_object()).then_some(shape)
}
/// The direction to look from to see the face of triangle `tri` straight on: a planar
/// face's normal, or a curved face's at that triangle.
pub fn face_normal(&self, tri: usize) -> Option<Vec3> {
let m = &self.mesh;
let normal = |t: &[u32; 3]| m.tri(t).and_then(|p| (p[1] - p[0]).cross(p[2] - p[0]).normalized());
let seen = normal(m.triangles.get(tri)?)?;
let face = *m.tri_face.get(tri)?;
let mut sum = Vec3::ZERO;
let mut planar = true;
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
if *f != face {
continue;
}
let Some(p) = m.tri(t) else { continue };
let area = (p[1] - p[0]).cross(p[2] - p[0]);
planar &= area.normalized().is_none_or(|n| n.dot(seen) > 1.0 - 1e-6);
sum += area;
}
Some(if planar { sum.normalized().unwrap_or(seen) } else { seen })
}
}
/// A mesh the gizmo can draw: some triangles, not too many, and not too long and thin.
fn fits(mesh: &Mesh) -> bool {
refusal(mesh).is_none()
}
/// Why a body can't be the gizmo, as a message id (`None`: it can).
fn refusal(mesh: &Mesh) -> Option<&'static str> {
if !(1..=MAX_TRIANGLES).contains(&mesh.triangles.len()) {
return Some("view_gizmo.too_detailed");
}
let (thinnest, widest) = widths(&mesh.positions);
(!(widest > 0.0 && thinnest * MAX_ASPECT * (1.0 + ASPECT_SLACK) >= widest)).then_some("view_gizmo.too_thin")
}
/// The thinnest and the widest the points are across, measured along the three axes, the six
/// face diagonals and the four body diagonals, so a stick lying diagonally is found too.
fn widths(points: &[Vec3]) -> (f64, f64) {
let mut directions = vec![Vec3::X, Vec3::Y, Vec3::Z];
for (a, b) in [(Vec3::X, Vec3::Y), (Vec3::Y, Vec3::Z), (Vec3::Z, Vec3::X)] {
directions.extend([a + b, a - b]);
}
directions.extend([Vec3::new(1.0, 1.0, 1.0), Vec3::new(1.0, 1.0, -1.0), Vec3::new(1.0, -1.0, 1.0), Vec3::new(-1.0, 1.0, 1.0)]);
let (mut thinnest, mut widest) = (f64::INFINITY, 0.0_f64);
for d in directions.into_iter().filter_map(|d| d.normalized()) {
let (lo, hi) =
points.iter().map(|p| p.dot(d)).filter(|x| x.is_finite()).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x)));
let width = if hi >= lo { hi - lo } else { 0.0 };
thinnest = thinnest.min(width);
widest = widest.max(width);
}
(thinnest, widest)
}
fn rgb(c: &Value) -> Option<[u8; 3]> {
let a = c.as_array()?;
let ch = |i: usize| a.get(i).and_then(Value::as_u64).and_then(|x| u8::try_from(x).ok());
Some([ch(0)?, ch(1)?, ch(2)?])
}
/// The bytes of a packed field (`None`: missing, not base64, or over `cap` bytes).
fn unpack(v: &Value, key: &str, cap: usize) -> Option<Vec<u8>> {
let text = v.get(key)?.as_str()?;
if text.len() > cap.div_ceil(3) * 4 {
return None;
}
solidcraft_engine::doc::canvas::base64_decode(text)
}
/// Little-endian 16-bit words, as base64.
fn pack<T: Copy>(words: &[T], bytes: impl Fn(T) -> [u8; 2]) -> String {
let raw: Vec<u8> = words.iter().flat_map(|w| bytes(*w)).collect();
solidcraft_engine::doc::canvas::base64_encode(&raw)
}
/// The stored form of `mesh`, centred and scaled to longest side 2, in whole 1/10000s. Each
/// list is little-endian 16-bit words as base64, about a third of the size of a JSON list:
/// `v` the points (x, y, z), `t` three point indices per triangle, `f` each triangle's B-rep
/// face, `e` the points of every edge one after another with `en` the count of each, and `ef`
/// the two faces each edge bounds ([`NO_FACE`]: none). `None` when the mesh is empty or flat to
/// a point, or has a face number too large to store.
fn snapshot(name: &str, mesh: &Mesh, colour: Option<[u8; 3]>, faces: &BTreeMap<u32, [u8; 3]>) -> Option<Value> {
let b = mesh.bounds();
if b.is_empty() {
return None;
}
let size = b.max - b.min;
let half = size.x.max(size.y).max(size.z) * 0.5;
if !half.is_finite() || half <= 0.0 {
return None;
}
let centre = b.center();
let unit = |x: f64| (x.round().clamp(-UNIT, UNIT)) as i16;
let q = |p: Vec3| {
let d = (p - centre) / half * UNIT;
[unit(d.x), unit(d.y), unit(d.z)]
};
let mut index: HashMap<[i16; 3], u16> = HashMap::new();
let (mut v, mut t, mut f) = (Vec::new(), Vec::new(), Vec::new());
for (i, tri) in mesh.triangles.iter().enumerate().take(MAX_TRIANGLES) {
let Some(p) = mesh.tri(tri) else { continue };
for p in p {
let k = q(p);
let id = match index.get(&k) {
Some(id) => *id,
None => {
let id = u16::try_from(index.len()).ok()?;
index.insert(k, id);
v.extend(k);
id
}
};
t.push(id);
}
f.push(u16::try_from(mesh.tri_face.get(i).copied().unwrap_or(0)).ok().filter(|f| *f != NO_FACE)?);
}
let (mut e, mut en, mut ef) = (Vec::new(), Vec::new(), Vec::new());
for (i, line) in mesh.edges.iter().enumerate().take(MAX_EDGES) {
if mesh.seams.get(i) == Some(&true) || mesh.smooth_edges.get(i) == Some(&true) || e.len() / 3 + line.len() > MAX_EDGE_POINTS {
continue;
}
e.extend(line.iter().flat_map(|p| q(*p)));
en.push(line.len());
let bounds = mesh.edge_faces.get(i).map(Vec::as_slice).unwrap_or_default();
ef.extend((0..2).map(|j| bounds.get(j).and_then(|f| u16::try_from(*f).ok()).unwrap_or(NO_FACE)));
}
let fc: Vec<Value> = faces.iter().map(|(f, c)| json!([f, c[0], c[1], c[2]])).collect();
Some(json!({
"name": name,
"v": pack(&v, i16::to_le_bytes),
"t": pack(&t, u16::to_le_bytes),
"f": pack(&f, u16::to_le_bytes),
"e": pack(&e, i16::to_le_bytes),
"en": en,
"ef": pack(&ef, u16::to_le_bytes),
"c": colour,
"fc": fc,
}))
}
/// The menu a right-click on the view navigator opens: Axes, Cube and Custom, the current one
/// marked. Custom opens the Custom View Navigator panel, which sets it on OK.
pub(crate) fn menu_items(app: &SolveApp) -> Vec<Item> {
NavigatorStyle::ALL
.into_iter()
.map(|style| {
let (label, icon) = match style {
NavigatorStyle::Axes => (app.tr("prefs.axes"), "origin"),
NavigatorStyle::Cube => (crate::i18n::tr_label("Cube"), "box"),
NavigatorStyle::Custom => (crate::i18n::tr_label("Custom"), "body"),
};
act("ui.navigatorStyle", label, icon).with(json!({ "style": style })).key(if app.preferences.navigator_style == style {
"current"
} else {
""
})
})
.collect()
}
/// A menu pick: Axes and Cube at once; Custom opens its panel, as the toolbar would.
pub(crate) fn pick_style(app: &mut SolveApp, style: NavigatorStyle) {
if style == NavigatorStyle::Custom {
app.start("view.navigator");
} else if let Err(e) = app.run("view.navigator", json!({ "style": style })) {
app.set_status(e, true);
}
}
/// Draw body `name` of the open design as the gizmo (`None`: no body, the cube again).
fn set_body(app: &mut SolveApp, name: Option<&str>) -> Result<(), String> {
let shape = match name {
None => None,
Some(name) => Some(snapshot_of(&app.session, name).map_err(|reason| crate::i18n::tr(reason).to_string())?),
};
app.view_gizmo.set(shape);
Ok(())
}
/// The snapshot of body `name`, or why it can't be the navigator (a message id).
fn snapshot_of(session: &solidcraft_engine::Session, name: &str) -> Result<Shape, &'static str> {
let st = session.world_state().map_err(|_| "view_gizmo.no_such_body")?;
let body = st.body(name).ok_or("view_gizmo.no_such_body")?;
if let Some(reason) = refusal(&body.mesh()) {
return Err(reason);
}
Shape::of_body(session, name).ok_or("view_gizmo.too_detailed")
}
/// `view.navigator`, after the engine checked its parameters: set what it names, then reply with
/// the whole navigator. A refused body changes nothing.
pub(crate) fn command(app: &mut SolveApp, v: &Value) -> Result<Value, String> {
let field = |key: &str| v.get(key).filter(|x| !x.is_null()).cloned();
let style: Option<NavigatorStyle> = field("style").map(serde_json::from_value).transpose().map_err(|e| e.to_string())?;
let texture: Option<NavigatorTexture> = field("texture").map(serde_json::from_value).transpose().map_err(|e| e.to_string())?;
match v.get("body") {
None => {}
Some(Value::Null) => set_body(app, None)?,
Some(Value::String(name)) => set_body(app, Some(name))?,
Some(_) => return Err("`body` must be a body name or null".into()),
}
let p = &mut app.preferences;
if let Some(style) = style {
p.navigator_style = style;
}
if let Some(texture) = texture {
p.navigator_texture = texture;
}
if let Some(on) = field("arrows").and_then(|x| x.as_bool()) {
p.navigator_arrows = on;
}
if let Some(on) = field("home").and_then(|x| x.as_bool()) {
p.navigator_home = on;
}
Ok(json!({
"style": p.navigator_style,
"body": app.view_gizmo.shape.as_ref().map(|s| s.name.clone()),
"texture": p.navigator_texture,
"arrows": p.navigator_arrows,
"home": p.navigator_home,
}))
}
/// The custom navigator's texture, arrows and Home, as a settings profile keeps them.
pub(crate) fn profile_settings(app: &SolveApp) -> Value {
let p = &app.preferences;
json!({"texture": p.navigator_texture, "arrows": p.navigator_arrows, "home": p.navigator_home})
}
/// A profile's navigator settings cut down to the ones this version reads.
pub(crate) fn checked_profile_settings(v: &Value) -> Value {
let mut out = serde_json::Map::new();
if let Some(t) = v.get("texture").filter(|t| serde_json::from_value::<NavigatorTexture>((*t).clone()).is_ok()) {
out.insert("texture".into(), t.clone());
}
for key in ["arrows", "home"] {
if let Some(on) = v.get(key).and_then(Value::as_bool) {
out.insert(key.into(), json!(on));
}
}
Value::Object(out)
}
/// Apply a profile's (checked) navigator settings; a missing one keeps its current value.
pub(crate) fn apply_profile_settings(app: &mut SolveApp, v: &Value) {
let p = &mut app.preferences;
if let Some(t) = v.get("texture").and_then(|t| serde_json::from_value(t.clone()).ok()) {
p.navigator_texture = t;
}
if let Some(on) = v.get("arrows").and_then(Value::as_bool) {
p.navigator_arrows = on;
}
if let Some(on) = v.get("home").and_then(Value::as_bool) {
p.navigator_home = on;
}
}
/// The Custom View Navigator panel's settings; its body is the panel's selection input.
#[derive(Clone, Debug)]
pub struct Form {
pub texture: NavigatorTexture,
pub arrows: bool,
pub home: bool,
/// The picked body and its snapshot (or why it can't be the navigator), which the navigator
/// previews while the panel is open.
preview: Option<(String, Result<Shape, &'static str>)>,
}
/// The panel opened by `view.navigator` from the toolbar or the navigator's menu, filled with
/// the navigator as it is (its body picked when the open design has that very body, not just one
/// of the same name, so OK on a changed texture keeps the body).
pub(crate) fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
(id == "view.navigator").then(|| {
let mut body = SelInput::new("Body", BODIES, false);
if let Some(shape) = &app.view_gizmo.shape
&& Shape::of_body(&app.session, &shape.name).is_some_and(|own| own.to_json() == app.view_gizmo.stored())
{
body.items.push(Sel::Body { name: shape.name.clone() });
}
let p = &app.preferences;
(Kind::ViewNavigator(Form { texture: p.navigator_texture, arrows: p.navigator_arrows, home: p.navigator_home, preview: None }), vec![body])
})
}
/// The body picked in the panel.
fn picked(inputs: &[SelInput]) -> Option<&str> {
inputs.first()?.items.iter().find_map(|s| match s {
Sel::Body { name } => Some(name.as_str()),
_ => None,
})
}
/// The panel's rows under its body input: why a picked body can't be the navigator, the
/// texture, the arrows and Home.
pub(crate) fn rows(app: &SolveApp, ui: &mut egui::Ui, form: &mut Form, inputs: &[SelInput]) {
let body = picked(inputs);
if form.preview.as_ref().map(|(name, _)| name.as_str()) != body {
form.preview = body.map(|name| (name.to_string(), snapshot_of(&app.session, name)));
}
if let Some((_, Err(reason))) = &form.preview {
ui_kit::text(ui, crate::i18n::tr(reason), ui_kit::Text::Error("view_gizmo_refused"));
}
ui_kit::row(ui, crate::i18n::tr("view_gizmo.texture"), |ui| {
let mut texture = usize::from(form.texture == NavigatorTexture::Modeled);
let changed = ui_kit::segmented(
ui,
&mut texture,
&[crate::i18n::tr("view_gizmo.themed"), crate::i18n::tr_label("Modeled")],
ui_kit::Segments { intrinsic: true, ..Default::default() },
);
if changed {
form.texture = if texture == 1 { NavigatorTexture::Modeled } else { NavigatorTexture::Themed };
}
});
let arrows = ui_kit::checkbox(ui, crate::i18n::tr("view_gizmo.arrows"), &mut form.arrows);
crate::scenario::publish_target("view_gizmo:arrows", arrows.rect);
let home = ui_kit::checkbox(ui, crate::i18n::tr("view_gizmo.home"), &mut form.home);
crate::scenario::publish_target("view_gizmo:home", home.rect);
ui_kit::text(ui, crate::i18n::tr("view_gizmo.note"), ui_kit::Text::Note("view_gizmo_note"));
}
/// OK: the custom navigator with the panel's body (or the one it has), texture, arrows and Home.
pub(crate) fn run_dialog(app: &mut SolveApp, form: &Form, inputs: &[SelInput]) -> Result<(), String> {
if let Some((_, Err(reason))) = &form.preview {
return Err(crate::i18n::tr(reason).to_string());
}
let mut params = json!({"style": NavigatorStyle::Custom, "texture": form.texture, "arrows": form.arrows, "home": form.home});
if let (Some(body), Some(o)) = (picked(inputs), params.as_object_mut()) {
o.insert("body".into(), json!(body));
}
app.run("view.navigator", params).map(|_| ())
}
/// What the navigator shows now: while the Custom View Navigator panel is open, the custom
/// navigator as the panel stands (its picked body, else the kept one); otherwise as set.
pub(crate) struct Shown {
pub style: NavigatorStyle,
pub shape: Option<Shape>,
pub texture: NavigatorTexture,
pub arrows: bool,
pub home: bool,
}
pub(crate) fn shown(app: &SolveApp) -> Shown {
let p = &app.preferences;
match app.dialog.as_ref().map(|d| &d.kind) {
Some(Kind::ViewNavigator(form)) => Shown {
style: NavigatorStyle::Custom,
shape: match &form.preview {
Some((_, Ok(shape))) => Some(shape.clone()),
_ => app.view_gizmo.shape.clone(),
},
texture: form.texture,
arrows: form.arrows,
home: form.home,
},
_ => Shown {
style: p.navigator_style,
shape: app.view_gizmo.shape.clone(),
texture: p.navigator_texture,
arrows: p.navigator_arrows,
home: p.navigator_home,
},
}
}
#[cfg(test)]
mod tests {
use super::*;
fn box_mesh() -> Arc<Mesh> {
let mut s = solidcraft_engine::Session::default();
s.execute("solid.box", &json!({"length": 40, "width": 20, "height": 10})).unwrap();
s.world_state().unwrap().bodies[0].mesh()
}
#[test]
fn a_body_at_the_aspect_limit_is_still_accepted_once_packed() {
let bar = |thin: f64| {
let mut s = solidcraft_engine::Session::default();
s.execute("solid.box", &json!({"length": 50, "width": thin, "height": thin})).unwrap();
// Turned 45 degrees about its length, so the packing rounds its thin widths.
let mut mesh = (*s.world_state().unwrap().bodies[0].mesh()).clone();
let r = std::f64::consts::FRAC_1_SQRT_2;
for p in &mut mesh.positions {
*p = Vec3::new(p.x, r * (p.y - p.z), r * (p.y + p.z));
}
Shape::of("Bar", &mesh, None, &BTreeMap::new())
};
assert!(bar(10.0001).is_some(), "just inside 5:1 stays inside after packing");
assert!(bar(9.9).is_none(), "clearly past 5:1 is still refused");
}
#[test]
fn snapshots_round_trip_at_the_same_size_whatever_the_body() {
let m = box_mesh();
let shape = Shape::of("Body1", &m, Some([200, 30, 40]), &BTreeMap::from([(2, [0, 128, 255])])).unwrap();
let b = shape.mesh.bounds();
let size = b.max - b.min;
assert!((size.x.max(size.y).max(size.z) - 2.0).abs() < 1e-3, "longest side 2: {size:?}");
assert!(b.center().len() < 1e-3);
assert_eq!(shape.mesh.triangles.len(), m.triangles.len());
assert_eq!(shape.mesh.edges.len(), 12);
let again = Shape::from_json(&shape.to_json()).unwrap();
assert_eq!(again.mesh.positions, shape.mesh.positions);
assert_eq!(again.mesh.tri_face, shape.mesh.tri_face);
assert_eq!(
(again.colour_of(Some(2)), again.colour_of(Some(1)), again.colour_of(None)),
(Some([0, 128, 255]), Some([200, 30, 40]), Some([200, 30, 40]))
);
// A box 25 times larger snapshots to the same shape.
let mut s = solidcraft_engine::Session::default();
s.execute("solid.box", &json!({"length": 1000, "width": 500, "height": 250})).unwrap();
let big = Shape::of("Big", &s.world_state().unwrap().bodies[0].mesh(), None, &BTreeMap::new()).unwrap();
let bb = big.mesh.bounds();
assert!((bb.max - bb.min).dist(b.max - b.min) < 1e-3);
}
#[test]
fn face_normals_are_the_planar_face_normals() {
let shape = Shape::of("Body1", &box_mesh(), None, &BTreeMap::new()).unwrap();
for tri in 0..shape.mesh.triangles.len() {
let n = shape.face_normal(tri).unwrap();
let axes = [n.x.abs(), n.y.abs(), n.z.abs()];
assert!(axes.iter().any(|a| (a - 1.0).abs() < 1e-9), "{n:?}");
}
}
#[test]
fn hostile_snapshots_never_panic() {
let good = Shape::of("Body1", &box_mesh(), None, &BTreeMap::new()).unwrap().to_json();
let words = |w: &[u16]| pack(w, u16::to_le_bytes);
let triangle = words(&[0, 0, 0, 1, 0, 0, 0, 1, 0]);
let mut cases = vec![
json!(null),
json!({}),
json!({"name": 3}),
json!({"name": "x", "v": "", "t": "", "f": ""}),
json!({"name": "x", "v": [0, 0, 0], "t": [0, 1, 2], "f": [0]}),
json!({"name": "x", "v": "not base64!", "t": words(&[0, 1, 2]), "f": words(&[0])}),
json!({"name": "x", "v": triangle, "t": words(&[0, 1, 99]), "f": ""}),
json!({"name": "x", "v": triangle, "t": words(&[0, 1]), "f": words(&[u16::MAX])}),
json!({"name": "x", "v": "AAA", "t": words(&[0, 1, 2]), "f": words(&[0])}),
json!({"name": "x", "v": triangle, "t": words(&[0, 1, 2]), "f": words(&[0]), "e": triangle, "en": [u64::MAX, 2], "ef": 7}),
json!({"name": "x", "v": triangle, "t": words(&[0, 1, 2]), "f": words(&[0]), "e": "no", "en": ["no"], "ef": words(&[NO_FACE; 5])}),
json!({"name": "x".repeat(10_000), "v": triangle, "t": words(&[0, 1, 2]), "f": words(&[0])}),
json!({"name": "x", "v": triangle, "t": words(&[0, 1, 2]), "f": words(&[0]), "c": [300, -1, "r"], "fc": [[0], [1, 2], "no", [u64::MAX, 1, 2, 3]]}),
// Readable, but the packer can't write them again: a face numbered NO_FACE, one point.
json!({"name": "x", "v": triangle, "t": words(&[0, 1, 2]), "f": words(&[NO_FACE])}),
json!({"name": "x", "v": words(&[0, 0, 0]), "t": words(&[0, 0, 0]), "f": words(&[0])}),
];
let mut huge = good.clone();
huge["t"] = json!(words(&vec![0; 3 * MAX_TRIANGLES + 3]));
cases.push(huge);
for c in &cases {
if let Some(s) = Shape::from_json(c) {
assert!(s.name.chars().count() <= MAX_NAME);
assert!(s.mesh.triangles.len() <= MAX_TRIANGLES);
for t in 0..s.mesh.triangles.len() {
let _ = s.face_normal(t);
}
}
let mut state = State::default();
state.load(Some(c));
// A body that loads saves again, so a profile never carries a `null` body.
assert_eq!(state.shape.is_some(), state.stored().is_object(), "{c}");
}
assert!(Shape::from_json(&json!({"name": "x", "v": [0, 0, 0], "t": [0, 1, 2], "f": [0]})).is_none());
let mut damaged = good.clone();
damaged["t"] = json!(words(&[0, 1, 2, 0, 1, 9999]));
assert!(Shape::from_json(&damaged).is_none(), "one triangle past the points refuses the whole snapshot");
let flat = json!({"name": "x", "v": words(&[0, 0, 0, 30000, 0, 0, 0, 30000, 0]), "t": words(&[0, 1, 2]), "f": words(&[0])});
assert!(Shape::from_json(&flat).is_none(), "a stored sheet is refused as a picked one is");
let mut over = good;
over["t"] = json!(words(&vec![0; 3 * MAX_TRIANGLES + 3]));
assert!(Shape::from_json(&over).is_none(), "more triangles than the limit are refused");
}
#[test]
fn long_sticks_and_thin_sheets_are_refused_whichever_way_they_lie() {
let mut s = solidcraft_engine::Session::default();
let mesh = |s: &mut solidcraft_engine::Session, params: Value| {
s.execute("solid.box", &params).unwrap();
s.world_state().unwrap().bodies.last().unwrap().mesh()
};
// A 4:2:1 block is fine; a 6:1:1 stick and a 6:6:1 sheet are not.
assert_eq!(refusal(&mesh(&mut s, json!({"length": 40, "width": 20, "height": 10}))), None);
assert_eq!(refusal(&mesh(&mut s, json!({"length": 60, "width": 10, "height": 10, "operation": "new"}))), Some("view_gizmo.too_thin"));
assert_eq!(refusal(&mesh(&mut s, json!({"length": 60, "width": 60, "height": 10, "operation": "new"}))), Some("view_gizmo.too_thin"));
// The same stick turned to lie along a diagonal: its bounding box is a cube.
let mut stick = (*mesh(&mut s, json!({"length": 60, "width": 10, "height": 10, "operation": "new"}))).clone();
let along = Vec3::new(1.0, 1.0, 1.0).normalized().unwrap();
let side = Vec3::new(1.0, -1.0, 0.0).normalized().unwrap();
let up = along.cross(side);
for p in &mut stick.positions {
*p = along * p.x + side * p.y + up * p.z;
}
assert_eq!(refusal(&stick), Some("view_gizmo.too_thin"));
assert_eq!(refusal(&Mesh::default()), Some("view_gizmo.too_detailed"));
}
#[test]
fn a_body_at_the_limit_fits_in_a_settings_profile_with_room_to_spare() {
// A sphere close to the triangle limit: as many points as a smooth body has.
let mut s = solidcraft_engine::Session::default();
s.execute("solid.sphere", &json!({"radius": 10})).unwrap();
let mesh = s.world_state().unwrap().bodies[0].mesh();
let mut big = (*mesh).clone();
while big.triangles.len() < MAX_TRIANGLES {
let offset = u32::try_from(big.positions.len()).unwrap();
let shift = Vec3::new(0.0, 0.0, 0.001 * big.triangles.len() as f64);
big.positions.extend(mesh.positions.iter().map(|p| *p + shift));
big.normals.extend(mesh.normals.iter().copied());
big.triangles.extend(mesh.triangles.iter().map(|t| t.map(|i| i + offset)));
big.tri_face.extend(mesh.tri_face.iter().copied());
}
// Exactly at the limit, however finely the sphere is meshed.
big.triangles.truncate(MAX_TRIANGLES);
big.tri_face.truncate(MAX_TRIANGLES);
assert!(fits(&big), "{} triangles", big.triangles.len());
let shape = Shape::of("Sphere", &big, Some([1, 2, 3]), &BTreeMap::new()).expect("a body under the limit snapshots");
let bytes = shape.to_json().to_string().len();
assert!(bytes < 400 * 1024, "{bytes} bytes for {} triangles", big.triangles.len());
}
#[test]
fn a_right_click_anywhere_on_the_navigator_offers_axes_cube_and_custom() {
use crate::context_menu::{Target, items};
let mut h = crate::scenario::Harness::new();
h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 10})).unwrap();
h.frames(2);
let design = h.app.session.doc.to_json();
for (from, pick, to) in [("axes", "Cube", NavigatorStyle::Cube), ("cube", "Axes", NavigatorStyle::Axes)] {
h.call("ui.prefs", json!({"navigator_style": from}));
h.frames(2);
let outer = crate::scenario::rect_of("axis_view:outer").expect("the navigator is shown");
// The middle, a corner of its box, and its Home button on the cube.
let mut spots = vec![outer.center(), outer.left_bottom() + egui::vec2(3.0, -3.0)];
spots.extend(crate::scenario::handle_at("navigation_cube:control:home"));
for at in spots {
crate::context_menu::close(&mut h.app);
h.call("ui.click", json!({"x": at.x, "y": at.y, "button": "right"}));
assert_eq!(h.app.menu.target, Target::ViewGizmo, "{from} at {at:?}: the navigator's own menu");
assert!(h.app.viewport.context_menu.is_some());
}
let rows = items(&h.app, &Target::ViewGizmo);
let labels: Vec<_> = rows.iter().map(|r| r.label.as_str()).collect();
assert_eq!(labels, ["Axes", "Cube", "Custom"], "just the three types");
let current: Vec<_> = rows.iter().filter(|i| i.shortcut == "current").collect();
assert_eq!(current.len(), 1);
assert_eq!(current[0].params.as_ref().map(|p| p["style"].clone()), Some(json!(from)));
assert_eq!(h.call("ui.menuPick", json!({"item": pick}))["ok"], true, "{pick}");
assert_eq!(h.app.preferences.navigator_style, to, "Axes and Cube apply at once");
assert!(h.app.dialog.is_none());
}
assert_eq!(h.app.session.doc.to_json(), design);
assert!(h.app.session.selection.is_empty(), "a right-click on the navigator selects nothing");
}
#[test]
fn custom_opens_a_panel_whose_ok_sets_the_navigator_and_cancel_leaves_it() {
let mut h = crate::scenario::Harness::new();
h.app.preferences.look_at_anim = false;
h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 10})).unwrap();
h.call("ui.prefs", json!({"navigator_style": "cube"}));
h.frames(2);
let body = h.app.session.world_state().unwrap().bodies[0].name.clone();
let open = |h: &mut crate::scenario::Harness| {
let before = h.app.preferences.navigator_style;
let c = crate::scenario::rect_of("axis_view:outer").unwrap().center();
h.call("ui.click", json!({"x": c.x, "y": c.y, "button": "right"}));
assert_eq!(h.call("ui.menuPick", json!({"item": "Custom"}))["ok"], true);
h.frames(2);
assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::ViewNavigator(_))), "the Custom View Navigator panel");
assert_eq!(h.app.preferences.navigator_style, before, "nothing changes before OK");
};
// Pick the body as a click in the view would, and turn Home off (it starts on).
let fill = |h: &mut crate::scenario::Harness| {
let d = h.app.dialog.as_mut().unwrap();
d.inputs[0].items = vec![Sel::Body { name: body.clone() }];
if let Kind::ViewNavigator(form) = &mut d.kind {
assert!(form.home && form.arrows, "Home and the arrows start on");
form.home = false;
form.texture = NavigatorTexture::Modeled;
}
h.frames(2);
};
open(&mut h);
fill(&mut h);
assert!(crate::scenario::count_of("body_gizmo:faces").is_some_and(|n| n >= 3.0), "the navigator previews the picked body");
assert!(crate::scenario::handle_at("navigation_cube:control:home").is_none(), "and the panel's Home, off");
assert!(crate::scenario::handle_at("navigation_cube:control:left").is_some(), "with its arrows");
h.step(&json!({"click": {"handle": "dialog:cancel"}})).unwrap();
h.frames(2);
assert!(h.app.dialog.is_none());
assert_eq!(h.app.preferences.navigator_style, NavigatorStyle::Cube, "Cancel keeps the cube");
assert!(h.app.view_gizmo.shape.is_none() && h.app.preferences.navigator_home, "Cancel keeps Home on");
let undo = h.app.session.undo.len();
open(&mut h);
fill(&mut h);
h.step(&json!({"click": {"handle": "dialog:ok"}})).unwrap();
h.frames(2);
assert!(h.app.dialog.is_none());
assert_eq!(h.app.preferences.navigator_style, NavigatorStyle::Custom);
assert_eq!(h.app.view_gizmo.shape.as_ref().map(|s| s.name.as_str()), Some(body.as_str()));
assert!(!h.app.preferences.navigator_home && h.app.preferences.navigator_arrows);
assert_eq!(h.app.preferences.navigator_texture, NavigatorTexture::Modeled);
assert_eq!(h.app.session.undo.len(), undo, "the navigator is never part of the design");
// Opened again, the panel starts from the navigator as it is.
open(&mut h);
let d = h.app.dialog.as_ref().unwrap();
assert_eq!(d.inputs[0].items, vec![Sel::Body { name: body.clone() }]);
assert!(matches!(&d.kind, Kind::ViewNavigator(f) if !f.home && f.texture == NavigatorTexture::Modeled));
}
#[test]
fn the_body_is_kept_with_the_preferences_and_unreadable_ones_are_dropped() {
let mut h = crate::scenario::Harness::new();
h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 10})).unwrap();
let name = h.app.session.world_state().unwrap().bodies[0].name.clone();
let reply = h.app.run("view.navigator", json!({"body": name})).unwrap();
assert_eq!(reply["body"], json!(name), "{reply}");
assert!(h.app.dialog.is_none(), "a programmatic call never opens the panel");
let mut other = crate::scenario::Harness::new();
other.app.load_prefs(&h.app.prefs());
let kept = other.app.view_gizmo.shape.as_ref().expect("the body survives a restart");
assert_eq!(kept.name, name);
assert_eq!(kept.mesh.triangles.len(), h.app.view_gizmo.shape.as_ref().unwrap().mesh.triangles.len());
let preselected = |app: &SolveApp| start(app, "view.navigator").map(|(_, inputs)| picked(&inputs).map(str::to_owned));
assert_eq!(preselected(&h.app), Some(Some(name.clone())), "the panel picks the kept body in its own design");
other.app.run("solid.box", json!({"length": 30, "width": 30, "height": 10})).unwrap();
assert_eq!(other.app.session.world_state().unwrap().bodies[0].name, name);
assert_eq!(preselected(&other.app), Some(None), "another design's body of the same name is not the kept one");
assert!(h.app.run("view.navigator", json!({"body": "No such body"})).is_err());
assert!(h.app.run("view.navigator", json!({"body": 3})).is_err());
h.app.run("solid.box", json!({"length": 60, "width": 10, "height": 10, "operation": "new"})).unwrap();
let stick = h.app.session.world_state().unwrap().bodies.last().unwrap().name.clone();
assert!(h.app.run("view.navigator", json!({"body": stick})).is_err(), "a stick is refused");
assert_eq!(h.app.view_gizmo.shape.as_ref().map(|s| s.name.clone()), Some(name), "a refused body changes nothing");
assert_eq!(h.app.run("view.navigator", json!({"body": null})).unwrap()["body"], Value::Null);
other.app.load_prefs(&json!({"view_gizmo": {"name": "x", "v": "broken"}}).to_string());
assert!(other.app.view_gizmo.shape.is_none());
}
}
+41 -5
View File
@@ -39,6 +39,9 @@ mod plane_target_tests;
#[path = "viewport_refine_wait_tests.rs"]
mod refine_wait_tests;
#[path = "body_gizmo.rs"]
mod body_gizmo;
#[path = "navigation_cube.rs"]
mod navigation_cube;
@@ -3197,7 +3200,7 @@ fn section_clip(app: &SolveApp) -> [f32; 4] {
pub(crate) fn axis_view_size(style: crate::prefs::NavigatorStyle) -> f32 {
match style {
crate::prefs::NavigatorStyle::Axes => 116.0,
crate::prefs::NavigatorStyle::Cube => navigation_cube::SIZE,
crate::prefs::NavigatorStyle::Cube | crate::prefs::NavigatorStyle::Custom => navigation_cube::SIZE,
}
}
// Keep command panels anchored independently of the compact cube's display size.
@@ -6860,9 +6863,11 @@ fn axis_view_orbit(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) -> bool {
(p.primary_pressed(), p.primary_down(), p.is_decidedly_dragging(), p.press_origin(), p.interact_pos(), i.modifiers.shift)
});
if pressed && ui.is_enabled() && ui.rect_contains_pointer(rect) && !pos.is_some_and(|p| crate::shell::covered(app, p)) {
app.viewport.axis_drag = origin.filter(|p| match app.preferences.navigator_style {
let shown = crate::view_gizmo::shown(app);
app.viewport.axis_drag = origin.filter(|p| match shown.style {
crate::prefs::NavigatorStyle::Axes => axis_rect(app, rect).contains(*p),
crate::prefs::NavigatorStyle::Cube => {
crate::prefs::NavigatorStyle::Custom if shown.shape.is_some() => body_gizmo::drag_origin(app, rect, *p),
crate::prefs::NavigatorStyle::Cube | crate::prefs::NavigatorStyle::Custom => {
navigation_cube::drag_origin(app, axis_center(app, rect), *p, axis_rect(app, rect).width() / navigation_cube::DESIGN_SIZE)
}
});
@@ -6884,10 +6889,41 @@ fn axis_view_orbit(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) -> bool {
true
}
/// The whole navigator's box takes the right-click for the navigator's menu, before the view
/// under it would (its controls are drawn over it, and open the same menu themselves).
fn gizmo_menu(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) {
let outer = axis_rect(app, rect);
if !outer.is_positive() || !outer.is_finite() {
return;
}
// Read the pointer rather than add a widget over the navigator, which would take the
// primary clicks the viewport owns there when orbiting is off.
if ui.is_enabled()
&& ui.input(|i| i.pointer.secondary_clicked())
&& app.dialog.is_none()
&& let Some(at) = ui.input(|i| i.pointer.interact_pos())
&& ui.rect_contains_pointer(outer)
&& view_gizmo_at(app, at)
{
crate::context_menu::open_for(app, at, crate::context_menu::Target::ViewGizmo);
}
}
/// The view gizmo (whichever type is shown) is under `p`: a right-click there opens its menu.
pub(crate) fn view_gizmo_at(app: &SolveApp, p: Pos2) -> bool {
app.viewport.rect.is_some_and(|rect| {
let outer = axis_rect(app, rect);
outer.is_positive() && outer.contains(p) && !crate::shell::covered(app, p)
})
}
pub(crate) fn axis_view(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) {
match app.preferences.navigator_style {
gizmo_menu(app, ui, rect);
let shown = crate::view_gizmo::shown(app);
match shown.style {
crate::prefs::NavigatorStyle::Axes => signed_axis_view(app, ui, rect),
crate::prefs::NavigatorStyle::Cube => navigation_cube::show(app, ui, rect),
crate::prefs::NavigatorStyle::Custom if shown.shape.is_some() => body_gizmo::show(app, ui, rect, shown),
crate::prefs::NavigatorStyle::Cube | crate::prefs::NavigatorStyle::Custom => navigation_cube::show(app, ui, rect),
}
}
+1 -1
View File
@@ -161,7 +161,7 @@ impl Layout {
// This decision depends only on viewport size, never on an overlay.
if axis_view.intersect(navigation).is_positive() {
let compact = (navigation.top() - top - 4.0).min(cube_size);
axis_view = if style == crate::prefs::NavigatorStyle::Cube && compact >= 96.0 {
axis_view = if style != crate::prefs::NavigatorStyle::Axes && compact >= 96.0 {
Rect::from_min_size(pos2(axis_left(compact), top), vec2(compact, compact))
} else {
Rect::NOTHING
+2 -1
View File
@@ -236,7 +236,8 @@ fn measured_navigator_targets_home_and_drag_work_beside_the_palette_at_hidpi() {
continue;
}
assert!(!layout.navigation.intersect(outer).is_positive());
if style == crate::prefs::NavigatorStyle::Cube {
// Custom without a body draws the cube.
if style != crate::prefs::NavigatorStyle::Axes {
let front = crate::scenario::handle_at("navigation_cube:front").unwrap();
assert!(outer.contains(front));
let up = crate::scenario::handle_at("navigation_cube:control:up").unwrap();
+24 -5
View File
@@ -729,7 +729,11 @@ One setting per line, sorted by name. A change that adds a setting adds its own
- `msaa`
- `nav` (`fusion`, `solidworks`, `creo`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`)
- `nav_bridge_enabled` (default false) and `nav_bridge_port` (default 8765: a device's own app on this computer moves the view, [the navigation bridge](3d-mouse.md#device-apps-the-navigation-bridge))
- `navigator_arrows` (default true: the custom view navigator has the cube's orbit and roll arrows around its body; also `view.navigator {arrows}`)
- `navigator_fit` (default false: a view chosen on the view cube or the axis gizmo also looks at the middle of the model from the one distance that fits its bounding sphere in the free part of the view, at `home_fit_size`; Home and an opened design use the same zoom and centre while it is on, so views chosen after them only turn; #10091)
- `navigator_home` (default true: the custom view navigator has the cube's Home button beside it; also `view.navigator {home}`)
- `navigator_style` (`axes` (default), `cube`, `custom`: the body chosen with `view.navigator`, the cube until one is chosen)
- `navigator_texture` (`themed` (default): the custom view navigator in the cube's colours; `modeled`: in its body's own appearance and edge colour)
- `offer_stand_up`
- `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true)
- `orbit_reverse` (default false: Shift with two-finger scrolling orbits the other way)
@@ -857,11 +861,26 @@ channel; see [mcp.md](mcp.md).
{"id":5,"method":"ui.screenshot","params":{"path":"/tmp/part.png"}}
```
Preferences → Navigation → View navigator offers **Signed axes** (the original default) and
**Cube**. This choice is saved independently of the mouse preset. The control channel selects it
with `ui.prefs {"navigator_style":"axes"}` or `ui.prefs {"navigator_style":"cube"}`.
Existing settings without this field keep signed axes. Signed-axis tips choose principal views;
clicking an aligned tip again reverses the view.
Preferences → Navigation → View navigator offers **Signed axes** (the original default),
**Cube** and **Custom**; a right-click anywhere on the navigator offers the same three. This choice is
saved independently of the mouse preset. The control channel selects it with
`ui.prefs {"navigator_style":"axes"}`, `"cube"` or `"custom"`. Existing settings without this field
keep signed axes. Signed-axis tips choose principal views; clicking an aligned tip again reverses
the view.
Custom draws a body in place of the cube, at the cube's size; a click on one of its faces looks
straight at it, and with `navigator_fit` on it also frames the model, as the cube does. Picking
Custom from the navigator's menu opens the Custom View Navigator panel, with OK and Cancel: pick
the body in the view, then its texture (`themed`: the cube's colours; `modeled`: the body's own
appearance and the view's edge colour) and whether the cube's rotation arrows and Home button go
around it. The navigator previews the panel's choices while it is open. OK runs
`view.navigator`, which scripts and `engine.execute` run too without opening anything:
`{"style": "custom", "body": "Body1", "texture": "modeled", "arrows": true, "home": false}` (any
subset; `"body": null` goes back to the cube) returns the whole navigator. A body over 10,000
triangles is refused, and so is a long or flat one: measured across the axes and the diagonals,
its thinnest width must be at least a fifth of its widest. The body is kept as a snapshot with the
preferences and in settings profiles (`settings.profile.*`, as `view_gizmo`), so it stays across
runs and designs and travels with an exported profile.
Hold Shift during an orbit gesture to snap to the nearest standard or diagonal view. This applies to
right-drag, the Orbit navigation tool, and dragging either view navigator. Under the default preset,
+1
View File
@@ -329,6 +329,7 @@ view.left the view: camera, layout, display
view.list the view: camera, layout, display
view.navigate the view: camera, layout, display
view.navigation_bar the view: camera, layout, display
view.navigator the view: navigator type; crates/engine/src/schema/view_navigation_tests.rs
view.next_tab the view: camera, layout, display
view.normal_to the view: camera, layout, display
view.perspective the view: camera, layout, display