Merge pull request #1415 from ramox81/codex/aligned-constraint-parity

Aligned dimensional constraint: Point & line, 2Lines, value and property parity

# Conflicts:
#	src/app/command_driver.rs
#	src/app/update/viewport.rs
#	src/entities/dimension.rs
#	src/scene/parametric_constraints.rs
This commit is contained in:
Hakan Seven committed 2026-09-21 22:41:42 +03:00
commit 7490b2bebd
12 files changed
+1292 -167

No files matched your search

+276 -68
View File
@@ -367,41 +367,197 @@ 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 layer the reference keeps dynamic dimensions on; an annotational
/// dimensional constraint sits on an ordinary layer instead.
pub(crate) const DYNAMIC_DIMENSION_LAYER: &str = "*ADSK_CONSTRAINTS";
/// 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
/// (`fx: d2=d1*2`).
pub(crate) fn dynamic_dimension_text(name: &str, source: &str, value: f64, format: u8) -> String {
let source = source.trim();
let literal = source.parse::<f64>().is_ok();
let shown = if literal {
source.to_string()
} else {
measured_expression(value)
/// 1 = value, 2 = name=value, the value with its trailing zeros dropped
/// (`d9=80`, `d1=111.8034`). A parameter defined by a formula shows the
/// formula behind `fx:` (`fx: len=d1*2`); a reference (driven) constraint's
/// text sits in parentheses; an annotational one keeps dimension precision.
pub(crate) fn dynamic_dimension_text(
name: &str,
value: f64,
format: u8,
reference: bool,
expression: Option<&str>,
annotational: bool,
) -> String {
let formula = expression
.map(str::trim)
.filter(|source| !source.is_empty() && source.parse::<f64>().is_err());
let shown = match formula {
Some(source) => source.to_string(),
// An annotational dimension shows the value at dimension precision
// (`d1=100.0000`), as the reference does.
None if annotational => format!("{value:.4}"),
None => {
let text = format!("{value:.4}");
let text = text.trim_end_matches('0').trim_end_matches('.');
if text.is_empty() || text == "-" {
"0".to_string()
} else {
text.to_string()
}
}
};
match format {
let text = match format {
0 => name.to_string(),
1 if literal => shown,
1 => format!("fx: {shown}"),
_ if literal => format!("{name}={shown}"),
_ => format!("fx: {name}={source}"),
1 => shown,
_ => format!("{name}={shown}"),
};
let text = if formula.is_some() {
format!("fx: {text}")
} else {
text
};
if reference {
format!("({text})")
} else {
text
}
}
/// The expression a measured value seeds a parameter with (`100`, `111.8034`).
/// The expression a measured value seeds a parameter with: twelve
/// significant digits with the trailing zeros dropped (`100`,
/// `111.803398875`), as the reference stores it.
pub(crate) fn measured_expression(value: f64) -> String {
let text = format!("{value:.4}");
let text = text.trim_end_matches('0').trim_end_matches('.');
if text.is_empty() || text == "-" {
if !value.is_finite() {
return "0".to_string();
}
// Solver noise (24.9999999047) reads as the round value it means.
let snapped = (value * 1.0e4).round() / 1.0e4;
let value = if (value - snapped).abs() < 1.0e-6 {
snapped
} else {
value
};
let magnitude = value.abs();
let integer_digits = if magnitude < 1.0 {
1
} else {
magnitude.log10().floor() as i32 + 1
};
let decimals = (12 - integer_digits).clamp(0, 12) as usize;
let text = format!("{value:.decimals$}");
let text = if text.contains('.') {
text.trim_end_matches('0').trim_end_matches('.')
} else {
text.as_str()
};
if text.is_empty() || text == "-" || text == "-0" {
"0".to_string()
} else {
text.to_string()
}
}
/// Moves a dynamic dimension's extension origins to `first`/`second`,
/// keeping its dimension line where it was; true when anything moved.
fn dynamic_dimension_follow_points(
dimension: &mut acadrust::entities::Dimension,
first: Vector3,
second: Vector3,
) -> bool {
use acadrust::entities::Dimension;
let same = |a: Vector3, b: Vector3| (a - b).length_squared() < 1.0e-16;
let to_dvec = |p: Vector3| glam::DVec3::new(p.x, p.y, p.z);
let (current_first, current_second, definition, axis) = match dimension {
Dimension::Aligned(d) => (d.first_point, d.second_point, d.definition_point, None),
Dimension::Linear(d) => (
d.first_point,
d.second_point,
d.definition_point,
Some(glam::DVec3::new(d.rotation.cos(), d.rotation.sin(), 0.0)),
),
_ => return false,
};
if same(current_first, first) && same(current_second, second) {
return false;
}
let text = dimension.base().user_text.clone();
let rebuilt = match axis {
None => crate::modules::annotate::aligned_dim::aligned_dimension_entity(
to_dvec(first),
to_dvec(second),
to_dvec(definition),
text,
),
Some(axis) => crate::modules::annotate::linear_dim::linear_dimension_entity(
to_dvec(first),
to_dvec(second),
to_dvec(definition),
axis,
text,
),
};
let acadrust::EntityType::Dimension(mut rebuilt) = rebuilt else {
return false;
};
// Everything but the geometry stays: identity, layer, color, style, xdata.
let base = dimension.base();
let target = rebuilt.base_mut();
target.common = base.common.clone();
target.style_name = base.style_name.clone();
target.text_rotation = base.text_rotation;
target.attachment_point = base.attachment_point;
target.line_spacing_style = base.line_spacing_style;
target.line_spacing_factor = base.line_spacing_factor;
*dimension = rebuilt;
true
}
/// What stays put when a dimensional constraint's value changes: its first
/// point, and — when the distance runs perpendicular to a line that owns
/// that point (2Lines, line-first Point & line) — the whole line, so the
/// other object moves, as in the reference.
pub(crate) fn dimensional_anchor_refs(
document: &acadrust::CadDocument,
refs: &[ParametricRef],
) -> Vec<ParametricRef> {
let Some(&first) = refs.first() else {
return Vec::new();
};
let mut anchors = vec![first];
if let Some(&line) = refs.get(2).filter(|line| line.entity == first.entity) {
let ends = match line.segment_index() {
Some(index) => {
let index = index as i32;
let end = document
.get_entity(line.entity)
.and_then(|entity| resolve_point(entity, index + 1))
.map_or(0, |_| index + 1);
[
ParametricRef::point(line.entity, index),
ParametricRef::point(line.entity, end),
]
}
None => [
ParametricRef::point(line.entity, 0),
ParametricRef::point(line.entity, 1),
],
};
anchors.extend(ends.into_iter().filter(|end| *end != first));
}
anchors
}
/// The constraint a dynamic dimension shows, with the table its parameter
/// lives in.
pub(crate) fn dynamic_dimension_constraint(
sets: &[ParametricConstraintSet],
handle: Handle,
) -> Option<(&ParametricConstraintSet, &ParametricConstraint)> {
sets.iter().find_map(|set| {
let id = set
.dimensions
.iter()
.find_map(|(id, dimension)| (*dimension == handle).then_some(*id))?;
Some((set, set.get(id)?))
})
}
/// Grabbed points are exact kernel inputs; the solver anchors the remaining
/// endpoint coordinates according to the line's directional constraints.
pub(crate) fn grip_solve_anchor_refs(
@@ -1477,12 +1633,16 @@ impl super::Scene {
/// Rewrites every dynamic dimension's text from its constraint's
/// parameter name and current value, in the CONSTRAINTNAMEFORMAT
/// reading `constraint_name_format` selects.
/// reading `constraint_name_format` selects, and moves its extension
/// origins to where the solve left the constraint points.
pub(crate) fn refresh_dynamic_dimension_texts(&mut self) {
let format = self.constraint_name_format;
let mut updates: Vec<(Handle, String)> = Vec::new();
let mut updates: Vec<(Handle, String, Option<(Vector3, Vector3)>)> = Vec::new();
// A reference (driven) constraint's parameter follows the geometry.
let mut followed: Vec<(String, f64)> = Vec::new();
for set in &self.parametric_constraints {
let table = if set.local_parameters.is_empty() {
let model_table = set.local_parameters.is_empty();
let table = if model_table {
&self.named_parameters
} else {
&set.local_parameters
@@ -1491,47 +1651,94 @@ impl super::Scene {
let Some(constraint) = set.get(*id) else {
continue;
};
let (name, source, value) = match &constraint.driving_param {
Some(DrivingValue::Named(name)) => (
name.clone(),
table
.get(name)
.map(|parameter| parameter.source.clone())
.unwrap_or_default(),
table.resolve(name).unwrap_or(f64::NAN),
),
Some(DrivingValue::Literal(value)) => {
(String::new(), measured_expression(*value), *value)
let world = |reference: &ParametricRef| {
let entity = self.document.get_entity(reference.entity)?;
resolve_point(entity, reference.marker?)
};
let points = match constraint.refs.as_slice() {
[first, second, ..] => world(first).zip(world(second)),
_ => None,
};
let reference = !constraint.enabled;
let measured = points.map(|(first, second)| {
let delta = second - first;
let axis = match self.document.get_entity(*dimension) {
Some(acadrust::EntityType::Dimension(
acadrust::entities::Dimension::Linear(linear),
)) => Some((linear.rotation.cos(), linear.rotation.sin())),
_ => None,
};
match (constraint.kind, axis) {
(ConstraintKind::DistanceX, _) => delta.x.abs(),
(ConstraintKind::DistanceY, _) => delta.y.abs(),
(ConstraintKind::DistanceDirected, Some((ax, ay))) => {
(delta.x * ax + delta.y * ay).abs()
}
_ => delta.length(),
}
});
let (name, value, source) = match &constraint.driving_param {
Some(DrivingValue::Named(name)) => {
let value = match (reference, measured) {
(true, Some(measured)) => {
if model_table {
followed.push((name.clone(), measured));
}
measured
}
_ => table.resolve(name).unwrap_or(f64::NAN),
};
let source = (!reference)
.then(|| table.get(name).map(|parameter| parameter.source.clone()))
.flatten();
(name.clone(), value, source)
}
Some(DrivingValue::Literal(value)) => (String::new(), *value, None),
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
};
let annotational = self.dimension_is_annotational(*dimension);
updates.push((
*dimension,
dynamic_dimension_text(&name, &source, value, format),
dynamic_dimension_text(
&name,
value,
format,
reference,
source.as_deref(),
annotational,
),
points,
));
}
}
for (handle, text) in updates {
for (name, measured) in followed {
let source = measured_expression(measured);
if self.named_parameters.get(&name).map(|p| p.source.as_str()) != Some(source.as_str()) {
let _ = self.named_parameters.set(&name, &source);
}
}
for (handle, text, points) in updates {
let Some(acadrust::EntityType::Dimension(mut dimension)) =
self.document.get_entity(handle).cloned()
else {
continue;
};
if dimension.base().user_text.as_deref() == Some(text.as_str()) {
continue;
let mut changed = false;
if let Some((first, second)) = points {
if dynamic_dimension_follow_points(&mut dimension, first, second) {
changed = true;
}
}
if dimension.base().user_text.as_deref() != Some(text.as_str()) {
crate::entities::dimension::set_dimension_text_override(
dimension.base_mut(),
Some(text),
);
changed = true;
}
if changed {
self.update_entity(acadrust::EntityType::Dimension(dimension));
}
crate::entities::dimension::set_dimension_text_override(
dimension.base_mut(),
Some(text),
);
self.update_entity(acadrust::EntityType::Dimension(dimension));
}
}
@@ -1602,6 +1809,19 @@ impl super::Scene {
ids.len()
}
/// Makes sure the reference's dynamic dimension layer exists: hidden
/// from the layer lists (the `*` prefix) and never plotted.
pub(crate) fn ensure_dynamic_dimension_layer(&mut self) {
if self.document.layers.contains(DYNAMIC_DIMENSION_LAYER) {
return;
}
let mut layer = acadrust::tables::Layer::new(DYNAMIC_DIMENSION_LAYER);
layer.color = acadrust::types::Color::from_index(7);
layer.is_plottable = false;
layer.handle = self.document.allocate_handle();
let _ = self.document.layers.add(layer);
}
/// 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 {
@@ -1612,29 +1832,17 @@ impl super::Scene {
}
/// True when a dimensional constraint's dimension uses the annotational
/// form: drawn with its style, plotted, never rescaled to the screen.
/// form: on an ordinary layer instead of the reference's constraints
/// layer, 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
!entity
.common()
.extended_data
.get_record(ANNOTATIONAL_DIMENSION_APP)
.is_some()
.layer
.eq_ignore_ascii_case(DYNAMIC_DIMENSION_LAYER)
})
}
/// 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 {