feat(layout): MVSETUP sets a drawing up for plotting

In model space MVSETUP draws the sheet border at the drawing scale
(scale factor, paper width and height) and zooms to it, or switches to
a layout. On a layout it creates viewports in a bounding area (a single
one, a 2x2 engineering set of top/front/right/isometric views, or an
array with spacing), deletes picked objects, and scales picked
viewports to a paper/model unit ratio.

A viewport's fit to the model now measures the model along the
viewport's own view direction, so side and isometric views frame it
too.

Refs #1501

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Hakan SevenandClaude Opus 5.5 committed 2026-10-13 15:21:26 +03:00
1 parent b1d4c9bd9b
commit 57eb7fe4db
31 files changed
+929 -10

No files matched your search

+7
View File
@@ -882,6 +882,13 @@ impl OpenCADStudio {
CmdResult::ZoomToWindow { p1, p2 } => {
self.handle_zoom_to_window(p1, p2);
}
CmdResult::CommitAndZoom { entity, p1, p2 } => {
self.handle_commit_entities_and_exit(vec![entity], false, false);
self.handle_zoom_to_window(p1, p2);
}
CmdResult::ScaleViewports { handles, factor } => {
self.handle_scale_viewports(handles, factor);
}
CmdResult::TwistView(twist) => {
self.handle_twist_view(twist);
}
+27
View File
@@ -447,6 +447,33 @@ impl OpenCADStudio {
.push_output(crate::t!("Zoom Window").as_ref());
}
/// MVSETUP Scale viewports: each picked layout viewport shows the model
/// at `factor` paper units per model unit. One undo step.
pub(in crate::app) fn handle_scale_viewports(&mut self, handles: Vec<Handle>, factor: f64) {
let i = self.active_tab;
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
let handles: Vec<Handle> = handles
.into_iter()
.filter(|handle| {
matches!(
self.tabs[i].scene.document.get_entity(*handle),
Some(codec::EntityType::Viewport(viewport)) if viewport.id > 1
)
})
.collect();
if handles.is_empty() {
return;
}
self.push_undo_snapshot(i, "MVSETUP");
for handle in handles {
self.tabs[i]
.scene
.set_viewport_scale_factor_for(handle, factor);
}
self.tabs[i].dirty = true;
}
/// Turn the active view about its line of sight so the drawing shows
/// `twist` radians counter-clockwise from its untwisted orientation.
pub(in crate::app) fn handle_twist_view(&mut self, twist: f64) {
+28
View File
@@ -647,6 +647,34 @@ impl OpenCADStudio {
}
}
// MVSETUP — sheet border in model space, viewports on a layout.
"MVSETUP" => {
let scene = &mut self.tabs[i].scene;
let target = (scene.current_layout == "Model").then(|| {
scene
.layout_names()
.into_iter()
.find(|name| name != "Model")
.unwrap_or_else(|| "Layout1".to_string())
});
// The sheet MVSETUP lays viewports out on: the layout it
// switches to from model space, or the current one.
let current = target
.clone()
.map(|name| std::mem::replace(&mut scene.current_layout, name));
let paper_bounds = scene
.printable_area_limits()
.or_else(|| scene.paper_limits())
.unwrap_or(((0.0, 0.0), (297.0, 210.0)));
if let Some(current) = current {
scene.current_layout = current;
}
use crate::modules::layout::mvsetup::MvsetupCommand;
let command = MvsetupCommand::new(target, paper_bounds);
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
}
// ── MSPACE / PSPACE ───────────────────────────────────────────
"MSPACE" => {
return Some(Task::done(Message::MspaceCommand));
+2 -2
View File
@@ -6445,10 +6445,10 @@ properties={:.1}ms picked={}",
&& self.tabs[i]
.active_cmd
.as_ref()
.is_some_and(|command| command.name() == "MVIEW");
.is_some_and(|command| matches!(command.name(), "MVIEW" | "MVSETUP"));
if context_changed {
if preserve_active_command {
// MVIEW keeps its command-owned step data, but all host-owned
// MVIEW and MVSETUP keep their step data, but all host-owned
// cursor/snap/dynamic-input state belongs to the old space.
self.reset_space_interaction_state();
}
+12
View File
@@ -1943,6 +1943,18 @@ pub enum CmdResult {
p1: DVec3,
p2: DVec3,
},
/// Commit `entity`, then zoom to the given corner points; end command.
CommitAndZoom {
entity: EntityType,
p1: DVec3,
p2: DVec3,
},
/// Scale the given layout viewports to `factor` paper units per model
/// unit; end command.
ScaleViewports {
handles: Vec<Handle>,
factor: f64,
},
/// Print a measurement result to the command line and end the command.
Measurement(String),
/// Print a measurement result and keep the command active.
+19
View File
@@ -2089,6 +2089,25 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static
"MText" => Some(("common", "mtext")),
"MVIEW Specify corner of viewport or [Polygonal/Object/Fit/Insert view]:" => Some(("layout", "mview-specify-corner-of-viewport-or-polygonal")),
"MVIEW Specify opposite corner:" => Some(("layout", "mview-specify-opposite-corner")),
"MVSETUP Enable paper space? [No/Yes] <Y>:" => Some(("layout", "mvsetup-enable-paper-space")),
"MVSETUP Enter the scale factor <1>:" => Some(("layout", "mvsetup-enter-scale-factor")),
"MVSETUP Enter the paper width:" => Some(("layout", "mvsetup-enter-paper-width")),
"MVSETUP Enter the paper height:" => Some(("layout", "mvsetup-enter-paper-height")),
"MVSETUP Enter an option [Create/Delete objects/Scale viewports]:" => Some(("layout", "mvsetup-enter-option")),
"MVSETUP Select the objects to delete:" => Some(("layout", "mvsetup-select-objects-to-delete")),
"Delete objects" => Some(("layout", "delete-objects-option")),
"MVSETUP Enter viewport layout [Single/Engineering/Array] <Single>:" => Some(("layout", "mvsetup-enter-viewport-layout")),
"MVSETUP Specify first corner of bounding area for viewport(s) <Sheet>:" => Some(("layout", "mvsetup-specify-first-corner")),
"MVSETUP Specify opposite corner:" => Some(("layout", "mvsetup-specify-opposite-corner")),
"MVSETUP Enter number of viewports in X direction <2>:" => Some(("layout", "mvsetup-viewports-in-x")),
"MVSETUP Enter number of viewports in Y direction <2>:" => Some(("layout", "mvsetup-viewports-in-y")),
"MVSETUP Specify distance between viewports in X direction <0>:" => Some(("layout", "mvsetup-distance-in-x")),
"MVSETUP Specify distance between viewports in Y direction <0>:" => Some(("layout", "mvsetup-distance-in-y")),
"MVSETUP Select the viewports to scale:" => Some(("layout", "mvsetup-select-viewports")),
"MVSETUP Enter the number of paper space units <1>:" => Some(("layout", "mvsetup-paper-space-units")),
"MVSETUP Enter the number of model space units <1>:" => Some(("layout", "mvsetup-model-space-units")),
"MVSETUP The viewports do not fit in the bounding area." => Some(("layout", "mvsetup-viewports-do-not-fit")),
"Scale viewports" => Some(("layout", "scale-viewports-option")),
"MVIEW Insert view Choose a named view or [New]:" => Some(("layout", "mview-insert-view-choose-a-named-view-or-new")),
"MVIEW Insert view No named views; choose [New]:" => Some(("layout", "mview-insert-view-no-named-views-choose-new")),
"MVIEW Insert view Specify placement point:" => Some(("layout", "mview-insert-view-specify-placement-point")),
+1
View File
@@ -2,6 +2,7 @@
// This tab is only shown when the active layout is not "Model".
pub mod mview;
pub mod mvsetup;
pub mod vplayer;
use crate::modules::{CadModule, IconKind, ModuleEvent, RibbonGroup, ToolDef};
+374
View File
@@ -0,0 +1,374 @@
// MVSETUP — set a drawing up for plotting.
//
// In model space without paper space it draws the sheet border at the
// drawing scale:
// Enable paper space? [No/Yes] <Y>:
// Enter the scale factor <1>:
// Enter the paper width:
// Enter the paper height:
// On a layout it lays out viewports or scales them:
// Enter an option [Create/Delete objects/Scale viewports]:
// Enter viewport layout [Single/Engineering/Array] <Single>:
// Specify first corner of bounding area for viewport(s) <Sheet>:
// Specify opposite corner:
// Enter number of viewports in X direction <2>: (Array)
// Enter number of viewports in Y direction <2>: (Array)
// Specify distance between viewports in X direction <0>:
// Specify distance between viewports in Y direction <0>:
// Select the objects to delete:
// Select the viewports to scale:
// Enter the number of paper space units <1>:
// Enter the number of model space units <1>:
use crate::t;
use codec::entities::{LwPolyline, LwVertex, Viewport};
use codec::types::{Vector2, Vector3};
use codec::{EntityType, Handle};
use glam::{DVec2, DVec3};
use crate::command::{CadCommand, CmdOption, CmdResult};
#[derive(Clone, Copy, PartialEq)]
enum Step {
PaperSpace,
Scale,
Width,
Height,
Option,
Arrangement,
FirstCorner,
SecondCorner,
Columns,
Rows,
GapX,
GapY,
Delete,
Viewports,
PaperUnits,
ModelUnits,
}
#[derive(Clone, Copy, PartialEq)]
enum Arrangement {
Single,
Engineering,
Array,
}
pub struct MvsetupCommand {
step: Step,
/// The layout model space switches to when paper space is enabled.
layout: String,
paper_bounds: ((f64, f64), (f64, f64)),
scale: f64,
width: f64,
arrangement: Arrangement,
first: DVec2,
area: (DVec2, DVec2),
columns: u32,
rows: u32,
gap_x: f64,
picked: Vec<Handle>,
paper_units: f64,
}
impl MvsetupCommand {
/// `layout` is `None` on a layout, or the layout to switch to from model
/// space; `paper_bounds` is the sheet's printable area.
pub fn new(layout: Option<String>, paper_bounds: ((f64, f64), (f64, f64))) -> Self {
Self {
step: if layout.is_some() {
Step::PaperSpace
} else {
Step::Option
},
layout: layout.unwrap_or_default(),
paper_bounds,
scale: 1.0,
width: 0.0,
arrangement: Arrangement::Single,
first: DVec2::ZERO,
area: (DVec2::ZERO, DVec2::ZERO),
columns: 2,
rows: 2,
gap_x: 0.0,
picked: Vec::new(),
paper_units: 1.0,
}
}
fn after_area(&mut self) -> CmdResult {
self.step = match self.arrangement {
Arrangement::Single => return self.create(0.0),
Arrangement::Engineering => Step::GapX,
Arrangement::Array => Step::Columns,
};
CmdResult::NeedPoint
}
/// The viewports of the chosen arrangement, `gap_y` apart vertically.
fn create(&self, gap_y: f64) -> CmdResult {
let (columns, rows, gap_x) = match self.arrangement {
Arrangement::Single => (1, 1, 0.0),
Arrangement::Engineering => (2, 2, self.gap_x),
Arrangement::Array => (self.columns, self.rows, self.gap_x),
};
let (min, max) = self.area;
let width = (max.x - min.x - gap_x * (columns - 1) as f64) / columns as f64;
let height = (max.y - min.y - gap_y * (rows - 1) as f64) / rows as f64;
if width <= 1e-6 || height <= 1e-6 {
return CmdResult::ReportError(
t!("MVSETUP The viewports do not fit in the bounding area.").into_owned(),
);
}
// Engineering: top view over front view, right view beside it, and
// an isometric view in the remaining corner.
let directions = [
Vector3::new(0.0, 0.0, 1.0),
Vector3::new(1.0, -1.0, 1.0),
Vector3::new(0.0, -1.0, 0.0),
Vector3::new(1.0, 0.0, 0.0),
];
let mut viewports = Vec::new();
for row in 0..rows {
for column in 0..columns {
let mut viewport = Viewport::new();
viewport.center = Vector3::new(
min.x + column as f64 * (width + gap_x) + width / 2.0,
max.y - row as f64 * (height + gap_y) - height / 2.0,
0.0,
);
viewport.width = width;
viewport.height = height;
viewport.id = 2;
if self.arrangement == Arrangement::Engineering {
viewport.view_direction = directions[(row * 2 + column) as usize].clone();
}
viewports.push(EntityType::Viewport(viewport));
}
}
CmdResult::CommitEntitiesAndExit(viewports)
}
fn sheet_border(&self, height: f64) -> CmdResult {
let (width, height) = (self.width * self.scale, height * self.scale);
let mut border = LwPolyline::new();
border.is_closed = true;
border.vertices = [(0.0, 0.0), (width, 0.0), (width, height), (0.0, height)]
.into_iter()
.map(|(x, y)| LwVertex::new(Vector2::new(x, y)))
.collect();
CmdResult::CommitAndZoom {
entity: EntityType::LwPolyline(border),
p1: DVec3::ZERO,
p2: DVec3::new(width, height, 0.0),
}
}
}
/// A positive number, or `default` for an empty answer.
fn positive(text: &str, default: f64) -> Option<f64> {
if text.is_empty() {
return Some(default);
}
crate::entities::common::parse_typed_length(text).filter(|value| *value > 0.0)
}
impl CadCommand for MvsetupCommand {
fn name(&self) -> &'static str {
"MVSETUP"
}
fn prompt(&self) -> String {
t!(match self.step {
Step::PaperSpace => "MVSETUP Enable paper space? [No/Yes] <Y>:",
Step::Scale => "MVSETUP Enter the scale factor <1>:",
Step::Width => "MVSETUP Enter the paper width:",
Step::Height => "MVSETUP Enter the paper height:",
Step::Option => "MVSETUP Enter an option [Create/Delete objects/Scale viewports]:",
Step::Arrangement => {
"MVSETUP Enter viewport layout [Single/Engineering/Array] <Single>:"
}
Step::FirstCorner => {
"MVSETUP Specify first corner of bounding area for viewport(s) <Sheet>:"
}
Step::SecondCorner => "MVSETUP Specify opposite corner:",
Step::Columns => "MVSETUP Enter number of viewports in X direction <2>:",
Step::Rows => "MVSETUP Enter number of viewports in Y direction <2>:",
Step::GapX => "MVSETUP Specify distance between viewports in X direction <0>:",
Step::GapY => "MVSETUP Specify distance between viewports in Y direction <0>:",
Step::Delete => "MVSETUP Select the objects to delete:",
Step::Viewports => "MVSETUP Select the viewports to scale:",
Step::PaperUnits => "MVSETUP Enter the number of paper space units <1>:",
Step::ModelUnits => "MVSETUP Enter the number of model space units <1>:",
})
.into_owned()
}
fn options(&self) -> Vec<CmdOption> {
match self.step {
Step::PaperSpace => vec![CmdOption::new("No", "N"), CmdOption::new("Yes", "Y")],
Step::Option => vec![
CmdOption::new("Create", "C"),
CmdOption::new("Delete objects", "D"),
CmdOption::new("Scale viewports", "S"),
],
Step::Arrangement => vec![
CmdOption::new("Single", "S"),
CmdOption::new("Engineering", "E"),
CmdOption::new("Array", "A"),
],
_ => Vec::new(),
}
}
fn wants_text_input(&self) -> bool {
!matches!(self.step, Step::Delete | Step::Viewports)
}
fn needs_entity_pick(&self) -> bool {
matches!(self.step, Step::Delete | Step::Viewports)
}
fn entity_pick_highlights_hover(&self) -> bool {
true
}
fn on_entity_pick(&mut self, handle: Handle, _pt: DVec3) -> CmdResult {
if !handle.is_null() && !self.picked.contains(&handle) {
self.picked.push(handle);
}
CmdResult::NeedPoint
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let text = text.trim();
let word = text.trim_start_matches('_').to_ascii_uppercase();
match self.step {
Step::PaperSpace => match word.as_str() {
"N" | "NO" => self.step = Step::Scale,
"" | "Y" | "YES" => {
self.step = Step::Option;
return Some(CmdResult::MviewSwitchLayout(self.layout.clone()));
}
_ => return None,
},
Step::Scale => {
self.scale = positive(text, 1.0)?;
self.step = Step::Width;
}
Step::Width => {
self.width = positive(text, f64::NAN).filter(|value| value.is_finite())?;
self.step = Step::Height;
}
Step::Height => {
let height = positive(text, f64::NAN).filter(|value| value.is_finite())?;
return Some(self.sheet_border(height));
}
Step::Option => match word.as_str() {
"C" | "CREATE" => self.step = Step::Arrangement,
"D" | "DELETE" => self.step = Step::Delete,
"S" | "SCALE" => self.step = Step::Viewports,
_ => return None,
},
Step::Arrangement => {
self.arrangement = match word.as_str() {
"" | "S" | "SINGLE" | "1" => Arrangement::Single,
"E" | "ENGINEERING" | "2" => Arrangement::Engineering,
"A" | "ARRAY" | "3" => Arrangement::Array,
_ => return None,
};
self.step = Step::FirstCorner;
}
Step::FirstCorner if text.is_empty() => {
let ((x0, y0), (x1, y1)) = self.paper_bounds;
self.area = (
DVec2::new(x0.min(x1), y0.min(y1)),
DVec2::new(x0.max(x1), y0.max(y1)),
);
return Some(self.after_area());
}
Step::Columns | Step::Rows => {
let count = if text.is_empty() {
2
} else {
text.parse::<u32>().ok().filter(|count| (1..=100).contains(count))?
};
if self.step == Step::Columns {
self.columns = count;
self.step = Step::Rows;
} else {
self.rows = count;
self.step = Step::GapX;
}
}
Step::GapX | Step::GapY => {
let gap = if text.is_empty() {
0.0
} else {
crate::entities::common::parse_typed_length(text).filter(|v| *v >= 0.0)?
};
if self.step == Step::GapY {
return Some(self.create(gap));
}
self.gap_x = gap;
self.step = Step::GapY;
}
Step::PaperUnits => {
self.paper_units = positive(text, 1.0)?;
self.step = Step::ModelUnits;
}
Step::ModelUnits => {
let model_units = positive(text, 1.0)?;
return Some(CmdResult::ScaleViewports {
handles: std::mem::take(&mut self.picked),
factor: self.paper_units / model_units,
});
}
Step::FirstCorner | Step::SecondCorner | Step::Delete | Step::Viewports => {
return None
}
}
Some(CmdResult::NeedPoint)
}
fn on_point(&mut self, pt: DVec3) -> CmdResult {
match self.step {
Step::FirstCorner => {
self.first = pt.truncate();
self.step = Step::SecondCorner;
CmdResult::NeedPoint
}
Step::SecondCorner => {
let second = pt.truncate();
self.area = (self.first.min(second), self.first.max(second));
self.after_area()
}
_ => CmdResult::NeedPoint,
}
}
fn on_enter(&mut self) -> CmdResult {
match self.step {
Step::Delete => {
self.step = Step::Option;
let erased = std::mem::take(&mut self.picked);
if erased.is_empty() {
return CmdResult::NeedPoint;
}
CmdResult::ReplaceManyContinue(
erased.into_iter().map(|handle| (handle, Vec::new())).collect(),
)
}
Step::Viewports if self.picked.is_empty() => CmdResult::Cancel,
Step::Viewports => {
self.step = Step::PaperUnits;
CmdResult::NeedPoint
}
Step::Option | Step::Width | Step::Height | Step::SecondCorner => CmdResult::Cancel,
_ => self.on_text_input("").unwrap_or(CmdResult::NeedPoint),
}
}
}
inventory::submit!(crate::command::CommandRegistration { names: &["MVSETUP"] });
+41 -8
View File
@@ -6656,6 +6656,12 @@ impl Scene {
let Some(viewport) = self.explicit_viewport_handle() else {
return false;
};
self.set_viewport_scale_factor_for(viewport, factor)
}
/// Scale `viewport` to `factor` paper units per model unit, as
/// [`Self::set_viewport_scale_factor`] does for the active one.
pub fn set_viewport_scale_factor_for(&mut self, viewport: Handle, factor: f64) -> bool {
let unit_factor = self.annotation_scale_unit_factor();
let named = self
.document
@@ -12990,22 +12996,49 @@ vis_index={:.1} visible_probe={:.1}",
Some(e) => e,
None => return,
};
let (min, max) = (min.as_dvec3(), max.as_dvec3());
let center = (min + max) * 0.5;
let content_w = (max.x - min.x).max(1e-3);
let content_h = (max.y - min.y).max(1e-3);
let vp = match self.document.get_entity_mut(vp_handle) {
Some(codec::EntityType::Viewport(vp)) => vp,
_ => return,
};
// Set the view target to the model-space centroid (XY plane, z=0).
vp.view_target.x = center.x as f64;
vp.view_target.y = center.y as f64;
vp.view_target.z = 0.0;
let direction = glam::DVec3::new(
vp.view_direction.x,
vp.view_direction.y,
vp.view_direction.z,
)
.normalize_or(glam::DVec3::Z);
// The extents box as seen along the view direction: its span across
// the view's right and up axes. Looking down Z that is its X/Y size.
let right = glam::DVec3::Z.cross(direction).normalize_or(glam::DVec3::X);
let up = direction.cross(right);
let (mut span_right, mut span_up) = ((f64::MAX, f64::MIN), (f64::MAX, f64::MIN));
for corner in 0..8 {
let point = glam::DVec3::new(
if corner & 1 == 0 { min.x } else { max.x },
if corner & 2 == 0 { min.y } else { max.y },
if corner & 4 == 0 { min.z } else { max.z },
);
let (along_right, along_up) = (point.dot(right), point.dot(up));
span_right = (span_right.0.min(along_right), span_right.1.max(along_right));
span_up = (span_up.0.min(along_up), span_up.1.max(along_up));
}
let content_w = (span_right.1 - span_right.0).max(1e-3);
let content_h = (span_up.1 - span_up.0).max(1e-3);
// Aim at the model's centre; a plan view keeps it on the XY plane.
vp.view_target.x = center.x;
vp.view_target.y = center.y;
vp.view_target.z = if direction == glam::DVec3::Z {
0.0
} else {
center.z
};
// Choose the scale that fits both dimensions with the margin.
let scale_w = vp.width / (content_w as f64 * margin);
let scale_h = vp.height / (content_h as f64 * margin);
let scale_w = vp.width / (content_w * margin);
let scale_h = vp.height / (content_h * margin);
let fit_scale = scale_w.min(scale_h).min(1000.0).max(1e-6);
vp.custom_scale = fit_scale;