From 3e28604752160135694fb5a222916ebc3d35c529 Mon Sep 17 00:00:00 2001 From: ramox81 <184937705+ramox81@users.noreply.github.com> Date: Mon, 21 Sep 2026 15:08:44 +0300 Subject: [PATCH] Dimensional constraints: DCFORM, DIMCONSTRAINT options, -PARAMETERS, value prompt, save without display overrides DCFORM sets the annotational or dynamic form and continues into the DIMCONSTRAINT option prompt, whose wording and last-used default match the reference. -PARAMETERS manages parameters from the command line; a double-clicked constraint dimension opens its value prompt. Dynamic dimensions rescale on every camera change and their display overrides stay out of the saved file. A driving dimension between an entity's own ends no longer has its length retained, so a new value moves the second point along the dimension axis; parameter edits hold the first constraint point. Co-Authored-By: Claude Fable 5.1 --- src/app/command_driver.rs | 274 ++++++++++++++++++++++- src/app/commands/draw.rs | 138 +++++++++++- src/app/mod.rs | 6 + src/app/update/file.rs | 6 +- src/app/update/viewport.rs | 9 + src/modules/parametric/dim_constraint.rs | 155 ++++++++++++- src/modules/parametric/mod.rs | 9 +- src/modules/parametric/parameters_cli.rs | 146 ++++++++++++ src/scene/dwg_native_constraints.rs | 2 +- src/scene/mod.rs | 7 +- src/scene/parametric_constraints.rs | 77 ++++++- src/scene/parametric_solve.rs | 15 ++ 12 files changed, 810 insertions(+), 34 deletions(-) create mode 100644 src/modules/parametric/parameters_cli.rs diff --git a/src/app/command_driver.rs b/src/app/command_driver.rs index 84b3f3b6d..7e96ea001 100644 --- a/src/app/command_driver.rs +++ b/src/app/command_driver.rs @@ -3,6 +3,28 @@ use crate::command::{CmdResult, SelectionEntity, StepInput}; use acadrust::Handle; use iced::Task; +/// `old` as a whole identifier in `source` becomes `new`. +fn replace_identifier(source: &str, old: &str, new: &str) -> String { + let mut out = String::with_capacity(source.len()); + let mut token = String::new(); + let flush = |token: &mut String, out: &mut String| { + if !token.is_empty() { + out.push_str(if token == old { new } else { token.as_str() }); + token.clear(); + } + }; + for c in source.chars() { + if c.is_alphanumeric() || c == '_' { + token.push(c); + } else { + flush(&mut token, &mut out); + out.push(c); + } + } + flush(&mut token, &mut out); + out +} + impl OpenCADStudio { pub(super) fn reject_locked_edit(&mut self, i: usize, handle: Handle) -> bool { let Some(layer) = self.tabs[i].scene.locked_layer_name(handle) else { @@ -1147,6 +1169,213 @@ impl OpenCADStudio { } } + /// `Dynamic` or `Annotational`, the DCFORM setting. + pub(crate) fn constraint_form_name(&self) -> &'static str { + if self.constraint_form_annotational { + "Annotational" + } else { + "Dynamic" + } + } + + /// The value prompt a double-clicked constraint dimension opens. + pub(crate) fn dynamic_dimension_value_command( + &self, + i: usize, + handle: Handle, + ) -> Option { + use crate::scene::named_parameters::DrivingValue; + let scene = &self.tabs[i].scene; + for set in &scene.parametric_constraints { + let Some((id, _)) = set + .dimensions + .iter() + .find(|(_, dimension)| **dimension == handle) + else { + continue; + }; + let constraint = set.get(*id)?; + let Some(DrivingValue::Named(name)) = &constraint.driving_param else { + return None; + }; + let table = if set.local_parameters.is_empty() { + scene.named_parameters() + } else { + &set.local_parameters + }; + let current = table + .get(name) + .map(|parameter| parameter.source.trim().to_string()) + .unwrap_or_default(); + return Some(crate::modules::parametric::DimensionValueCommand::new( + name.clone(), + current, + )); + } + None + } + + /// Applies `expression` or `newname=expression` to parameter `name`: + /// the dimension value prompt and -PARAMETERS Edit. + pub(crate) fn apply_parameter_input(&mut self, i: usize, name: &str, input: &str) { + let input = input.trim(); + let (target, expression) = match input.split_once('=') { + Some((new_name, expression)) => { + (new_name.trim().to_string(), expression.trim().to_string()) + } + None => (name.to_string(), input.to_string()), + }; + if expression.is_empty() { + return; + } + if target != name { + if let Err(error) = self.rename_parameter(i, name, &target) { + self.command_line.push_error(&error); + return; + } + } + let mut table = self.tabs[i].scene.named_parameters().clone(); + if let Err(error) = table.set(&target, &expression) { + self.command_line.push_error(&error.to_string()); + return; + } + if !table + .resolve(&target) + .is_ok_and(|value| value.is_finite()) + { + self.command_line.push_error("Invalid expression."); + return; + } + let pending = self.begin_undo(i, "Edit parameter", 0, true); + self.tabs[i].scene.record_undo_named_parameters_before(); + self.tabs[i].scene.named_parameters = table; + self.resolve_named_parameter_edit(i, &target); + self.tabs[i].scene.refresh_dynamic_dimension_texts(); + self.tabs[i].dirty = true; + if let Some(pd) = pending { + self.commit_undo_delta(i, pd); + } + } + + /// -PARAMETERS New. + pub(crate) fn create_parameter(&mut self, i: usize, name: &str, expression: &str) { + if self.tabs[i].scene.named_parameters().contains(name) { + self.command_line + .push_error(&format!("Parameter {name} already exists.")); + return; + } + let mut table = self.tabs[i].scene.named_parameters().clone(); + if let Err(error) = table.set(name, expression) { + self.command_line.push_error(&error.to_string()); + return; + } + let pending = self.begin_undo(i, "New parameter", 0, true); + self.tabs[i].scene.record_undo_named_parameters_before(); + self.tabs[i].scene.named_parameters = table; + self.tabs[i].scene.sync_native_parametric_graph(); + self.tabs[i].dirty = true; + if let Some(pd) = pending { + self.commit_undo_delta(i, pd); + } + } + + /// Renames a parameter everywhere: the table, the expressions that use + /// it and the constraints it drives. + pub(crate) fn rename_parameter(&mut self, i: usize, old: &str, new: &str) -> Result<(), String> { + use crate::scene::named_parameters::{is_reserved_name, is_valid_name, DrivingValue}; + let table = self.tabs[i].scene.named_parameters().clone(); + let Some(source) = table.get(old).map(|parameter| parameter.source.clone()) else { + return Err(format!("Parameter {old} not found.")); + }; + if !is_valid_name(new) || is_reserved_name(new) || table.contains(new) { + return Err(format!("Invalid parameter name {new}.")); + } + let mut renamed = table.clone(); + renamed.set(new, &source).map_err(|error| error.to_string())?; + for parameter in table.iter() { + if parameter.name == old { + continue; + } + let rewritten = replace_identifier(¶meter.source, old, new); + if rewritten != parameter.source { + renamed + .set(¶meter.name, &rewritten) + .map_err(|error| error.to_string())?; + } + } + renamed.remove(old); + let pending = self.begin_undo(i, "Rename parameter", 0, true); + self.tabs[i].scene.record_undo_named_parameters_before(); + self.tabs[i].scene.named_parameters = renamed; + let scopes: Vec<_> = self.tabs[i] + .scene + .parametric_constraints + .iter() + .map(|set| set.scope) + .collect(); + for scope in scopes { + let before = self.tabs[i] + .scene + .parametric_constraint_set(scope) + .filter(|set| { + set.constraints.iter().any(|constraint| { + matches!(&constraint.driving_param, Some(DrivingValue::Named(name)) if name == old) + }) + }) + .cloned(); + let Some(before) = before else { + continue; + }; + self.tabs[i] + .scene + .record_undo_parametric_constraints_before(scope, before); + let set = self.tabs[i].scene.parametric_constraint_set_mut(scope); + for constraint in &mut set.constraints { + if matches!(&constraint.driving_param, Some(DrivingValue::Named(name)) if name == old) { + constraint.driving_param = Some(DrivingValue::Named(new.to_string())); + } + } + } + self.tabs[i].scene.refresh_dynamic_dimension_texts(); + self.tabs[i].scene.sync_native_parametric_graph(); + self.tabs[i].dirty = true; + if let Some(pd) = pending { + self.commit_undo_delta(i, pd); + } + Ok(()) + } + + /// -PARAMETERS Delete: a parameter no constraint drives with. + pub(crate) fn delete_parameter(&mut self, i: usize, name: &str) { + use crate::scene::named_parameters::DrivingValue; + if !self.tabs[i].scene.named_parameters().contains(name) { + self.command_line + .push_error(&format!("Parameter {name} not found.")); + return; + } + let in_use = self.tabs[i] + .scene + .parametric_constraints + .iter() + .flat_map(|set| set.constraints.iter()) + .any(|constraint| { + matches!(&constraint.driving_param, Some(DrivingValue::Named(used)) if used == name) + }); + if in_use { + self.command_line + .push_error(&format!("Parameter {name} is used by a constraint.")); + return; + } + let pending = self.begin_undo(i, "Delete parameter", 0, true); + self.tabs[i].scene.record_undo_named_parameters_before(); + self.tabs[i].scene.named_parameters_mut().remove(name); + self.tabs[i].scene.sync_native_parametric_graph(); + self.tabs[i].dirty = true; + if let Some(pd) = pending { + self.commit_undo_delta(i, pd); + } + } + fn remove_parametric_constraint( &mut self, id: crate::scene::parametric_constraints::ConstraintId, @@ -1344,7 +1573,25 @@ impl OpenCADStudio { .into_iter() .map(|h| (h, crate::scene::ChangeKind::Modified)) .collect(); - self.tabs[i].scene.bump_entities(&changes); + // A changed value moves a dimensional constraint's second point; its + // first point stays, as in the reference. + let anchors: Vec = self.tabs[i] + .scene + .parametric_constraints + .iter() + .flat_map(|set| set.constraints.iter()) + .filter(|c| { + c.enabled + && matches!(&c.driving_param, Some(crate::scene::named_parameters::DrivingValue::Named(n)) if n == name) + }) + .filter_map(|c| c.refs.first().copied()) + .filter(|reference| reference.marker.is_some()) + .collect(); + self.tabs[i].scene.bump_entities_with_parametric_policy( + &changes, + &anchors, + self.constraint_solve_mode, + ); } /// Commits one field of one Parameters-section row (Properties panel) — @@ -3609,9 +3856,17 @@ impl OpenCADStudio { return Task::none(); } }; + // DCFORM Annotational: an ordinary plotted dimension that shows + // the value at dimension precision. + let annotational = self.constraint_form_annotational; + let source = if annotational { + format!("{value:.4}") + } else { + expression.clone() + }; let text = dynamic_dimension_text( &name, - &expression, + &source, value, self.tabs[i].scene.constraint_name_format, ); @@ -3641,11 +3896,13 @@ impl OpenCADStudio { } // A dynamic dimension draws in the constraint gray, not the // current color. - entity.common_mut().color = acadrust::types::Color::Rgb { - r: 103, - g: 109, - b: 118, - }; + if !annotational { + entity.common_mut().color = acadrust::types::Color::Rgb { + r: 103, + g: 109, + b: 118, + }; + } let constraints_before = self.tabs[i] .scene .parametric_constraint_set(scope) @@ -3664,6 +3921,9 @@ impl OpenCADStudio { self.tabs[i].scene.record_undo_named_parameters_before(); self.tabs[i].scene.named_parameters = table; let dimension = self.tabs[i].scene.add_entity(entity); + if annotational { + self.tabs[i].scene.mark_dimension_annotational(dimension); + } let set = self.tabs[i].scene.parametric_constraint_set_mut(scope); let id = set.add(kind, refs, Some(DrivingValue::Named(name))); set.dimensions.insert(id, dimension); diff --git a/src/app/commands/draw.rs b/src/app/commands/draw.rs index cf9d4686d..aa6d28f11 100644 --- a/src/app/commands/draw.rs +++ b/src/app/commands/draw.rs @@ -1310,6 +1310,7 @@ impl OpenCADStudio { } "DCCONVERT" => { + self.dim_constraint_last = "Convert"; let handles = self.tabs[i].scene.selected_handles_in_order(); if handles.is_empty() { use crate::modules::draw::select::SelectObjectsCommand; @@ -1508,14 +1509,129 @@ impl OpenCADStudio { "DIMCONSTRAINT" => { use crate::modules::parametric::DimConstraintMenuCommand; - // Only the dynamic form exists here. - self.command_line - .push_output("Current settings: Constraint form = Dynamic"); - let new_cmd = DimConstraintMenuCommand; + self.command_line.push_output(&format!( + "Current settings: Constraint form = {}", + self.constraint_form_name() + )); + let new_cmd = DimConstraintMenuCommand::new(self.dim_constraint_last); self.command_line.push_info(&new_cmd.prompt()); self.tabs[i].active_cmd = Some(Box::new(new_cmd)); } + "DCFORM" => { + use crate::modules::parametric::ConstraintFormCommand; + let new_cmd = ConstraintFormCommand::new(self.constraint_form_annotational); + self.command_line.push_info(&new_cmd.prompt()); + self.tabs[i].active_cmd = Some(Box::new(new_cmd)); + } + + // DCFORM's answer, then on into DIMCONSTRAINT's options as the + // reference does. + cmd if cmd.starts_with("DCFORM_SET ") => { + use crate::modules::parametric::DimConstraintMenuCommand; + self.constraint_form_annotational = cmd + .trim_start_matches("DCFORM_SET ") + .trim() + .eq_ignore_ascii_case("Annotational"); + self.command_line.push_output(&format!( + "Current settings: Constraint form = {}", + self.constraint_form_name() + )); + let new_cmd = DimConstraintMenuCommand::new(self.dim_constraint_last); + self.command_line.push_info(&new_cmd.prompt()); + self.tabs[i].active_cmd = Some(Box::new(new_cmd)); + } + + // A dynamic dimension's value prompt (double-click). + cmd if cmd.starts_with("DCVALUE ") => { + let rest = cmd.trim_start_matches("DCVALUE ").trim(); + if let Some((name, input)) = rest.split_once(' ') { + self.apply_parameter_input(i, name.trim(), input); + } + } + + "-PARAMETERS" => { + use crate::modules::parametric::ParametersCliCommand; + let new_cmd = ParametersCliCommand::new(); + self.command_line.push_info(&new_cmd.prompt()); + self.tabs[i].active_cmd = Some(Box::new(new_cmd)); + } + + cmd if cmd.starts_with("-PARAMETERS ") => { + let rest = cmd.trim_start_matches("-PARAMETERS ").trim(); + let (op, args) = rest.split_once(' ').unwrap_or((rest, "")); + match op { + "LIST" => { + let rule = "-".repeat(74); + let rows: Vec = { + let table = self.tabs[i].scene.named_parameters(); + table + .iter() + .map(|parameter| { + let value = table + .resolve(¶meter.name) + .map(|value| format!("{value:.4}")) + .unwrap_or_else(|_| "**".to_string()); + format!( + "Parameter: {:<12} Expression: {:<21} Value: {value}", + parameter.name, parameter.source + ) + }) + .collect() + }; + self.command_line.push_output(&rule); + for row in rows { + self.command_line.push_output(&row); + } + self.command_line.push_output(&rule); + } + "NEW" => { + if let Some((name, expression)) = args.split_once(' ') { + self.create_parameter(i, name.trim(), expression.trim()); + } + } + "EDIT" => { + use crate::modules::parametric::ParametersCliCommand; + let name = args.trim().to_string(); + let old = { + let table = self.tabs[i].scene.named_parameters(); + table.get(&name).map(|parameter| { + let value = table + .resolve(&name) + .map(|value| format!("{value:.4}")) + .unwrap_or_else(|_| "**".to_string()); + format!("Old Expression = {}, Value = {value}", parameter.source) + }) + }; + match old { + Some(line) => { + self.command_line.push_output(&line); + let new_cmd = ParametersCliCommand::edit_expression(name); + self.command_line.push_info(&new_cmd.prompt()); + self.tabs[i].active_cmd = Some(Box::new(new_cmd)); + } + None => self + .command_line + .push_error(&format!("Parameter {name} not found.")), + } + } + "SET" => { + if let Some((name, expression)) = args.split_once(' ') { + self.apply_parameter_input(i, name.trim(), expression.trim()); + } + } + "RENAME" => { + if let Some((old, new)) = args.split_once(' ') { + if let Err(error) = self.rename_parameter(i, old.trim(), new.trim()) { + self.command_line.push_error(&error); + } + } + } + "DELETE" => self.delete_parameter(i, args.trim()), + _ => {} + } + } + "EDCONSTRAINT" => { use crate::modules::parametric::EqualDistanceConstraintCommand; let new_cmd = EqualDistanceConstraintCommand::new(); @@ -1765,6 +1881,12 @@ impl OpenCADStudio { "DCALIGNED" => DimConstraintAxis::Aligned, _ => DimConstraintAxis::Linear, }; + self.dim_constraint_last = match cmd { + "DCHORIZONTAL" => "Horizontal", + "DCVERTICAL" => "Vertical", + "DCALIGNED" => "Aligned", + _ => "Linear", + }; let name = next_dimensional_parameter_name(self.tabs[i].scene.named_parameters()); // Both constraint points are picked inside the command. self.tabs[i].scene.deselect_all(); @@ -1774,6 +1896,11 @@ impl OpenCADStudio { } "DCONSTRAINT" | "DCRADIUS" | "DCDIAMETER" => { + if cmd == "DCRADIUS" { + self.dim_constraint_last = "Radius"; + } else if cmd == "DCDIAMETER" { + self.dim_constraint_last = "Diameter"; + } let handles = self.tabs[i].scene.selected_handles_in_order(); if handles.is_empty() { use crate::modules::draw::select::SelectObjectsCommand; @@ -1813,6 +1940,9 @@ impl OpenCADStudio { } "ACONSTRAINT" | "DCANGULAR" => { + if cmd == "DCANGULAR" { + self.dim_constraint_last = "ANgular"; + } let handles = self.tabs[i].scene.selected_handles_in_order(); if handles.is_empty() { use crate::modules::draw::select::SelectObjectsCommand; diff --git a/src/app/mod.rs b/src/app/mod.rs index fd1c73551..674622972 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -612,6 +612,10 @@ pub(super) struct OpenCADStudio { pub constraint_solve_mode: bool, pub constraint_infer: bool, pub constraint_bar_display: i16, + /// DCFORM: new dimensional constraints use the annotational form. + pub constraint_form_annotational: bool, + /// The dimensional constraint DIMCONSTRAINT offers by default: the last one used. + pub dim_constraint_last: &'static str, pub constraint_bar_mode: i16, /// Minutes between autosaves to a `.sv$` recovery file (SAVETIME command); /// 0 disables autosave. @@ -3949,6 +3953,8 @@ impl OpenCADStudio { constraint_solve_mode: true, constraint_infer: false, constraint_bar_display: 3, + constraint_form_annotational: false, + dim_constraint_last: "Aligned", constraint_bar_mode: 4095, savetime_min: 10, default_bg_color: None, diff --git a/src/app/update/file.rs b/src/app/update/file.rs index bb43488b2..dd93a679d 100644 --- a/src/app/update/file.rs +++ b/src/app/update/file.rs @@ -1464,7 +1464,7 @@ impl OpenCADStudio { self.prepare_native_save(i); let version = self.tabs[i].scene.document.version; - let snapshot = self.tabs[i].scene.document.clone(); + let snapshot = self.tabs[i].scene.document_for_save(); crate::io::save_owned_as_version_atomic( snapshot, &path, @@ -1893,7 +1893,7 @@ impl OpenCADStudio { path: std::path::PathBuf, ) -> Task { let i = self.active_tab; - let document = self.tabs[i].scene.document.clone(); + let document = self.tabs[i].scene.document_for_save(); let handles: Vec<_> = self.tabs[i].scene.selected.iter().copied().collect(); let worker_name = block_name.clone(); let worker_path = path.clone(); @@ -2298,7 +2298,7 @@ impl OpenCADStudio { crate::ui::wrap_bar::dropdown_bounds(crate::app::view::VIEWPORT_CAPTURE_BOUNDS_ID) }); let clone_started = iced::time::Instant::now(); - let mut snapshot = self.tabs[i].scene.document.clone(); + let mut snapshot = self.tabs[i].scene.document_for_save(); // Save-As across folders: rebase relative reference paths onto the // new base dir inside the snapshot only (live strings are untouched). if purpose == crate::app::SavePurpose::SaveAs { diff --git a/src/app/update/viewport.rs b/src/app/update/viewport.rs index dee93d74c..4e9d2006e 100644 --- a/src/app/update/viewport.rs +++ b/src/app/update/viewport.rs @@ -5060,6 +5060,15 @@ properties={:.1}ms picked={}", { return Task::none(); } + // A constraint dimension edits its parameter from the + // command line, standing in for the reference's in-place + // value editor. + if let Some(prompt) = self.dynamic_dimension_value_command(i, handle) { + use crate::command::CadCommand; + self.command_line.push_info(&prompt.prompt()); + self.tabs[i].active_cmd = Some(Box::new(prompt)); + return Task::none(); + } // Any text-bearing entity opens its in-place editor // (plain box or rich MText editor, per type). A // Leader resolves to the entity it annotates. diff --git a/src/modules/parametric/dim_constraint.rs b/src/modules/parametric/dim_constraint.rs index 522119203..d3e5dadf4 100644 --- a/src/modules/parametric/dim_constraint.rs +++ b/src/modules/parametric/dim_constraint.rs @@ -392,9 +392,16 @@ impl CadCommand for DimConstraintCommand { /// `DIMCONSTRAINT`: the reference's option front end for the dimensional /// constraint family; each choice runs the focused command. -pub struct DimConstraintMenuCommand; +pub struct DimConstraintMenuCommand { + /// The option Enter takes: the dimensional constraint used last. + default: &'static str, +} impl DimConstraintMenuCommand { + pub fn new(default: &'static str) -> Self { + Self { default } + } + fn dispatch(keyword: &str) -> Option<&'static str> { Some(match keyword { "L" | "LINEAR" => "DCLINEAR", @@ -404,10 +411,24 @@ impl DimConstraintMenuCommand { "AN" | "ANGULAR" => "DCANGULAR", "R" | "RADIAL" | "RADIUS" => "DCRADIUS", "D" | "DIAMETER" => "DCDIAMETER", + "F" | "FORM" => "DCFORM", "C" | "CONVERT" => "DCCONVERT", _ => return None, }) } + + fn command_for_label(label: &str) -> &'static str { + match label { + "Linear" => "DCLINEAR", + "Horizontal" => "DCHORIZONTAL", + "Vertical" => "DCVERTICAL", + "ANgular" => "DCANGULAR", + "Radius" => "DCRADIUS", + "Diameter" => "DCDIAMETER", + "Convert" => "DCCONVERT", + _ => "DCALIGNED", + } + } } impl CadCommand for DimConstraintMenuCommand { @@ -416,7 +437,10 @@ impl CadCommand for DimConstraintMenuCommand { } fn prompt(&self) -> String { - "DIMCONSTRAINT Enter dimensional constraint option [Linear/Horizontal/Vertical/Aligned/ANgular/Radial/Diameter/Convert] :".to_string() + format!( + "DIMCONSTRAINT Enter a dimensional constraint option [Linear/Horizontal/Vertical/Aligned/ANgular/Radius/Diameter/Form/Convert] <{}>:", + self.default + ) } fn options(&self) -> Vec { @@ -426,8 +450,9 @@ impl CadCommand for DimConstraintMenuCommand { CmdOption::new("Vertical", "V"), CmdOption::new("Aligned", "A"), CmdOption::new("ANgular", "AN"), - CmdOption::new("Radial", "R"), + CmdOption::new("Radius", "R"), CmdOption::new("Diameter", "D"), + CmdOption::new("Form", "F"), CmdOption::new("Convert", "C"), ] } @@ -446,7 +471,129 @@ impl CadCommand for DimConstraintMenuCommand { } fn on_enter(&mut self) -> CmdResult { - CmdResult::Dispatch("DCALIGNED".to_string()) + CmdResult::Dispatch(Self::command_for_label(self.default).to_string()) + } + + fn on_escape(&mut self) -> CmdResult { + CmdResult::Cancel + } +} + +/// `DCFORM`: `Enter constraint form [Annotational/Dynamic] :`; +/// the host records the answer and continues into DIMCONSTRAINT's option +/// prompt, as the reference does. +pub struct ConstraintFormCommand { + annotational: bool, +} + +impl ConstraintFormCommand { + pub fn new(annotational: bool) -> Self { + Self { annotational } + } + + fn current(&self) -> &'static str { + if self.annotational { + "Annotational" + } else { + "Dynamic" + } + } +} + +impl CadCommand for ConstraintFormCommand { + fn name(&self) -> &'static str { + "DCFORM" + } + + fn prompt(&self) -> String { + format!( + "DCFORM Enter constraint form [Annotational/Dynamic] <{}>:", + self.current() + ) + } + + fn options(&self) -> Vec { + vec![ + CmdOption::new("Annotational", "A"), + CmdOption::new("Dynamic", "D"), + ] + } + + fn wants_text_input(&self) -> bool { + true + } + + fn point_step_accepts_keywords(&self) -> bool { + true + } + + fn on_text_input(&mut self, text: &str) -> Option { + let keyword = text.trim().trim_start_matches('_').to_ascii_uppercase(); + let form = match keyword.as_str() { + "A" | "ANNOTATIONAL" => "Annotational", + "D" | "DYNAMIC" => "Dynamic", + _ => return None, + }; + Some(CmdResult::Dispatch(format!("DCFORM_SET {form}"))) + } + + fn on_point(&mut self, _point: DVec3) -> CmdResult { + CmdResult::NeedPoint + } + + fn on_enter(&mut self) -> CmdResult { + CmdResult::Dispatch(format!("DCFORM_SET {}", self.current())) + } + + fn on_escape(&mut self) -> CmdResult { + CmdResult::Cancel + } +} + +/// The value prompt a double-clicked dynamic dimension opens, standing in +/// for the reference's in-place editor; `name=expression` also renames. +pub struct DimensionValueCommand { + name: String, + current: String, +} + +impl DimensionValueCommand { + pub fn new(name: String, current: String) -> Self { + Self { name, current } + } +} + +impl CadCommand for DimensionValueCommand { + fn name(&self) -> &'static str { + "DCVALUE" + } + + fn prompt(&self) -> String { + format!( + "DCVALUE Enter value or name and value <{}={}>:", + self.name, self.current + ) + } + + fn wants_text_input(&self) -> bool { + true + } + + fn point_step_accepts_keywords(&self) -> bool { + true + } + + fn on_text_input(&mut self, text: &str) -> Option { + let text = text.trim(); + (!text.is_empty()).then(|| CmdResult::Dispatch(format!("DCVALUE {} {text}", self.name))) + } + + fn on_point(&mut self, _point: DVec3) -> CmdResult { + CmdResult::NeedPoint + } + + fn on_enter(&mut self) -> CmdResult { + CmdResult::Cancel } fn on_escape(&mut self) -> CmdResult { diff --git a/src/modules/parametric/mod.rs b/src/modules/parametric/mod.rs index 6353d3672..c064008d9 100644 --- a/src/modules/parametric/mod.rs +++ b/src/modules/parametric/mod.rs @@ -5,6 +5,7 @@ mod coincident; mod concentric; mod dim_constraint; +mod parameters_cli; mod constraint_bar; mod equal_distance; #[path = "equal.rs"] @@ -26,7 +27,11 @@ mod tools; mod value; pub use coincident::{coincident_tool, CoincidentConstraintCommand}; pub use concentric::ConcentricConstraintCommand; -pub use dim_constraint::{DimConstraintAxis, DimConstraintCommand, DimConstraintMenuCommand}; +pub use dim_constraint::{ + ConstraintFormCommand, DimConstraintAxis, DimConstraintCommand, DimConstraintMenuCommand, + DimensionValueCommand, +}; +pub use parameters_cli::ParametersCliCommand; pub use constraint_bar::ConstraintBarOptionCommand; pub use equal_command::EqualConstraintCommand; pub use equal_distance::{equal_distance_tool, EqualDistanceConstraintCommand}; @@ -158,7 +163,7 @@ inventory::submit!(crate::command::CommandRegistration { names: &[ "AUTOCONSTRAIN", "CONSTRAINTSETTINGS", "GCSMOOTH", "GCSHOW", "GCHIDE", "GCRESET", "GCSHOWALL", "GCHIDEALL", "DCSHOW", "DCHIDE", "DCSHOWALL", "DCHIDEALL", - "DCCONVERT", "DELCONSTRAINT", "DIMCONSTRAINT", + "DCCONVERT", "DELCONSTRAINT", "DIMCONSTRAINT", "DCFORM", "-PARAMETERS", ] }); diff --git a/src/modules/parametric/parameters_cli.rs b/src/modules/parametric/parameters_cli.rs new file mode 100644 index 000000000..ad6e8986e --- /dev/null +++ b/src/modules/parametric/parameters_cli.rs @@ -0,0 +1,146 @@ +use glam::DVec3; + +use crate::command::{CadCommand, CmdOption, CmdResult}; + +/// `-PARAMETERS`: the reference's command-line parameter manager. One run +/// performs one operation; the host answers the `LIST`, `NEW`, `EDIT`, +/// `SET`, `RENAME` and `DELETE` dispatches. +pub struct ParametersCliCommand { + step: Step, +} + +#[derive(Clone)] +enum Step { + /// `Enter a parameter option [New/Edit/Rename/Delete/?]:` + Option, + /// `Enter name for new user parameter:` + NewName, + /// `Enter expression:` + NewExpression { name: String }, + /// `Enter parameter name:` + EditName, + /// `Enter expression:` after the host printed the old expression. + EditExpression { name: String }, + /// `Enter old parameter name:` + RenameOld, + /// `Enter new parameter name:` + RenameNew { old: String }, + /// `Enter parameter name to delete:` + DeleteName, +} + +impl ParametersCliCommand { + pub fn new() -> Self { + Self { step: Step::Option } + } + + /// The expression prompt the host opens after printing the old expression. + pub fn edit_expression(name: String) -> Self { + Self { + step: Step::EditExpression { name }, + } + } +} + +impl Default for ParametersCliCommand { + fn default() -> Self { + Self::new() + } +} + +impl CadCommand for ParametersCliCommand { + fn name(&self) -> &'static str { + "-PARAMETERS" + } + + fn prompt(&self) -> String { + let text = match &self.step { + Step::Option => "Enter a parameter option [New/Edit/Rename/Delete/?]:", + Step::NewName => "Enter name for new user parameter:", + Step::NewExpression { .. } | Step::EditExpression { .. } => "Enter expression:", + Step::EditName => "Enter parameter name:", + Step::RenameOld => "Enter old parameter name:", + Step::RenameNew { .. } => "Enter new parameter name:", + Step::DeleteName => "Enter parameter name to delete:", + }; + format!("-PARAMETERS {text}") + } + + fn options(&self) -> Vec { + match self.step { + Step::Option => vec![ + CmdOption::new("New", "N"), + CmdOption::new("Edit", "E"), + CmdOption::new("Rename", "R"), + CmdOption::new("Delete", "D"), + CmdOption::new("?", "?"), + ], + _ => Vec::new(), + } + } + + fn wants_text_input(&self) -> bool { + true + } + + fn point_step_accepts_keywords(&self) -> bool { + true + } + + fn on_text_input(&mut self, text: &str) -> Option { + let text = text.trim(); + if text.is_empty() { + return None; + } + match self.step.clone() { + Step::Option => { + let keyword = text.trim_start_matches('_').to_ascii_uppercase(); + let next = match keyword.as_str() { + "N" | "NEW" => Step::NewName, + "E" | "EDIT" => Step::EditName, + "R" | "RENAME" => Step::RenameOld, + "D" | "DELETE" => Step::DeleteName, + "?" => return Some(CmdResult::Dispatch("-PARAMETERS LIST".to_string())), + _ => return None, + }; + self.step = next; + Some(CmdResult::NeedPoint) + } + Step::NewName => { + self.step = Step::NewExpression { + name: text.to_string(), + }; + Some(CmdResult::NeedPoint) + } + Step::NewExpression { name } => { + Some(CmdResult::Dispatch(format!("-PARAMETERS NEW {name} {text}"))) + } + Step::EditName => Some(CmdResult::Dispatch(format!("-PARAMETERS EDIT {text}"))), + Step::EditExpression { name } => { + Some(CmdResult::Dispatch(format!("-PARAMETERS SET {name} {text}"))) + } + Step::RenameOld => { + self.step = Step::RenameNew { + old: text.to_string(), + }; + Some(CmdResult::NeedPoint) + } + Step::RenameNew { old } => { + Some(CmdResult::Dispatch(format!("-PARAMETERS RENAME {old} {text}"))) + } + Step::DeleteName => Some(CmdResult::Dispatch(format!("-PARAMETERS DELETE {text}"))), + } + } + + fn on_point(&mut self, _point: DVec3) -> CmdResult { + CmdResult::NeedPoint + } + + fn on_enter(&mut self) -> CmdResult { + CmdResult::Cancel + } + + fn on_escape(&mut self) -> CmdResult { + CmdResult::Cancel + } +} diff --git a/src/scene/dwg_native_constraints.rs b/src/scene/dwg_native_constraints.rs index f1e4a208d..bf5901e94 100644 --- a/src/scene/dwg_native_constraints.rs +++ b/src/scene/dwg_native_constraints.rs @@ -2812,7 +2812,7 @@ impl Scene { self.parametric_constraints.clear(); // Dynamic dimensions read from the file get their screen size on the // first tick after the view is known. - self.dynamic_dimension_band = 0.0; + self.dynamic_dimension_camera_gen = None; let owners: Vec<_> = self .document .block_records diff --git a/src/scene/mod.rs b/src/scene/mod.rs index aae7b130d..d3e6b5c95 100644 --- a/src/scene/mod.rs +++ b/src/scene/mod.rs @@ -2302,9 +2302,8 @@ pub struct Scene { pub dynamic_constraint_display: bool, /// Dynamic dimensions DCHIDE or DYNCONSTRAINTDISPLAY 0 keep off screen. hidden_dynamic_dimensions: HashSet, - /// The zoom band (`quantize_wpp`) the dynamic dimensions were last - /// scaled for; 0 until the first scaling. - dynamic_dimension_band: f32, + /// The camera generation the dynamic dimensions were last scaled for. + dynamic_dimension_camera_gen: Option, /// Session-only visibility overrides for constraint glyphs. hidden_parametric_constraints: HashSet<( parametric_constraints::ParametricScope, @@ -2638,7 +2637,7 @@ impl Scene { constraint_name_format: 2, dynamic_constraint_display: true, hidden_dynamic_dimensions: HashSet::default(), - dynamic_dimension_band: 0.0, + dynamic_dimension_camera_gen: None, hidden_parametric_constraints: HashSet::default(), shown_parametric_constraints: HashSet::default(), named_parameters: named_parameters::ParameterTable::new(), diff --git a/src/scene/parametric_constraints.rs b/src/scene/parametric_constraints.rs index 579eaa90b..6a72eb76b 100644 --- a/src/scene/parametric_constraints.rs +++ b/src/scene/parametric_constraints.rs @@ -367,6 +367,9 @@ pub const DYNAMIC_DIMENSION_GLYPH: &str = "\u{1F512}"; /// The on-screen text height of a dynamic dimension, in pixels. pub const DYNAMIC_DIMENSION_TEXT_PX: f32 = 12.0; +/// The xdata application that marks an annotational constraint dimension. +pub const ANNOTATIONAL_DIMENSION_APP: &str = "OCS_CONSTRAINT_FORM"; + /// The text a dynamic dimension shows: CONSTRAINTNAMEFORMAT 0 = name, /// 1 = value, 2 = name=value. A plain number shows as typed (`d1=100`); an /// expression shows the expression under the reference's `fx:` prefix @@ -1502,6 +1505,13 @@ impl super::Scene { } None => continue, }; + // An annotational dimension shows the value at dimension + // precision, as the reference does. + let source = if self.dimension_is_annotational(*dimension) { + format!("{value:.4}") + } else { + source + }; updates.push(( *dimension, dynamic_dimension_text(&name, &source, value, format), @@ -1592,25 +1602,69 @@ impl super::Scene { ids.len() } - /// True for a dimension that shows a dimensional constraint. + /// True for a dynamic dimension of a dimensional constraint (not an + /// annotational one, which is an ordinary plotted dimension). pub(crate) fn is_dynamic_dimension(&self, handle: Handle) -> bool { self.parametric_constraints .iter() .any(|set| set.dimensions.values().any(|dimension| *dimension == handle)) + && !self.dimension_is_annotational(handle) + } + + /// True when a dimensional constraint's dimension uses the annotational + /// form: drawn with its style, plotted, never rescaled to the screen. + pub(crate) fn dimension_is_annotational(&self, handle: Handle) -> bool { + self.document.get_entity(handle).is_some_and(|entity| { + entity + .common() + .extended_data + .get_record(ANNOTATIONAL_DIMENSION_APP) + .is_some() + }) + } + + /// Marks a constraint dimension as annotational (DCFORM Annotational). + pub(crate) fn mark_dimension_annotational(&mut self, handle: Handle) { + crate::scene::view::dispatch::set_entity_xdata( + &mut self.document, + handle, + ANNOTATIONAL_DIMENSION_APP, + Some(vec![acadrust::xdata::XDataValue::String( + "ANNOTATIONAL".to_string(), + )]), + ); + } + + /// The document as written to a file: a dynamic dimension's screen-size + /// overrides are a display matter and stay out of the file. + pub(crate) fn document_for_save(&self) -> acadrust::CadDocument { + use crate::entities::dim_override as ov; + let mut document = self.document.clone(); + for set in &self.parametric_constraints { + for handle in set.dimensions.values().copied() { + if self.dimension_is_annotational(handle) { + continue; + } + for code in [ov::DIMSCALE, ov::DIMTIH, ov::DIMTOH] { + ov::set(&mut document, handle, code, None); + } + } + } + document } /// Gives every dynamic dimension a DIMSCALE override that keeps its /// text, arrows and offsets at a screen size (the reference draws them - /// at a constant pixel size whatever the zoom). Runs once per zoom band; - /// `force` re-applies after a dimension was created or loaded. + /// at a constant pixel size whatever the zoom). Runs whenever the camera + /// changed; `force` re-applies after a dimension was created or loaded. pub fn refresh_dynamic_dimension_scales(&mut self, force: bool) { - let Some(band) = super::Scene::quantize_wpp(self.world_per_pixel()) else { + let Some(wpp) = self.world_per_pixel() else { return; }; - if !force && band == self.dynamic_dimension_band { + if !force && self.dynamic_dimension_camera_gen == Some(self.camera_generation) { return; } - self.dynamic_dimension_band = band; + self.dynamic_dimension_camera_gen = Some(self.camera_generation); let handles: Vec = self .parametric_constraints .iter() @@ -1622,6 +1676,10 @@ impl super::Scene { else { continue; }; + // An annotational dimension keeps its style's size. + if self.dimension_is_annotational(handle) { + continue; + } let style_name = dimension.base().style_name.clone(); let text_height = self .document @@ -1635,7 +1693,7 @@ impl super::Scene { .map(|style| style.dimtxt) .filter(|height| *height > 1e-9) .unwrap_or(0.18); - let scale = f64::from(band) * f64::from(DYNAMIC_DIMENSION_TEXT_PX) / text_height; + let scale = f64::from(wpp) * f64::from(DYNAMIC_DIMENSION_TEXT_PX) / text_height; use crate::entities::dim_override as ov; let xdata = &dimension.base().common.extended_data; let current = ov::real(xdata, ov::DIMSCALE); @@ -1676,8 +1734,9 @@ impl super::Scene { .iter() .flat_map(|set| { set.dimensions.iter().filter_map(|(id, dimension)| { - (!self.dynamic_constraint_display - || !self.is_parametric_constraint_visible(set.scope, *id)) + (!self.dimension_is_annotational(*dimension) + && (!self.dynamic_constraint_display + || !self.is_parametric_constraint_visible(set.scope, *id))) .then_some(*dimension) }) }) diff --git a/src/scene/parametric_solve.rs b/src/scene/parametric_solve.rs index 3101a2103..0f1f4e671 100644 --- a/src/scene/parametric_solve.rs +++ b/src/scene/parametric_solve.rs @@ -2766,6 +2766,21 @@ fn solve_scope( constraint.refs.get(2).is_some_and(|axis| axis.entity == *handle) }) || equal_followers.iter().any(|follower| follower.entity == *handle) + // A driving dimension between an entity's own ends is its size; + // a retained length would contradict a new value. + || constraints.iter().any(|c| { + c.enabled + && c.driving_param.is_some() + && matches!( + c.kind, + ConstraintKind::Distance + | ConstraintKind::DistanceX + | ConstraintKind::DistanceY + | ConstraintKind::DistanceDirected + ) + && c.refs.len() >= 2 + && c.refs.iter().all(|r| r.entity == *handle && r.marker.is_some()) + }) { continue; }