Bring the Equal constraint to reference parity

Equal was applied through a generic gather-then-apply flow and, with the
default size-retaining solve mode, never changed anything: the solver
held both sizes and the relation could not be met. Now:

- GCEQUAL joins ECONSTRAINT and GEOMCONSTRAINT Equal; both objects are
  picked inside the command (`Select first object or [Multiple]:`,
  `Select second object:`; Multiple gathers `Select objects to make equal
  to the first:`), a selection made beforehand is not used, a miss says
  `No object found.` and re-asks, an unsupported object or the same object
  twice is reported and re-asked, a repeat is refused.
- The follower is resized in place before the relation is added: a line or
  straight polyline segment keeps its start and direction and its end
  moves to the first object's length; a circle or arc keeps its center and
  takes the radius.
- During edits the side that is not being edited follows the same rule:
  its size is not retained, its start (or center) and other vertices are
  held and its direction kept, so only its length or radius changes; a
  chain of Equal relations follows along.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
ramox81andClaude Fable 5.1 committed 2026-09-18 22:56:31 +03:00
1 parent 1f0b888833
commit 8520ee45e8
10 files changed
+598 -5

No files matched your search

+120
View File
@@ -3265,6 +3265,126 @@ impl OpenCADStudio {
self.commit_undo_delta(i, pd);
}
}
CmdResult::AddEqualConstraint {
first,
others,
label,
} => {
use crate::modules::parametric::EqualConstraintCommand;
use crate::scene::parametric_constraints::{
equal_size_follower, ConstraintKind, ParametricRef,
};
let scope = self.tabs[i].current_parametric_scope();
let mut followers: Vec<ParametricRef> = Vec::new();
for other in others {
// A Multiple set arrives as whole objects.
let resolved = if other.marker.is_none() {
self.tabs[i]
.scene
.document
.get_entity(other.entity)
.and_then(|entity| {
EqualConstraintCommand::whole_reference(entity, other.entity)
})
} else {
Some(other)
};
let Some(other) = resolved.filter(|other| *other != first) else {
self.command_line
.push_error(EqualConstraintCommand::INVALID_OBJECT);
continue;
};
let refs = [first, other];
if self
.tabs[i]
.scene
.validate_parametric_constraint(ConstraintKind::Equal, &refs, None)
.is_err()
|| equal_size_follower(&self.tabs[i].scene.document, first, other)
.is_none()
{
self.command_line
.push_error(EqualConstraintCommand::INVALID_OBJECT);
continue;
}
let exists = self.tabs[i]
.scene
.parametric_constraint_set(scope)
.is_some_and(|set| {
set.constraints.iter().any(|existing| {
existing.enabled
&& existing.kind == ConstraintKind::Equal
&& (existing.refs == refs || existing.refs == [other, first])
})
});
if exists {
self.command_line
.push_error("The constraint already exists on the selected objects.");
continue;
}
if !followers.contains(&other) {
followers.push(other);
}
}
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
if followers.is_empty() {
return Task::none();
}
let constraints_before = self.tabs[i]
.scene
.parametric_constraint_set(scope)
.cloned()
.unwrap_or_else(|| {
crate::scene::parametric_constraints::ParametricConstraintSet::new(scope)
});
let mut touched = vec![first.entity];
for follower in &followers {
if !touched.contains(&follower.entity) {
touched.push(follower.entity);
}
}
let pending = self.begin_undo(i, label, touched.len(), true);
self.tabs[i]
.scene
.record_undo_parametric_constraints_before(scope, constraints_before);
// The reference resizes the follower in place — its start (a
// circle its center) and direction stay, only its length or
// radius takes the first object's — so do that first and let
// the relation then hold what already fits.
for follower in &followers {
if let Some(resized) =
equal_size_follower(&self.tabs[i].scene.document, first, *follower)
{
self.tabs[i].scene.update_entity(resized);
}
let id = self.tabs[i]
.scene
.parametric_constraint_set_mut(scope)
.add(ConstraintKind::Equal, vec![first, *follower], None);
self.tabs[i].scene.note_parametric_constraint_applied(
scope,
id,
self.constraint_bar_display,
);
}
let changes = touched
.into_iter()
.map(|handle| (handle, crate::scene::ChangeKind::Modified))
.collect::<Vec<_>>();
self.tabs[i].scene.bump_entities_with_parametric_policy(
&changes,
&[],
self.constraint_solve_mode,
);
self.tabs[i].dirty = true;
self.command_line.push_output("Equal constraint applied.");
self.refresh_properties();
if let Some(pd) = pending {
self.commit_undo_delta(i, pd);
}
}
CmdResult::AddFixedConstraint(pick) => {
use crate::modules::parametric::FixConstraintCommand;
use crate::scene::parametric_constraints::{
+12 -4
View File
@@ -1569,8 +1569,17 @@ impl OpenCADStudio {
}
}
"PCONSTRAINT" | "ECONSTRAINT" | "LCONSTRAINT"
| "NRCONSTRAINT" => {
"ECONSTRAINT" | "GCEQUAL" => {
use crate::modules::parametric::EqualConstraintCommand;
// Both objects are picked inside the command, as in the
// reference; a selection made beforehand is not used.
self.tabs[i].scene.deselect_all();
let command = EqualConstraintCommand::new();
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
}
"PCONSTRAINT" | "LCONSTRAINT" | "NRCONSTRAINT" => {
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() {
use crate::modules::draw::select::SelectObjectsCommand;
@@ -1587,8 +1596,7 @@ impl OpenCADStudio {
let (kind, label) = match cmd {
"PCONSTRAINT" => (ConstraintKind::Parallel, "Parallel constraint"),
"LCONSTRAINT" => (ConstraintKind::Colinear, "Colinear constraint"),
"NRCONSTRAINT" => (ConstraintKind::Normal, "Normal constraint"),
_ => (ConstraintKind::Equal, "Equal constraint"),
_ => (ConstraintKind::Normal, "Normal constraint"),
};
return Some(self.apply_cmd_result(CmdResult::AddParametricConstraint {
kind,
+1
View File
@@ -248,6 +248,7 @@ fn command_category(name: &str) -> &'static str {
"GCHORIZONTAL",
"VCONSTRAINT",
"ECONSTRAINT",
"GCEQUAL",
"TCONSTRAINT",
"GCCONCENTRIC",
"NRCONSTRAINT",
+9
View File
@@ -1592,6 +1592,14 @@ pub enum CmdResult {
direction: acadrust::types::Vector3,
label: &'static str,
},
/// Adds an Equal relation from `first` to each of `others` (the second
/// object, or a Multiple set). The host resizes every follower to the
/// first object's length or radius before the relation holds it there.
AddEqualConstraint {
first: crate::scene::parametric_constraints::ParametricRef,
others: Vec<crate::scene::parametric_constraints::ParametricRef>,
label: &'static str,
},
/// Adds a point or object symmetry relation around a picked line. The
/// first reference and axis remain fixed during initial placement.
AddSymmetricConstraint {
@@ -2894,6 +2902,7 @@ mod constraint_registry_tests {
"QCONSTRAINT",
"GCPERPENDICULAR",
"ECONSTRAINT",
"GCEQUAL",
"TCONSTRAINT",
"GCCONCENTRIC",
"NRCONSTRAINT",
+286
View File
@@ -0,0 +1,286 @@
use acadrust::{EntityType, Handle};
use glam::DVec3;
use crate::command::{CadCommand, CmdOption, CmdResult};
use crate::scene::parametric_constraints::ParametricRef;
use super::HorizontalConstraintCommand;
#[derive(Clone, Copy)]
enum Step {
/// `Select first object or [Multiple]:`, or `Select first object:`
/// once Multiple was chosen.
First { multiple: bool },
/// `Select second object:` — the one that takes the first's size.
Second(ParametricRef),
/// `Select objects to make equal to the first:` — a selection set,
/// applied on Enter.
Others(ParametricRef),
}
/// Interactive front end for the Equal geometric constraint: the first
/// object sets the size, the second (or, with Multiple, every object of a
/// set) takes its length or radius. Picks are made inside the command; a
/// selection made before it starts is not used.
pub struct EqualConstraintCommand {
step: Step,
picked_entity: Option<EntityType>,
others: Vec<Handle>,
}
impl EqualConstraintCommand {
pub const NO_OBJECT: &'static str = "No object found.";
pub const INVALID_OBJECT: &'static str =
"Invalid selection for Equal. Select a line, polyline segment, circle or arc.";
pub const SAME_OBJECT: &'static str =
"The object or point is already selected. Select a different object or constraint point.";
pub fn new() -> Self {
Self {
step: Step::First { multiple: false },
picked_entity: None,
others: Vec::new(),
}
}
/// The whole line, circle or arc, or the picked straight polyline
/// segment.
pub fn picked_reference(
entity: &EntityType,
handle: Handle,
point: DVec3,
) -> Option<ParametricRef> {
match entity {
EntityType::Line(_) | EntityType::Circle(_) | EntityType::Arc(_) => {
Some(ParametricRef::whole(handle))
}
EntityType::LwPolyline(_) | EntityType::Polyline2D(_) => {
let (source, _, _) =
crate::scene::centerline::picked_source(entity, handle, point)?;
let index = usize::try_from(source.segment_index).ok()?;
HorizontalConstraintCommand::segment_is_straight(entity, index)
.then_some(ParametricRef::segment(handle, index))
}
_ => None,
}
}
/// An object of a Multiple set: a whole line, circle or arc, a
/// one-segment polyline as its segment.
pub fn whole_reference(entity: &EntityType, handle: Handle) -> Option<ParametricRef> {
match entity {
EntityType::Line(_) | EntityType::Circle(_) | EntityType::Arc(_) => {
Some(ParametricRef::whole(handle))
}
EntityType::LwPolyline(polyline) => {
let count = if polyline.is_closed {
polyline.vertices.len()
} else {
polyline.vertices.len().saturating_sub(1)
};
(count == 1 && HorizontalConstraintCommand::segment_is_straight(entity, 0))
.then_some(ParametricRef::segment(handle, 0))
}
EntityType::Polyline2D(polyline) => {
let count = if polyline.is_closed() {
polyline.vertices.len()
} else {
polyline.vertices.len().saturating_sub(1)
};
(count == 1 && HorizontalConstraintCommand::segment_is_straight(entity, 0))
.then_some(ParametricRef::segment(handle, 0))
}
_ => None,
}
}
fn report(message: &str) -> CmdResult {
CmdResult::ReportError(message.to_string())
}
fn finish(first: ParametricRef, others: Vec<ParametricRef>) -> CmdResult {
CmdResult::AddEqualConstraint {
first,
others,
label: "Equal constraint",
}
}
}
impl CadCommand for EqualConstraintCommand {
fn name(&self) -> &'static str {
"GCEQUAL"
}
fn prompt(&self) -> String {
match self.step {
Step::First { multiple: false } => {
"GCEQUAL Select first object or [Multiple]:".to_string()
}
Step::First { multiple: true } => "GCEQUAL Select first object:".to_string(),
Step::Second(_) => "GCEQUAL Select second object:".to_string(),
Step::Others(_) if self.others.is_empty() => {
"GCEQUAL Select objects to make equal to the first:".to_string()
}
Step::Others(_) => format!(
"GCEQUAL Select objects to make equal to the first ({} selected, Enter to apply):",
self.others.len()
),
}
}
fn options(&self) -> Vec<CmdOption> {
matches!(self.step, Step::First { multiple: false })
.then(|| vec![CmdOption::new("Multiple", "M")])
.unwrap_or_default()
}
fn wants_text_input(&self) -> bool {
true
}
fn point_step_accepts_keywords(&self) -> bool {
matches!(self.step, Step::First { multiple: false })
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let keyword = text.trim().trim_start_matches('_').to_ascii_uppercase();
if matches!(self.step, Step::First { multiple: false })
&& matches!(keyword.as_str(), "M" | "MULTIPLE")
{
self.step = Step::First { multiple: true };
return Some(CmdResult::NeedPoint);
}
None
}
fn needs_entity_pick(&self) -> bool {
!matches!(self.step, Step::Others(_))
}
fn entity_pick_accepts_points(&self) -> bool {
true
}
fn entity_pick_highlights_hover(&self) -> bool {
true
}
fn inject_before_entity_pick(&self) -> bool {
true
}
fn inject_picked_entity(&mut self, entity: EntityType) {
self.picked_entity = Some(entity);
}
fn is_selection_gathering(&self) -> bool {
matches!(self.step, Step::Others(_))
}
fn on_selection_complete(&mut self, handles: Vec<Handle>) -> CmdResult {
if let Step::Others(first) = self.step {
// The first object sets the size; it cannot also follow itself.
self.others = handles
.into_iter()
.filter(|handle| *handle != first.entity)
.collect();
}
CmdResult::NeedPoint
}
fn on_entity_pick(&mut self, handle: Handle, point: DVec3) -> CmdResult {
if handle.is_null() {
return Self::report(Self::NO_OBJECT);
}
let Some(entity) = self.picked_entity.take() else {
return CmdResult::NeedPoint;
};
let Some(reference) = Self::picked_reference(&entity, handle, point) else {
return Self::report(Self::INVALID_OBJECT);
};
match self.step {
Step::First { multiple: false } => {
self.step = Step::Second(reference);
CmdResult::NeedPoint
}
Step::First { multiple: true } => {
self.step = Step::Others(reference);
CmdResult::NeedPoint
}
Step::Second(first) => {
if first == reference {
return Self::report(Self::SAME_OBJECT);
}
Self::finish(first, vec![reference])
}
Step::Others(_) => CmdResult::NeedPoint,
}
}
// An empty-space click while an object is asked for.
fn on_point(&mut self, _point: DVec3) -> CmdResult {
Self::report(Self::NO_OBJECT)
}
fn on_enter(&mut self) -> CmdResult {
match self.step {
Step::Others(first) if !self.others.is_empty() => Self::finish(
first,
self.others.iter().map(|handle| ParametricRef::whole(*handle)).collect(),
),
_ => CmdResult::Cancel,
}
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}
inventory::submit!(crate::command::CommandRegistration {
names: &["ECONSTRAINT", "GCEQUAL"]
});
#[cfg(test)]
mod tests {
use super::*;
use acadrust::entities::Line;
use acadrust::types::Vector3;
fn line() -> EntityType {
EntityType::Line(Line::from_points(Vector3::ZERO, Vector3::new(10.0, 0.0, 0.0)))
}
#[test]
fn two_picks_make_the_second_follow_the_first() {
let mut command = EqualConstraintCommand::new();
command.inject_picked_entity(line());
assert!(matches!(
command.on_entity_pick(Handle::new(7), DVec3::ZERO),
CmdResult::NeedPoint
));
command.inject_picked_entity(line());
let CmdResult::AddEqualConstraint { first, others, .. } =
command.on_entity_pick(Handle::new(8), DVec3::ZERO)
else {
panic!("the second pick must create the constraint");
};
assert_eq!(first, ParametricRef::whole(Handle::new(7)));
assert_eq!(others, vec![ParametricRef::whole(Handle::new(8))]);
}
#[test]
fn multiple_applies_the_gathered_set_on_enter() {
let mut command = EqualConstraintCommand::new();
assert!(matches!(command.on_text_input("M"), Some(CmdResult::NeedPoint)));
command.inject_picked_entity(line());
command.on_entity_pick(Handle::new(7), DVec3::ZERO);
assert!(command.is_selection_gathering());
command.on_selection_complete(vec![Handle::new(7), Handle::new(8), Handle::new(9)]);
let CmdResult::AddEqualConstraint { others, .. } = command.on_enter() else {
panic!("Enter must apply the set");
};
assert_eq!(others.len(), 2);
}
}
+1 -1
View File
@@ -98,7 +98,7 @@ impl HorizontalConstraintCommand {
CmdResult::ReportError("No valid constraint point found.".to_string())
}
fn segment_is_straight(entity: &EntityType, index: usize) -> bool {
pub(crate) fn segment_is_straight(entity: &EntityType, index: usize) -> bool {
match entity {
EntityType::LwPolyline(polyline) => polyline
.vertices
+3
View File
@@ -6,6 +6,8 @@ mod coincident;
mod concentric;
mod constraint_bar;
mod equal_distance;
#[path = "equal.rs"]
mod equal_command;
#[path = "fixed.rs"]
mod fixed_command;
mod geom_constraint;
@@ -24,6 +26,7 @@ mod value;
pub use coincident::{coincident_tool, CoincidentConstraintCommand};
pub use concentric::ConcentricConstraintCommand;
pub use constraint_bar::ConstraintBarOptionCommand;
pub use equal_command::EqualConstraintCommand;
pub use equal_distance::{equal_distance_tool, EqualDistanceConstraintCommand};
pub use fixed_command::FixConstraintCommand;
pub use geom_constraint::GeomConstraintCommand;
+1
View File
@@ -166,6 +166,7 @@ inventory::submit!(crate::command::CommandRegistration {
"QCONSTRAINT",
"GCPERPENDICULAR",
"ECONSTRAINT",
"GCEQUAL",
"TCONSTRAINT",
"GCCONCENTRIC",
"NRCONSTRAINT",
+83
View File
@@ -265,6 +265,89 @@ pub(crate) fn set_polyline_vertex(
}
}
/// The size an Equal relation copies.
#[derive(Clone, Copy)]
pub(crate) enum EqualSize {
/// A line's or a straight polyline segment's length.
Length(f64),
/// A circle's or an arc's radius.
Radius(f64),
}
pub(crate) fn equal_size(
document: &acadrust::CadDocument,
reference: ParametricRef,
) -> Option<EqualSize> {
let entity = document.get_entity(reference.entity)?;
match entity {
acadrust::EntityType::Circle(circle) if reference.marker.is_none() => {
Some(EqualSize::Radius(circle.radius))
}
acadrust::EntityType::Arc(arc) if reference.marker.is_none() => {
Some(EqualSize::Radius(arc.radius))
}
acadrust::EntityType::Line(_)
| acadrust::EntityType::LwPolyline(_)
| acadrust::EntityType::Polyline2D(_) => {
let index = reference.segment_index().map_or(0, |index| index as i32);
let start = resolve_point(entity, index)?;
let end = resolve_point(entity, index + 1)?;
let length = (end - start).length();
(length > 1.0e-12).then_some(EqualSize::Length(length))
}
_ => None,
}
}
/// `follower` resized to `first`'s size the way the reference does it: a
/// line or segment keeps its start and direction and only its end moves,
/// a circle or arc keeps its center and takes the radius. `None` when the
/// two do not share a size kind.
pub(crate) fn equal_size_follower(
document: &acadrust::CadDocument,
first: ParametricRef,
follower: ParametricRef,
) -> Option<acadrust::EntityType> {
let size = equal_size(document, first)?;
let original = document.get_entity(follower.entity)?;
let mut entity = original.clone();
match size {
EqualSize::Radius(radius) if follower.marker.is_none() => match &mut entity {
acadrust::EntityType::Circle(circle) => circle.radius = radius,
acadrust::EntityType::Arc(arc) => arc.radius = radius,
_ => return None,
},
EqualSize::Length(length) => {
let index = follower.segment_index().map_or(0, |index| index as i32);
let start = resolve_point(original, index)?;
let end = resolve_point(original, index + 1)?;
let current = (end - start).length();
if current <= 1.0e-12 {
return None;
}
let scale = length / current;
let x = start.x + (end.x - start.x) * scale;
let y = start.y + (end.y - start.y) * scale;
if matches!(
original,
acadrust::EntityType::LwPolyline(_) | acadrust::EntityType::Polyline2D(_)
) {
if !set_polyline_vertex(&mut entity, index as usize + 1, x, y) {
return None;
}
} else if let (acadrust::EntityType::Line(line), None) = (&mut entity, follower.marker)
{
line.end.x = x;
line.end.y = y;
} else {
return None;
}
}
_ => return None,
}
Some(entity)
}
/// 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(
+82
View File
@@ -2450,6 +2450,87 @@ fn solve_scope(
}
}
}
// Equal: the side that is not being edited follows the other's length
// or radius the way the reference does it — its start (a circle its
// center) and direction stay and only its end moves — so its size is
// not retained below, its other points are held and its direction is
// kept while the edit lasts. A chain of Equal relations follows along.
let edited = |handle: Handle| {
driven_refs.iter().any(|reference| reference.entity == handle)
|| initial_fixed_refs.iter().any(|reference| reference.entity == handle)
};
let mut equal_followers: Vec<ParametricRef> = Vec::new();
let mut moving: Vec<Handle> = cache.keys().copied().filter(|handle| edited(*handle)).collect();
loop {
let before = equal_followers.len();
for constraint in &constraints {
if !constraint.enabled || constraint.kind != ConstraintKind::Equal {
continue;
}
let [a, b] = constraint.refs.as_slice() else { continue };
let follower = match (moving.contains(&a.entity), moving.contains(&b.entity)) {
(true, false) => *b,
(false, true) => *a,
_ => continue,
};
if !equal_followers.contains(&follower) {
equal_followers.push(follower);
moving.push(follower.entity);
}
}
if equal_followers.len() == before {
break;
}
}
for follower in &equal_followers {
let Some(geometry) = resolve_ref(document, &mut sys, &mut cache, *follower) else {
continue;
};
let mut hold = |anchor: ParametricRef| {
if !anchors.contains(&anchor) {
anchors.push(anchor);
}
};
let line = match &geometry {
EntityGeom::Line(line) => Some(*line),
EntityGeom::Polyline { .. } => follower
.segment_index()
.and_then(|index| geometry.line_segment(index)),
_ => None,
};
match &geometry {
EntityGeom::Circle(_) | EntityGeom::Arc(_) => {
hold(ParametricRef::center(follower.entity));
}
EntityGeom::Line(_) => hold(ParametricRef::point(follower.entity, 0)),
EntityGeom::Polyline { points, .. } => {
let moving_vertex = follower
.segment_index()
.map(|index| (index + 1) % points.len().max(1));
for index in (0..points.len()).filter(|index| Some(*index) != moving_vertex) {
hold(ParametricRef::point(follower.entity, index as i32));
}
}
_ => {}
}
if let Some(line) = line {
let (dx, dy) = {
let store = sys.store();
(
store.get(line.p2.x) - store.get(line.p1.x),
store.get(line.p2.y) - store.get(line.p1.y),
)
};
if dx.hypot(dy) > f64::EPSILON {
let datum = GLine {
p1: GPoint::new(sys.add_param(0.0, true), sys.add_param(0.0, true)),
p2: GPoint::new(sys.add_param(dx, true), sys.add_param(dy, true)),
};
let parallel = ParallelConstraint::new(sys.store(), line, datum);
sys.add_constraint(Rc::new(parallel));
}
}
}
if !retain_lengths {
let mut axis_lines: Vec<_> = line_axes.into_iter().filter_map(|(reference, vertical)| {
let geometry = cache.get(&reference.entity)?;
@@ -2583,6 +2664,7 @@ fn solve_scope(
|| symmetric_constraints.iter().any(|constraint| {
constraint.refs.get(2).is_some_and(|axis| axis.entity == *handle)
})
|| equal_followers.iter().any(|follower| follower.entity == *handle)
{
continue;
}