Merge branch 'HakanSeven12:main' into main

This commit is contained in:
dichhead authored and GitHub committed 2026-09-17 17:56:03 +02:00
commit bec382a99b
54 files changed
+20627 -684

No files matched your search

Generated
+2 -2
View File
@@ -921,7 +921,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cadkernel"
version = "0.1.0"
source = "git+https://github.com/HakanSeven12/cadkernel.git?rev=35aa7a5#35aa7a541ab7c020cd23f43978373337523e25df"
source = "git+https://github.com/HakanSeven12/cadkernel.git?rev=d2a288b#d2a288b5f397ad7941719119f216a048d6cdcc6f"
dependencies = [
"acadrust",
"cavalier_contours",
@@ -932,7 +932,7 @@ dependencies = [
[[package]]
name = "cadkernel-constraints"
version = "0.1.0"
source = "git+https://github.com/HakanSeven12/cadkernel.git?rev=35aa7a5#35aa7a541ab7c020cd23f43978373337523e25df"
source = "git+https://github.com/HakanSeven12/cadkernel.git?rev=d2a288b#d2a288b5f397ad7941719119f216a048d6cdcc6f"
dependencies = [
"nalgebra",
]
+2 -2
View File
@@ -34,8 +34,8 @@ clap = { version = "4", features = ["derive", "string"] }
env_logger = "0.11"
log = "0.4"
acadrust = { git = "https://github.com/HakanSeven12/cadcodec.git", rev = "8a28c21", features = ["serde"] }
cadkernel = { git = "https://github.com/HakanSeven12/cadkernel.git", rev = "35aa7a5", features = ["acis", "offset"] }
cadkernel-constraints = { git = "https://github.com/HakanSeven12/cadkernel.git", rev = "35aa7a5" }
cadkernel = { git = "https://github.com/HakanSeven12/cadkernel.git", rev = "d2a288b", features = ["acis", "offset"] }
cadkernel-constraints = { git = "https://github.com/HakanSeven12/cadkernel.git", rev = "d2a288b" }
dwg-thumbnailer = { path = "crates/dwg-thumbnailer" }
flate2 = "1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "bmp", "tiff"] }
+2 -2
View File
@@ -1,4 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="64" height="64">
<line x1="4" y1="17" x2="20" y2="17" stroke="#B4B6B9" stroke-width="2.25" stroke-linecap="round"/>
<line x1="12" y1="4" x2="12" y2="17" stroke="#6DB7ED" stroke-width="2.25" stroke-linecap="round"/>
<line x1="4" y1="18.5" x2="20" y2="18.5" stroke="#B4B6B9" stroke-width="2.25" stroke-linecap="round"/>
<line x1="12" y1="5.5" x2="12" y2="18.5" stroke="#6DB7ED" stroke-width="2.25" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 293 B

After

Width:  |  Height:  |  Size: 301 B

+3 -3
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="64" height="64">
<path d="M3 18C8 18 7 6 13 6c4 0 4 6 8 6" stroke="#B4B6B9" stroke-width="2.1" stroke-linecap="round" fill="none"/>
<path d="M13 6c4 0 4 6 8 6" stroke="#6DB7ED" stroke-width="2.1" stroke-linecap="round" fill="none"/>
<circle cx="13" cy="6" r="1.6" fill="#6DB7ED"/>
<path d="M3 17C7 17 8 12 12 12" stroke="#B4B6B9" stroke-width="2.1" stroke-linecap="round" fill="none"/>
<path d="M12 12C16 12 17 7 21 7" stroke="#6DB7ED" stroke-width="2.1" stroke-linecap="round" fill="none"/>
<circle cx="12" cy="12" r="1.6" fill="#6DB7ED"/>
</svg>

Before

Width:  |  Height:  |  Size: 361 B

After

Width:  |  Height:  |  Size: 357 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

+1 -1
View File
@@ -294,7 +294,7 @@ impl OpenCADStudio {
match req["op"].as_str().unwrap_or("") {
"new" => {
let i = self.active_tab;
self.tabs[i].scene.clear();
self.tabs[i].scene.reset_to_new_drawing();
self.tabs[i].scene.material_base_dir = None;
self.tabs[i].current_path = None;
// The headless session starts on the welcome (Start) tab, which
+395 -1
View File
@@ -3182,9 +3182,24 @@ impl OpenCADStudio {
&refs,
driving_param.as_ref(),
) {
let keep_smooth_selection = kind
== crate::scene::parametric_constraints::ConstraintKind::Smooth
&& self.tabs[i]
.active_cmd
.as_ref()
.is_some_and(|command| command.name() == "GCSMOOTH");
if !keep_smooth_selection {
self.tabs[i].active_cmd = None;
}
self.tabs[i].snap_result = None;
self.command_line.push_error(message);
if keep_smooth_selection {
if let Some(prompt) =
self.tabs[i].active_cmd.as_ref().map(|command| command.prompt())
{
self.command_line.push_info(&prompt);
}
}
return Task::none();
}
let scope = self.tabs[i].current_parametric_scope();
@@ -3229,6 +3244,150 @@ impl OpenCADStudio {
self.commit_undo_delta(i, pd);
}
}
CmdResult::AddHorizontalConstraint {
selection,
direction,
label,
} => {
use crate::command::HorizontalConstraintSelection;
use crate::scene::parametric_constraints::{
nearest_parametric_point, nearest_parametric_point_on_entity, ConstraintKind,
DirectionalAxis, ParametricRef,
};
let scope = self.tabs[i].current_parametric_scope();
let to_world = |point: glam::DVec3| {
acadrust::types::Vector3::new(point.x, point.y, point.z)
};
let (refs, initial_fixed) = match selection {
HorizontalConstraintSelection::Reference(reference) => {
let initial_fixed = match reference.directional_axis() {
Some(DirectionalAxis::EllipseMajor | DirectionalAxis::EllipseMinor) => {
vec![ParametricRef::center(reference.entity)]
}
Some(DirectionalAxis::TextBaseline) => {
vec![ParametricRef::point(reference.entity, 0)]
}
None => Vec::new(),
};
(vec![reference], initial_fixed)
}
HorizontalConstraintSelection::Points(first, second) => {
let resolve = |pick: crate::command::CoincidentPick| {
if let Some(handle) = pick.handle {
nearest_parametric_point_on_entity(
&self.tabs[i].scene.document,
scope,
handle,
to_world(pick.point),
)
} else {
nearest_parametric_point(
&self.tabs[i].scene.document,
scope,
to_world(pick.point),
None,
)
}
};
let (Some(first_ref), Some(second_ref)) =
(resolve(first), resolve(second))
else {
self.command_line.push_error(
"Horizontal: select supported endpoints, centers, midpoints, or vertices.",
);
return Task::none();
};
if first_ref == second_ref {
self.command_line
.push_error("Horizontal: select two different points.");
return Task::none();
}
(vec![first_ref, second_ref], vec![first_ref])
}
};
let axis_length = direction.x.hypot(direction.y);
if axis_length <= 1.0e-12 {
self.command_line
.push_error("Horizontal: the current UCS X axis is not supported.");
return Task::none();
}
let direction = acadrust::types::Vector3::new(
direction.x / axis_length,
direction.y / axis_length,
0.0,
);
if let Err(message) = self.tabs[i].scene.validate_parametric_constraint(
ConstraintKind::Horizontal,
&refs,
None,
) {
self.command_line.push_error(message);
return Task::none();
}
if self
.tabs[i]
.scene
.parametric_constraint_set(scope)
.is_some_and(|set| {
set.contains_axis_constraint(
ConstraintKind::Horizontal,
&refs,
direction,
)
})
{
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
self.command_line
.push_error("Horizontal constraint is already applied.");
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::new();
for reference in &refs {
if !touched.contains(&reference.entity) {
touched.push(reference.entity);
}
}
let pending = self.begin_undo(i, label, touched.len(), true);
self.tabs[i]
.scene
.record_undo_parametric_constraints_before(scope, constraints_before);
let id = self.tabs[i]
.scene
.parametric_constraint_set_mut(scope)
.add_axis_constraint(ConstraintKind::Horizontal, refs, direction);
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,
&initial_fixed,
self.constraint_solve_mode,
);
self.tabs[i].dirty = true;
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
self.command_line
.push_output("Horizontal constraint applied.");
self.refresh_properties();
if let Some(pd) = pending {
self.commit_undo_delta(i, pd);
}
}
CmdResult::AddPerpendicularConstraint {
first,
second,
@@ -3280,7 +3439,7 @@ impl OpenCADStudio {
.into_iter()
.map(|handle| (handle, crate::scene::ChangeKind::Modified))
.collect::<Vec<_>>();
self.tabs[i].scene.bump_entities_with_parametric_policy(
self.tabs[i].scene.bump_entities_with_initial_parametric_policy(
&changes,
&[first_fixed, second_start],
true,
@@ -3357,6 +3516,88 @@ impl OpenCADStudio {
self.commit_undo_delta(i, pd);
}
}
CmdResult::AddConcentricConstraint {
first,
second,
label,
} => {
use crate::scene::parametric_constraints::ConstraintKind;
let refs = vec![first, second];
if let Err(message) = self.tabs[i].scene.validate_parametric_constraint(
ConstraintKind::Concentric,
&refs,
None,
) {
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
self.command_line.push_error(message);
return Task::none();
}
let scope = self.tabs[i].current_parametric_scope();
let duplicate = self.tabs[i]
.scene
.parametric_constraint_set(scope)
.is_some_and(|set| {
set.constraints.iter().any(|constraint| {
constraint.enabled
&& constraint.kind == ConstraintKind::Concentric
&& matches!(constraint.refs.as_slice(), [a, b]
if (*a == first && *b == second)
|| (*a == second && *b == first))
})
});
if duplicate {
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
self.command_line
.push_output("The Concentric constraint already exists.");
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 touched = if first.entity == second.entity {
vec![first.entity]
} else {
vec![first.entity, second.entity]
};
let pending = self.begin_undo(i, label, touched.len(), true);
self.tabs[i]
.scene
.record_undo_parametric_constraints_before(scope, constraints_before);
let id = self.tabs[i].scene.parametric_constraint_set_mut(scope).add(
ConstraintKind::Concentric,
refs,
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_initial_parametric_policy(
&changes,
&[first],
true,
);
self.tabs[i].dirty = true;
self.tabs[i].active_cmd = None;
self.tabs[i].snap_result = None;
self.command_line.push_output("Constraint applied.");
self.refresh_properties();
if let Some(pd) = pending {
self.commit_undo_delta(i, pd);
}
}
CmdResult::AddCoincidentConstraint {
first,
second,
@@ -8450,6 +8691,159 @@ mod parametric_constraint_undo_tests {
);
}
#[test]
fn perpendicular_initial_solve_rotates_parallel_second_line_in_kernel() {
let mut app = OpenCADStudio::new_for_test();
let _ = app.automation_op(r#"{"op":"new"}"#);
let first = add_line(&mut app, 0.0, 0.0, 10.0, 0.0);
let second = add_line(&mut app, 20.0, 0.0, 30.0, 0.0);
let _ = app.apply_cmd_result(CmdResult::AddPerpendicularConstraint {
first: ParametricRef::whole(first),
second: ParametricRef::whole(second),
first_fixed: ParametricRef::whole(first),
second_start: ParametricRef::point(second, 0),
label: "Perpendicular constraint",
});
let line = |handle| match app.tabs[app.active_tab].scene.document.get_entity(handle) {
Some(acadrust::EntityType::Line(line)) => line.clone(),
other => panic!("expected a Line, got {other:?}"),
};
let fixed = line(first);
let moving = line(second);
assert_eq!(fixed.start, acadrust::types::Vector3::new(0.0, 0.0, 0.0));
assert_eq!(fixed.end, acadrust::types::Vector3::new(10.0, 0.0, 0.0));
assert!((moving.start - acadrust::types::Vector3::new(20.0, 0.0, 0.0)).length() < 1.0e-9);
assert!((moving.length() - 10.0).abs() < 1.0e-7);
assert!(
(fixed.end - fixed.start)
.dot(&(moving.end - moving.start))
.abs()
< 1.0e-7,
"fixed={fixed:?}, moving={moving:?}"
);
}
#[test]
fn horizontal_initial_solve_uses_the_captured_axis_in_kernel() {
let mut app = OpenCADStudio::new_for_test();
let _ = app.automation_op(r#"{"op":"new"}"#);
let handle = add_line(&mut app, 0.0, 0.0, 5.0, 2.0);
let (original_start, original_end, original_length) = match app.tabs[app.active_tab]
.scene
.document
.get_entity(handle)
{
Some(acadrust::EntityType::Line(line)) => (line.start, line.end, line.length()),
other => panic!("expected a Line, got {other:?}"),
};
let direction = acadrust::types::Vector3::new(3.0, 4.0, 0.0).normalize();
let _ = app.apply_cmd_result(CmdResult::AddHorizontalConstraint {
selection: crate::command::HorizontalConstraintSelection::Reference(
ParametricRef::whole(handle),
),
direction,
label: "Horizontal constraint",
});
let line = match app.tabs[app.active_tab].scene.document.get_entity(handle) {
Some(acadrust::EntityType::Line(line)) => line,
other => panic!("expected a Line, got {other:?}"),
};
let solved = (line.end - line.start).normalize();
assert!(solved.cross(&direction).length() < 1.0e-7);
assert!((line.length() - original_length).abs() < 1.0e-7);
let constraint = &app.tabs[app.active_tab]
.scene
.parametric_constraint_set(ParametricScope::ModelSpace)
.unwrap()
.constraints[0];
assert_eq!(constraint.axis_direction, Some(direction));
app.undo_steps(1);
let line = match app.tabs[app.active_tab].scene.document.get_entity(handle) {
Some(acadrust::EntityType::Line(line)) => line,
other => panic!("expected a Line after undo, got {other:?}"),
};
assert_eq!((line.start, line.end), (original_start, original_end));
assert_eq!(
app.tabs[app.active_tab]
.scene
.parametric_constraint_set(ParametricScope::ModelSpace)
.map(|set| set.constraints.len())
.unwrap_or(0),
0
);
app.redo_steps(1);
let line = match app.tabs[app.active_tab].scene.document.get_entity(handle) {
Some(acadrust::EntityType::Line(line)) => line,
other => panic!("expected a Line after redo, got {other:?}"),
};
assert!((line.end - line.start).normalize().cross(&direction).length() < 1.0e-7);
}
#[test]
fn horizontal_two_point_solve_keeps_the_first_point_fixed() {
let mut app = OpenCADStudio::new_for_test();
let _ = app.automation_op(r#"{"op":"new"}"#);
let first = add_line(&mut app, 0.0, 0.0, 0.0, 5.0);
let second = add_line(&mut app, 8.0, 3.0, 8.0, 7.0);
let pick = |handle, point| crate::command::CoincidentPick {
handle: Some(handle),
point,
whole_curve: false,
};
let _ = app.apply_cmd_result(CmdResult::AddHorizontalConstraint {
selection: crate::command::HorizontalConstraintSelection::Points(
pick(first, glam::DVec3::ZERO),
pick(second, glam::DVec3::new(8.0, 3.0, 0.0)),
),
direction: acadrust::types::Vector3::UNIT_X,
label: "Horizontal constraint",
});
let line = |handle| match app.tabs[app.active_tab].scene.document.get_entity(handle) {
Some(acadrust::EntityType::Line(line)) => line,
other => panic!("expected a Line, got {other:?}"),
};
assert_eq!(line(first).start, acadrust::types::Vector3::ZERO);
assert!(line(second).start.y.abs() < 1.0e-8);
}
#[test]
fn horizontal_minor_axis_rotates_an_ellipse_around_its_center() {
let mut app = OpenCADStudio::new_for_test();
let _ = app.automation_op(r#"{"op":"new"}"#);
let mut ellipse = acadrust::entities::Ellipse::default();
ellipse.center = acadrust::types::Vector3::new(3.0, 7.0, 0.0);
ellipse.major_axis = acadrust::types::Vector3::new(3.0, 4.0, 0.0);
ellipse.minor_axis_ratio = 0.4;
let handle = app.tabs[app.active_tab]
.scene
.add_entity(acadrust::EntityType::Ellipse(ellipse));
let _ = app.apply_cmd_result(CmdResult::AddHorizontalConstraint {
selection: crate::command::HorizontalConstraintSelection::Reference(
ParametricRef::ellipse_minor_axis(handle),
),
direction: acadrust::types::Vector3::UNIT_X,
label: "Horizontal constraint",
});
let ellipse = match app.tabs[app.active_tab].scene.document.get_entity(handle) {
Some(acadrust::EntityType::Ellipse(ellipse)) => ellipse,
other => panic!("expected an Ellipse, got {other:?}"),
};
assert!((ellipse.center - acadrust::types::Vector3::new(3.0, 7.0, 0.0)).length() < 1.0e-9);
assert!(ellipse.major_axis.x.abs() < 1.0e-7);
assert!((ellipse.major_axis.length() - 5.0).abs() < 1.0e-7);
assert!((ellipse.minor_axis_ratio - 0.4).abs() < 1.0e-9);
}
/// Drawing commands must not create parametric constraints implicitly.
#[test]
fn drawing_a_line_onto_an_existing_endpoint_does_not_add_a_constraint() {
+145 -31
View File
@@ -1016,6 +1016,26 @@ impl OpenCADStudio {
}
// ── Persistent constraints ────────────────────────────────────
"CONSTRAINTBAR" | "CONSTRAINTBAR_OPTIONS" => {
use crate::modules::parametric::ConstraintBarOptionCommand;
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() && cmd == "CONSTRAINTBAR" {
use crate::modules::draw::select::SelectObjectsCommand;
let command =
SelectObjectsCommand::routed("CONSTRAINTBAR", "CONSTRAINTBAR_OPTIONS");
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
} else if handles.is_empty() {
self.command_line.push_output("No objects selected.");
} else {
let command = ConstraintBarOptionCommand::new(handles);
self.command_line.push_info(&command.prompt());
self.command_line.set_step_options(command.options());
self.tabs[i].active_cmd = Some(Box::new(command));
}
}
"GCSHOW" | "GCHIDE" | "DCSHOW" | "DCHIDE" => {
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() {
@@ -1048,6 +1068,24 @@ impl OpenCADStudio {
.push_output(format!("{} constraint indicator(s) reset.", count).as_str());
}
"CONSTRAINTBAR_RESET" => {
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() {
self.command_line.push_output("No objects selected.");
} else {
let scope = self.tabs[i].current_parametric_scope();
let count = self.tabs[i].scene.set_parametric_constraint_visibility(
scope,
Some(&handles),
false,
true,
);
self.command_line.push_output(
format!("{} constraint bar(s) reset.", count).as_str(),
);
}
}
"GCSHOWALL" | "GCHIDEALL" | "DCSHOWALL" | "DCHIDEALL" => {
let scope = self.tabs[i].current_parametric_scope();
let dimensional = cmd.starts_with("DC");
@@ -1206,17 +1244,38 @@ impl OpenCADStudio {
}
}
"SMOOTHCONSTRAINT" => {
"GCSMOOTH" => {
use crate::modules::parametric::SmoothConstraintCommand;
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() {
use crate::modules::draw::select::SelectObjectsCommand;
let sel = SelectObjectsCommand::new(cmd);
self.command_line.push_info(&sel.prompt());
self.tabs[i].active_cmd = Some(Box::new(sel));
let command = SmoothConstraintCommand::new();
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
} else if handles.len() != 2 {
self.tabs[i].scene.deselect_all();
self.command_line.push_error(
"Smooth requires an open spline first and a target curve second.",
);
let command = SmoothConstraintCommand::new();
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
} else {
let Some(refs) = self.tabs[i].scene.smooth_constraint_refs(&handles) else {
self.command_line
.push_output("Select one open spline and one open target curve.");
let first = self.tabs[i].scene.document.get_entity(handles[0]);
let second = self.tabs[i].scene.document.get_entity(handles[1]);
let refs = first.zip(second).and_then(|(first, second)| {
SmoothConstraintCommand::preselected_refs(
(first, handles[0]),
(second, handles[1]),
)
});
let Some(refs) = refs else {
self.tabs[i].scene.deselect_all();
self.command_line.push_error(
"Smooth requires an open spline first and a line, arc, polyline segment or open spline second.",
);
let command = SmoothConstraintCommand::new();
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
return None;
};
use crate::command::CmdResult;
@@ -1318,7 +1377,50 @@ impl OpenCADStudio {
}
}
"HCONSTRAINT" | "VCONSTRAINT" | "FXCONSTRAINT" => {
"GCHORIZONTAL" => {
use crate::command::{CmdResult, HorizontalConstraintSelection};
use crate::modules::parametric::HorizontalConstraintCommand;
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() {
let command = HorizontalConstraintCommand::new();
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
} else if handles.len() != 1 {
self.command_line
.push_error("Horizontal: select exactly one compatible object.");
} else {
let handle = handles[0];
let reference = self.tabs[i]
.scene
.document
.get_entity(handle)
.and_then(|entity| {
HorizontalConstraintCommand::preselected_reference(entity, handle)
});
if let Some(reference) = reference {
let direction = self.tabs[i].ucs_xform().working_plane().x;
return Some(self.apply_cmd_result(CmdResult::AddHorizontalConstraint {
selection: HorizontalConstraintSelection::Reference(reference),
direction: acadrust::types::Vector3::new(
direction.x,
direction.y,
direction.z,
),
label: "Horizontal constraint",
}));
}
self.tabs[i].scene.deselect_all();
self.command_line.push_error(
"Horizontal: select a line, straight polyline segment, text, MText, or an ellipse axis.",
);
let command = HorizontalConstraintCommand::new();
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
}
}
"VCONSTRAINT" | "FXCONSTRAINT" => {
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() {
use crate::modules::draw::select::SelectObjectsCommand;
@@ -1331,10 +1433,10 @@ impl OpenCADStudio {
} else {
use crate::command::CmdResult;
use crate::scene::parametric_constraints::{ConstraintKind, ParametricRef};
let (kind, label) = match cmd {
"HCONSTRAINT" => (ConstraintKind::Horizontal, "Horizontal constraint"),
"VCONSTRAINT" => (ConstraintKind::Vertical, "Vertical constraint"),
_ => (ConstraintKind::Fixed, "Fixed constraint"),
let (kind, label) = if cmd == "VCONSTRAINT" {
(ConstraintKind::Vertical, "Vertical constraint")
} else {
(ConstraintKind::Fixed, "Fixed constraint")
};
return Some(self.apply_cmd_result(CmdResult::AddParametricConstraint {
kind,
@@ -1475,30 +1577,42 @@ impl OpenCADStudio {
}
}
"NCONSTRAINT" => {
"GCCONCENTRIC" => {
use crate::command::CmdResult;
use crate::modules::parametric::ConcentricConstraintCommand;
let handles = self.tabs[i].scene.selected_handles_in_order();
if handles.is_empty() {
use crate::modules::draw::select::SelectObjectsCommand;
let sel = SelectObjectsCommand::new(cmd);
self.command_line.push_info(&sel.prompt());
self.tabs[i].active_cmd = Some(Box::new(sel));
} else if handles.len() != 2 {
self.command_line.push_output(
"Select exactly two circles/arcs, then run this constraint again.",
);
let command = ConcentricConstraintCommand::new();
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
} else {
use crate::command::CmdResult;
use crate::scene::parametric_constraints::{ConstraintKind, ParametricRef};
return Some(self.apply_cmd_result(CmdResult::AddParametricConstraint {
kind: ConstraintKind::Concentric,
refs: vec![
ParametricRef::center(handles[0]),
ParametricRef::center(handles[1]),
],
driving_param: None,
let refs = handles
.iter()
.filter_map(|handle| {
let entity = self.tabs[i].scene.document.get_entity(*handle)?;
ConcentricConstraintCommand::preselected_reference(entity, *handle)
})
.collect::<Vec<_>>();
if handles.len() == 2 && refs.len() == 2 && refs[0] != refs[1] {
return Some(self.apply_cmd_result(CmdResult::AddConcentricConstraint {
first: refs[0],
second: refs[1],
label: "Concentric constraint",
}));
}
self.tabs[i].scene.deselect_all();
self.command_line.push_error(
"Invalid selection for Concentric. Select a circle, arc, ellipse or polyline arc segment.",
);
let command = refs
.first()
.copied()
.map(ConcentricConstraintCommand::with_first)
.unwrap_or_else(ConcentricConstraintCommand::new);
self.command_line.push_info(&command.prompt());
self.tabs[i].active_cmd = Some(Box::new(command));
}
}
"SYCONSTRAINT" => {
+13 -3
View File
@@ -1051,6 +1051,7 @@ impl OpenCADStudio {
| "CONSTRAINTSOLVEMODE"
| "CONSTRAINTINFER"
| "CONSTRAINTBARDISPLAY"
| "CONSTRAINTBARMODE"
) =>
{
return self.dispatch_styleprops(&format!("SETVAR {cmd}"), i);
@@ -1073,7 +1074,7 @@ impl OpenCADStudio {
let value = it.next().map(|s| s.trim().to_string());
if name.is_empty() || name == "?" {
self.command_line.push_info(
crate::t!("SETVAR: CETRANSPARENCY LTSCALE CELTSCALE PDMODE PDSIZE TEXTSIZE ORTHOMODE FILLMODE MIRRTEXT FRAME IMAGEFRAME PDFFRAME WIPEOUTFRAME XCLIPFRAME POINTCLOUDCLIPFRAME ZOOMWHEEL ZOOMFACTOR SHORTCUTMENU SHORTCUTMENUDURATION CURSORSIZE PICKBOX CURSORTYPE SNAPANG TEXTFILL CLIPROMPTLINES COMMANDLINEFADETIME ATTREQ ATTDIA DIMASSOC DIMCONTINUEMODE CONSTRAINTSOLVEMODE CONSTRAINTINFER CONSTRAINTBARDISPLAY ANGBASE ANGDIR SKETCHINC SKPOLY SKTOLERANCE DONUTID DONUTOD CENTEREXE CENTERLAYER CENTERLTYPE CENTERLTSCALE CENTERLTYPEFILE CENTERCROSSSIZE CENTERCROSSGAP CENTERMARKEXE COLORTHEME SELECTIONAREA SELECTIONAREAOPACITY SELECTIONEFFECT SELECTIONEFFECTCOLOR WINDOWSAREACOLOR CROSSINGAREACOLOR SELECTIONPREVIEW GRIPSIZE GRIPCOLOR GRIPHOT GRIPHOVER GRIPOBJLIMIT | CLAYER CELTYPE TEXTSTYLE (read-only)").as_ref(),
crate::t!("SETVAR: CETRANSPARENCY LTSCALE CELTSCALE PDMODE PDSIZE TEXTSIZE ORTHOMODE FILLMODE MIRRTEXT FRAME IMAGEFRAME PDFFRAME WIPEOUTFRAME XCLIPFRAME POINTCLOUDCLIPFRAME ZOOMWHEEL ZOOMFACTOR SHORTCUTMENU SHORTCUTMENUDURATION CURSORSIZE PICKBOX CURSORTYPE SNAPANG TEXTFILL CLIPROMPTLINES COMMANDLINEFADETIME ATTREQ ATTDIA DIMASSOC DIMCONTINUEMODE CONSTRAINTSOLVEMODE CONSTRAINTINFER CONSTRAINTBARDISPLAY CONSTRAINTBARMODE ANGBASE ANGDIR SKETCHINC SKPOLY SKTOLERANCE DONUTID DONUTOD CENTEREXE CENTERLAYER CENTERLTYPE CENTERLTSCALE CENTERLTYPEFILE CENTERCROSSSIZE CENTERCROSSGAP CENTERMARKEXE COLORTHEME SELECTIONAREA SELECTIONAREAOPACITY SELECTIONEFFECT SELECTIONEFFECTCOLOR WINDOWSAREACOLOR CROSSINGAREACOLOR SELECTIONPREVIEW GRIPSIZE GRIPCOLOR GRIPHOT GRIPHOVER GRIPOBJLIMIT | CLAYER CELTYPE TEXTSTYLE (read-only)").as_ref(),
);
} else {
if name == "CETRANSPARENCY" {
@@ -1269,15 +1270,23 @@ impl OpenCADStudio {
}
if matches!(
name.as_str(),
"CONSTRAINTSOLVEMODE" | "CONSTRAINTINFER" | "CONSTRAINTBARDISPLAY"
"CONSTRAINTSOLVEMODE"
| "CONSTRAINTINFER"
| "CONSTRAINTBARDISPLAY"
| "CONSTRAINTBARMODE"
) {
let current = match name.as_str() {
"CONSTRAINTSOLVEMODE" => i16::from(self.constraint_solve_mode),
"CONSTRAINTINFER" => i16::from(self.constraint_infer),
"CONSTRAINTBARDISPLAY" => self.constraint_bar_display,
"CONSTRAINTBARMODE" => self.constraint_bar_mode,
_ => unreachable!(),
};
let maximum = if name == "CONSTRAINTBARDISPLAY" { 3 } else { 1 };
let maximum = match name.as_str() {
"CONSTRAINTBARDISPLAY" => 3,
"CONSTRAINTBARMODE" => 4095,
_ => 1,
};
if let Some(value) = &value {
match value
.parse::<i16>()
@@ -1293,6 +1302,7 @@ impl OpenCADStudio {
"CONSTRAINTBARDISPLAY" => {
self.constraint_bar_display = mode
}
"CONSTRAINTBARMODE" => self.constraint_bar_mode = mode,
_ => unreachable!(),
}
self.persist_settings_if_changed();
+19
View File
@@ -220,6 +220,25 @@ fn command_category(name: &str) -> &'static str {
"view"
} else if name.starts_with("DIM") || ["LEADER", "MLEADER", "TOLERANCE"].contains(&name) {
"annotate"
} else if [
"GEOMCONSTRAINT",
"GCCOINCIDENT",
"GCCOLLINEAR",
"GCPERPENDICULAR",
"QCONSTRAINT",
"PCONSTRAINT",
"GCHORIZONTAL",
"VCONSTRAINT",
"ECONSTRAINT",
"TCONSTRAINT",
"GCCONCENTRIC",
"NRCONSTRAINT",
"LCONSTRAINT",
"DELCONSTRAINT",
]
.contains(&name)
{
"parametric"
} else if [
"BOX",
"CYLINDER",
+1 -19
View File
@@ -1,5 +1,4 @@
use crate::command::CadCommand;
use crate::io::linetypes;
use crate::modules::draw::modify::block_edit::BlockEditSession;
use crate::modules::draw::modify::refedit::RefEditSession;
use crate::scene::pick::grip::GripEdit;
@@ -593,24 +592,7 @@ impl DocumentTab {
pub(super) fn new_drawing(n: usize) -> Self {
let mut scene = Scene::new();
linetypes::populate_document(&mut scene.document);
// Paper layouts start as A4 landscape.
for obj in scene.document.objects.values_mut() {
if let acadrust::objects::ObjectType::Layout(l) = obj {
if l.name != "Model" {
l.min_limits = (0.0, 0.0);
l.max_limits = (297.0, 210.0);
l.min_extents = (0.0, 0.0, 0.0);
l.max_extents = (297.0, 210.0, 0.0);
l.paper_width = 297.0;
l.paper_height = 210.0;
l.plot_paper_units = 1;
l.plot_scale_numerator = 1.0;
l.plot_scale_denominator = 1.0;
l.paper_size = "ISO_A4_(297.00_x_210.00_MM)".into();
}
}
}
scene.populate_new_drawing_defaults();
Self {
id: NEXT_DOCUMENT_TAB_ID.fetch_add(1, Ordering::Relaxed),
scene,
+2
View File
@@ -602,6 +602,7 @@ pub(super) struct OpenCADStudio {
pub constraint_solve_mode: bool,
pub constraint_infer: bool,
pub constraint_bar_display: i16,
pub constraint_bar_mode: i16,
/// Minutes between autosaves to a `.sv$` recovery file (SAVETIME command);
/// 0 disables autosave.
pub savetime_min: i32,
@@ -3906,6 +3907,7 @@ impl OpenCADStudio {
constraint_solve_mode: true,
constraint_infer: false,
constraint_bar_display: 3,
constraint_bar_mode: 4095,
savetime_min: 10,
default_bg_color: None,
default_paper_bg_color: None,
+8
View File
@@ -465,6 +465,9 @@ pub struct UserSettings {
/// Constraint bar display bit mask: 1 after applying, 2 on selection.
#[serde(default = "default_constraint_bar_display")]
pub constraint_bar_display: i16,
/// Geometric constraint type bit mask (1..2048, combined; default all).
#[serde(default = "default_constraint_bar_mode")]
pub constraint_bar_mode: i16,
/// Minutes between autosaves to a `.sv$` recovery file (SAVETIME command).
/// 0 disables autosave.
pub savetime_min: i32,
@@ -595,6 +598,10 @@ fn default_constraint_bar_display() -> i16 {
3
}
fn default_constraint_bar_mode() -> i16 {
4095
}
fn deserialize_clipromptlines<'de, D>(de: D) -> Result<i32, D::Error>
where
D: serde::Deserializer<'de>,
@@ -662,6 +669,7 @@ impl Default for UserSettings {
constraint_solve_mode: true,
constraint_infer: false,
constraint_bar_display: 3,
constraint_bar_mode: 4095,
savetime_min: 10,
default_save_format: crate::io::DEFAULT_SAVE_FORMAT.to_string(),
pick_add: true,
+2 -4
View File
@@ -1739,15 +1739,13 @@ pub(super) fn on_tab_close(&mut self, idx: usize) -> Task<Message> {
.get_entity(popup.handle)
.is_some_and(|entity| match (item.action, entity) {
(GripMenuAction::ShowFit, acadrust::EntityType::Spline(spline)) => {
!spline.cv_frame_visible
&& crate::entities::spline::uses_fit_method(spline)
crate::entities::spline::shows_fit_points(spline)
}
(
GripMenuAction::ShowControlVertices,
acadrust::EntityType::Spline(spline),
) => {
spline.cv_frame_visible
|| !crate::entities::spline::uses_fit_method(spline)
crate::entities::spline::shows_control_vertices(spline)
}
_ => false,
});
+673 -185
View File
@@ -152,6 +152,96 @@ fn paper_name_for_settings(
}
}
/// The stored rotation for the dialog's sheet on a medium that is itself
/// `natural`-oriented: a quarter turn when the requested orientation differs
/// from the medium's own, and "upside-down" adds a half turn on top. This is
/// how the commercial application writes it — a system printer's portrait
/// `A3` plotted landscape carries 90°, while its PDF driver's landscape
/// `ISO_A4_(297.00_x_210.00_MM)` medium plotted landscape carries 0°.
fn plot_dialog_rotation(
d: &crate::ui::window::plot::PlotDialogState,
natural: crate::io::paper_catalog::Orientation,
) -> acadrust::objects::PlotRotation {
use acadrust::objects::PlotRotation;
match (plot_dialog_orientation(d) != natural, d.upside_down) {
(false, false) => PlotRotation::None,
(true, false) => PlotRotation::Degrees90,
(false, true) => PlotRotation::Degrees180,
(true, true) => PlotRotation::Degrees270,
}
}
/// Millimetres in the paper unit a page setup counts in.
fn plot_paper_unit_mm(units: acadrust::objects::PlotPaperUnits) -> f64 {
match units {
acadrust::objects::PlotPaperUnits::Inches => 25.4,
_ => 1.0,
}
}
/// The factor the commercial application stores next to the scale (DXF 147)
/// is the `paper : drawing` ratio times 25.4 on millimetre page setups and
/// the plain ratio on inch ones — observed in its files, whatever the
/// published description says. Both directions of that convention live here.
fn stored_scale_factor(ratio: f64, units: acadrust::objects::PlotPaperUnits) -> f64 {
match units {
acadrust::objects::PlotPaperUnits::Millimeters => ratio * 25.4,
_ => ratio,
}
}
fn ratio_from_stored_scale_factor(factor: f64, units: acadrust::objects::PlotPaperUnits) -> f64 {
match units {
acadrust::objects::PlotPaperUnits::Millimeters => factor / 25.4,
_ => factor,
}
}
/// The file format's standard scale for a `paper : drawing` ratio, when it
/// has one. Only the metric ratios exist as standard codes here; an
/// architectural scale is stored as a custom ratio with the same value.
fn standard_scale_for_ratio(paper: f64, drawing: f64) -> Option<acadrust::objects::ScaledType> {
use acadrust::objects::ScaledType as S;
const STANDARD: &[(f64, f64, S)] = &[
(1.0, 1.0, S::OneToOne),
(1.0, 2.0, S::OneToTwo),
(1.0, 4.0, S::OneToFour),
(1.0, 8.0, S::OneToEight),
(1.0, 10.0, S::OneToTen),
(1.0, 16.0, S::OneToSixteen),
(1.0, 20.0, S::OneToTwenty),
(1.0, 30.0, S::OneToThirty),
(1.0, 40.0, S::OneToForty),
(1.0, 50.0, S::OneToFifty),
(1.0, 100.0, S::OneToHundred),
(2.0, 1.0, S::TwoToOne),
(4.0, 1.0, S::FourToOne),
(8.0, 1.0, S::EightToOne),
(10.0, 1.0, S::TenToOne),
(100.0, 1.0, S::HundredToOne),
];
let ratio = paper / drawing;
STANDARD
.iter()
.find(|(p, d, _)| (p / d - ratio).abs() <= 1e-9 * ratio.abs().max(1.0))
.map(|(_, _, scale)| *scale)
}
/// A scale-list name for a plot scale the drawing has no name for, spelled as
/// the ratio it is (`1:250`, `25.4:1`) so the value survives in the picker
/// instead of collapsing to 1:1.
fn ratio_scale_name(factor: f64) -> String {
let trim = |value: f64| {
let text = format!("{value:.4}");
text.trim_end_matches('0').trim_end_matches('.').to_string()
};
if factor >= 1.0 {
format!("{}:1", trim(factor))
} else {
format!("1:{}", trim(1.0 / factor))
}
}
/// The plot device the dialog currently targets.
fn plot_dialog_device(d: &crate::ui::window::plot::PlotDialogState) -> crate::io::plot_device::PlotDevice {
use crate::io::plot_device::PlotDevice;
@@ -521,6 +611,7 @@ impl OpenCADStudio {
constraint_solve_mode: self.constraint_solve_mode,
constraint_infer: self.constraint_infer,
constraint_bar_display: self.constraint_bar_display,
constraint_bar_mode: self.constraint_bar_mode,
savetime_min: self.savetime_min,
default_save_format: self.default_save_format.clone(),
pick_add: self.pick_add,
@@ -624,6 +715,7 @@ impl OpenCADStudio {
self.constraint_solve_mode = s.constraint_solve_mode;
self.constraint_infer = s.constraint_infer;
self.constraint_bar_display = s.constraint_bar_display.clamp(0, 3);
self.constraint_bar_mode = s.constraint_bar_mode.clamp(0, 4095);
self.savetime_min = s.savetime_min;
self.default_save_format =
crate::io::canonical_save_format(&s.default_save_format).to_string();
@@ -3004,112 +3096,195 @@ impl OpenCADStudio {
iced::exit()
}
/// Write the given plot page settings into the active layout.
/// No-op on the Model tab (which has no paper layout). Marks the tab dirty
/// and re-tessellates the sheet. Called by the Plot dialog's Set current action.
#[allow(clippy::too_many_arguments)]
pub(super) fn apply_plot_page_settings(
&mut self,
w: f64,
h: f64,
plot_area: &str,
center: bool,
offset_x: f64,
offset_y: f64,
rotation: i16,
) {
let i = self.active_tab;
let dialog = self.plot_dialog.clone();
let layout_name = self.tabs[i].scene.current_layout.clone();
let plot_window = self.plot_window;
if layout_name != "Model" {
let w: f64 = w.max(1.0);
let h: f64 = h.max(1.0);
use acadrust::objects::{
PlotRotation, PlotSettings, PlotType, ScaledType, ShadePlotMode,
ShadePlotResolutionLevel,
};
let mut ps = self
.plot_setup_template
/// The settings the dialog edits on top of: the named page setup it was
/// loaded from, else the active layout's own, else a fresh metric sheet.
/// Everything the dialog has no control for (viewport-border and
/// paper-update flags, the plot view handle, the paper unit that fixes
/// the layout's coordinate system) is carried over from here untouched.
fn dialog_base_settings(&self) -> acadrust::objects::PlotSettings {
use acadrust::objects::{PlotPaperUnits, PlotSettings};
let scene = &self.tabs[self.active_tab].scene;
self.plot_setup_template
.clone()
.or_else(|| self.tabs[i].scene.plot_settings_for(&layout_name))
.unwrap_or_else(|| PlotSettings::new(""));
.or_else(|| scene.plot_settings_for(&scene.current_layout))
.unwrap_or_else(|| {
let mut settings = PlotSettings::new("");
settings.paper_units = PlotPaperUnits::Millimeters;
settings
})
}
/// The page setup the dialog describes, written the way the file format
/// expects it: the portrait medium with the orientation in `rotation`,
/// standard scales by their code, custom ones as a readable ratio in the
/// layout's own paper unit. Named page setups and the layout's embedded
/// settings both come from here so the two can never drift apart.
fn plot_settings_from_dialog(
&self,
mut ps: acadrust::objects::PlotSettings,
) -> acadrust::objects::PlotSettings {
use crate::io::paper_catalog::Orientation;
use acadrust::objects::{PlotType, ScaledType, ShadePlotMode, ShadePlotResolutionLevel};
let d = &self.plot_dialog;
let scene = &self.tabs[self.active_tab].scene;
// Names and margins are decided against the stored settings before
// any field is overwritten.
let paper_size = paper_name_for_settings(&dialog, &ps);
let printer_name = device_name_for_settings(&dialog, &ps);
let margins = margins_for_settings(&dialog, &ps);
let paper_size = paper_name_for_settings(d, &ps);
let printer_name = device_name_for_settings(d, &ps);
let margins = margins_for_settings(d, &ps);
let same_medium = paper_unchanged(d, &ps) && ps.paper_width > 0.0 && ps.paper_height > 0.0;
ps.paper_size = paper_size;
ps.printer_name = printer_name;
ps.margins = margins;
ps.paper_width = w;
ps.paper_height = h;
ps.plot_type = match plot_area {
// An unchanged sheet keeps the medium exactly as the drawing stores
// it — its driver's precise dimensions in the orientation the driver
// defines it (a PDF driver lists landscape media of its own) — and
// only the rotation says how the sheet is plotted on it. A new
// selection is written as the catalogue's portrait medium.
let natural = if same_medium {
if ps.paper_width > ps.paper_height {
Orientation::Landscape
} else {
Orientation::Portrait
}
} else {
let (width, height) = plot_dialog_paper(d).portrait_mm();
ps.paper_width = width.max(1.0);
ps.paper_height = height.max(1.0);
Orientation::Portrait
};
ps.rotation = plot_dialog_rotation(d, natural);
let layout_area = d.area == "Layout";
ps.plot_type = match d.area.as_str() {
"Window" => PlotType::Window,
"Layout" => PlotType::Layout,
"Display" => PlotType::LastScreenDisplay,
"Extents" => PlotType::Extents,
"Limits" => PlotType::Limits,
area if area.starts_with("View: ") => PlotType::View,
_ => PlotType::Layout,
_ => PlotType::Extents,
};
ps.plot_view_name = plot_area.strip_prefix("View: ").unwrap_or("").to_string();
if plot_area == "Window" {
if let Some((x0, y0, x1, y1)) = plot_window {
ps.plot_view_name = d.area.strip_prefix("View: ").unwrap_or("").to_string();
if d.area == "Window" {
if let Some((x0, y0, x1, y1)) = self.plot_window {
ps.set_plot_window(x0, y0, x1, y1);
}
}
ps.flags.plot_centered = center && plot_area != "Layout";
ps.origin_x = if plot_area == "Layout" { 0.0 } else { offset_x };
ps.origin_y = if plot_area == "Layout" { 0.0 } else { offset_y };
ps.rotation = match rotation {
90 => PlotRotation::Degrees90,
180 => PlotRotation::Degrees180,
270 => PlotRotation::Degrees270,
_ => PlotRotation::None,
};
if dialog.fit_to_paper && plot_area != "Layout" {
ps.set_scale_to_fit();
} else if plot_area == "Layout" {
ps.set_standard_scale(ScaledType::OneToOne);
ps.standard_scale_factor = 1.0;
ps.flags.plot_centered = d.center && !layout_area;
ps.origin_x = if layout_area {
0.0
} else {
let factor = plot_dialog_scale_factor(&dialog);
ps.scale_type = ScaledType::CustomScale;
ps.scale_numerator = factor;
ps.scale_denominator = 1.0;
ps.standard_scale_factor = factor;
ps.flags.use_standard_scale = false;
d.offset_x.parse::<f64>().unwrap_or(0.0)
};
ps.origin_y = if layout_area {
0.0
} else {
d.offset_y.parse::<f64>().unwrap_or(0.0)
};
if d.fit_to_paper && !layout_area {
ps.set_scale_to_fit();
// The commercial application marks fitted plots with the
// "standard scale" bit and leaves the ratio it computed.
ps.flags.use_standard_scale = true;
} else {
// The dialog's factor is per the drawing's scale-family unit
// (inches for an imperial drawing, else millimetres) and already
// includes the drawing-unit factor; the file stores it per the
// layout's paper unit. A named ratio is kept as written when no
// drawing-unit factor hides inside it — a metre drawing plotting
// "1:100" really plots 10 mm per unit, which is what the file
// must say — and its standard code is kept even across a
// paper-unit conversion, the way the commercial application
// writes "1:1" on an inch page setup over a millimetre paper
// space as `1 in = 25.4 units`. A layout plot goes through the
// same path: the dialog holds it at 1:1, which the conversion
// turns into whatever keeps the paper space's unit intact.
let factor = plot_dialog_scale_factor(d);
let conversion = scene.scale_family_unit_mm() / plot_paper_unit_mm(ps.paper_units);
let named = scene.scale_ratio(&d.scale).filter(|(paper, drawing)| {
(paper / drawing - factor).abs() <= 1e-9 * factor.abs().max(1.0)
});
let standard =
named.and_then(|(paper, drawing)| standard_scale_for_ratio(paper, drawing));
let (numerator, denominator) = match named {
Some((paper, drawing)) if (conversion - 1.0).abs() <= 1e-12 => (paper, drawing),
_ => {
let per_unit = (factor * conversion).max(1e-9);
if per_unit >= 1.0 {
(per_unit, 1.0)
} else {
(1.0, 1.0 / per_unit)
}
ps.current_style_sheet = dialog.style_name.clone();
ps.flags.scale_lineweights = dialog.scale_lw;
ps.flags.print_lineweights = dialog.lineweights;
ps.flags.plot_plot_styles = dialog.apply_plot_styles && !dialog.style_name.is_empty();
ps.flags.show_plot_styles = dialog.show_plot_styles && !dialog.style_name.is_empty();
ps.flags.draw_viewports_first = dialog.paperspace_last;
ps.flags.plot_hidden = dialog.shade == "Hidden Line";
ps.shade_plot_mode = match dialog.shade.as_str() {
}
};
// The commercial application leaves the "standard scale" bit
// clear even for a standard code and keeps the ratio in the
// numerator/denominator pair; readers that trust the bit would
// otherwise take the stored factor as the ratio itself.
ps.scale_type = standard.unwrap_or(ScaledType::CustomScale);
ps.flags.use_standard_scale = false;
ps.scale_numerator = numerator;
ps.scale_denominator = denominator;
ps.standard_scale_factor =
stored_scale_factor(numerator / denominator, ps.paper_units);
}
ps.current_style_sheet = d.style_name.clone();
ps.flags.scale_lineweights = d.scale_lw;
ps.flags.print_lineweights = d.lineweights;
ps.flags.plot_plot_styles = d.apply_plot_styles;
ps.flags.show_plot_styles = d.show_plot_styles;
ps.flags.draw_viewports_first = d.paperspace_last;
ps.flags.plot_hidden = d.shade == "Hidden Line";
ps.shade_plot_mode = match d.shade.as_str() {
"2D Wireframe" | "3D Wireframe" => ShadePlotMode::Wireframe,
"Hidden Line" => ShadePlotMode::Hidden,
"As displayed" => ShadePlotMode::AsDisplayed,
_ => ShadePlotMode::Rendered,
};
ps.shade_plot_resolution = match dialog.quality.as_str() {
ps.shade_plot_resolution = match d.quality.as_str() {
"Low" => ShadePlotResolutionLevel::Draft,
"High" => ShadePlotResolutionLevel::Presentation,
_ => ShadePlotResolutionLevel::Normal,
};
ps.shade_plot_dpi = 300;
ps
}
/// Write the dialog's page setup into the active layout. No-op on the
/// Model tab (which has no paper layout). Marks the tab dirty and
/// re-tessellates the sheet. Called by the Plot dialog's Set current action.
pub(super) fn apply_plot_page_settings(&mut self) {
let i = self.active_tab;
let layout_name = self.tabs[i].scene.current_layout.clone();
if layout_name == "Model" {
return;
}
let ps = self.plot_settings_from_dialog(self.dialog_base_settings());
let (w, h) = plot_dialog_sheet_mm(&self.plot_dialog);
let plot_area = self.plot_dialog.area.clone();
let center = ps.flags.plot_centered;
let rotation = ps.rotation.to_degrees() as i32;
self.tabs[i]
.scene
.set_layout_plot_settings(&layout_name, &ps);
// Layout limits are the sheet in paper-space units, which the
// settings just written define, placed the way the commercial
// application places it: the printable area's corner is the paper
// space origin, so the sheet starts at minus its displayed margins.
let units_per_mm = self.tabs[i].scene.paper_space_unit_factor().max(1e-9);
let m = ps.margins;
let (left, bottom, ..) = crate::scene::rotated_margins(
(m.left, m.bottom, m.right, m.top),
ps.rotation.to_code(),
);
let (x0, y0) = (-left * units_per_mm, -bottom * units_per_mm);
let (lw, lh) = (w * units_per_mm, h * units_per_mm);
for obj in self.tabs[i].scene.document.objects.values_mut() {
if let acadrust::objects::ObjectType::Layout(layout) = obj {
if layout.name == layout_name {
layout.min_limits = (0.0, 0.0);
layout.max_limits = (w, h);
layout.min_extents = (0.0, 0.0, 0.0);
layout.max_extents = (w, h, 0.0);
layout.min_limits = (x0, y0);
layout.max_limits = (x0 + lw, y0 + lh);
layout.min_extents = (x0, y0, 0.0);
layout.max_extents = (x0 + lw, y0 + lh, 0.0);
break;
}
}
@@ -3125,7 +3300,6 @@ impl OpenCADStudio {
.as_ref(),
);
}
}
pub(in crate::app) fn on_plot_export_path_some(
&mut self,
@@ -4552,94 +4726,9 @@ impl OpenCADStudio {
/// Build a `PlotSettings` from the current dialog fields (for saving a named
/// page setup).
/// The dialog's values as a named page setup.
fn dialog_to_plotsettings(&self) -> acadrust::objects::PlotSettings {
use acadrust::objects::{
PlotPaperUnits, PlotRotation, PlotSettings, PlotType, ScaledType, ShadePlotMode,
ShadePlotResolutionLevel,
};
let d = &self.plot_dialog;
let (w, h) = plot_dialog_sheet_mm(d);
let mut ps = match self.plot_setup_template.clone() {
Some(settings) => settings,
None => {
let mut settings = PlotSettings::new("");
settings.paper_units = PlotPaperUnits::Millimeters;
settings
}
};
let paper_size = paper_name_for_settings(d, &ps);
let printer_name = device_name_for_settings(d, &ps);
let margins = margins_for_settings(d, &ps);
ps.paper_size = paper_size;
ps.printer_name = printer_name;
ps.margins = margins;
ps.paper_width = w;
ps.paper_height = h;
ps.plot_type = match d.area.as_str() {
"Window" => PlotType::Window,
"Layout" => PlotType::Layout,
"Display" => PlotType::LastScreenDisplay,
"Limits" => PlotType::Limits,
area if area.starts_with("View: ") => PlotType::View,
_ => PlotType::Extents,
};
ps.plot_view_name = d.area.strip_prefix("View: ").unwrap_or("").to_string();
if d.area == "Window" {
if let Some((x0, y0, x1, y1)) = self.plot_window {
ps.set_plot_window(x0, y0, x1, y1);
}
}
ps.flags.plot_centered = d.center && d.area != "Layout";
ps.origin_x = if d.area == "Layout" {
0.0
} else {
d.offset_x.parse::<f64>().unwrap_or(0.0)
};
ps.origin_y = if d.area == "Layout" {
0.0
} else {
d.offset_y.parse::<f64>().unwrap_or(0.0)
};
let rot: i16 = if d.upside_down { 180 } else { 0 };
ps.rotation = match rot {
90 => PlotRotation::Degrees90,
180 => PlotRotation::Degrees180,
270 => PlotRotation::Degrees270,
_ => PlotRotation::None,
};
if d.area == "Layout" {
ps.set_standard_scale(ScaledType::OneToOne);
ps.standard_scale_factor = 1.0;
} else if d.fit_to_paper {
ps.set_scale_to_fit();
} else {
let factor = plot_dialog_scale_factor(d);
ps.scale_type = ScaledType::CustomScale;
ps.scale_numerator = factor;
ps.scale_denominator = 1.0;
ps.standard_scale_factor = factor;
ps.flags.use_standard_scale = false;
}
ps.current_style_sheet = d.style_name.clone();
ps.flags.scale_lineweights = d.scale_lw;
ps.flags.print_lineweights = d.lineweights;
ps.flags.plot_plot_styles = d.apply_plot_styles && !d.style_name.is_empty();
ps.flags.show_plot_styles = d.show_plot_styles && !d.style_name.is_empty();
ps.flags.draw_viewports_first = d.paperspace_last;
ps.flags.plot_hidden = d.shade == "Hidden Line";
ps.shade_plot_mode = match d.shade.as_str() {
"2D Wireframe" | "3D Wireframe" => ShadePlotMode::Wireframe,
"Hidden Line" => ShadePlotMode::Hidden,
"As displayed" => ShadePlotMode::AsDisplayed,
_ => ShadePlotMode::Rendered,
};
ps.shade_plot_resolution = match d.quality.as_str() {
"Low" => ShadePlotResolutionLevel::Draft,
"High" => ShadePlotResolutionLevel::Presentation,
_ => ShadePlotResolutionLevel::Normal,
};
ps.shade_plot_dpi = 300;
ps
self.plot_settings_from_dialog(self.dialog_base_settings())
}
/// Load a `PlotSettings` into the dialog editor fields.
@@ -4700,6 +4789,7 @@ impl OpenCADStudio {
"Portrait"
}
.to_string();
let family_unit_mm = self.tabs[self.active_tab].scene.scale_family_unit_mm();
let d = &mut self.plot_dialog;
d.paper = paper.canonical.to_string();
d.paper_width_mm = ps.paper_width.max(1.0);
@@ -4735,22 +4825,39 @@ impl OpenCADStudio {
}
d.upside_down = matches!(deg, 180 | 270);
d.fit_to_paper = d.area != "Layout" && ps.is_scale_to_fit();
let target_factor = if d.area == "Layout" {
1.0
} else if ps.flags.use_standard_scale {
if ps.standard_scale_factor.is_finite() && ps.standard_scale_factor > 0.0 {
ps.standard_scale_factor
let ratio = ps.scale_numerator / ps.scale_denominator;
let stored_factor = if ratio.is_finite() && ratio > 0.0 {
ratio
} else if ps.flags.use_standard_scale
&& ps.standard_scale_factor.is_finite()
&& ps.standard_scale_factor > 0.0
{
ratio_from_stored_scale_factor(ps.standard_scale_factor, ps.paper_units)
} else {
ps.scale_type.scale_factor()
}
} else if ps.scale_denominator.abs() > 1e-9 {
ps.scale_numerator / ps.scale_denominator
};
// The file's factor is per the layout's paper unit; the picker's are
// per the drawing's scale-family unit (see `plot_settings_from_dialog`).
let target_factor = if stored_factor.is_finite() && stored_factor > 0.0 {
stored_factor * plot_paper_unit_mm(ps.paper_units) / family_unit_mm
} else {
1.0
};
if !d.fit_to_paper || !d.scales.iter().any(|(name, _)| name == &d.scale) {
d.scale = scale_name_for_factor(&d.scales, target_factor)
.or_else(|| scale_name_for_factor(&d.scales, 1.0))
if !d.fit_to_paper {
d.scale = scale_name_for_factor(&d.scales, target_factor).unwrap_or_else(|| {
// A scale the drawing has no name for stays what it is rather
// than snapping to 1:1; the ratio entry disappears again with
// the next scale-list refresh once it is no longer selected.
let name = ratio_scale_name(target_factor);
d.scales.push((name.clone(), target_factor));
d.scales
.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
name
});
} else if !d.scales.iter().any(|(name, _)| name == &d.scale) {
// A fitted plot's stored ratio is what the fit computed, not a
// choice; the picker just needs a valid entry behind it.
d.scale = scale_name_for_factor(&d.scales, 1.0)
.or_else(|| d.scales.first().map(|(name, _)| name.clone()))
.unwrap_or_else(|| "1:1".into());
}
@@ -4806,12 +4913,7 @@ impl OpenCADStudio {
fn apply_dialog_to_layout(&mut self) {
self.sync_dialog_plot_runtime();
let d = self.plot_dialog.clone();
let (sheet_w, sheet_h) = plot_dialog_sheet_mm(&d);
let rotation: i16 = if d.upside_down { 180 } else { 0 };
let off_x = d.offset_x.parse::<f64>().unwrap_or(0.0);
let off_y = d.offset_y.parse::<f64>().unwrap_or(0.0);
self.apply_plot_page_settings(sheet_w, sheet_h, &d.area, d.center, off_x, off_y, rotation);
self.apply_plot_page_settings();
}
/// Open a preview PDF, export a PDF, or send the job to the chosen printer.
@@ -5239,16 +5341,394 @@ mod plot_paper_tests {
ps.paper_size = "A4".into();
ps.paper_width = 297.0;
ps.paper_height = 210.0;
// Such drivers spell the orientation in the dimensions, not the rotation.
ps.rotation = acadrust::objects::PlotRotation::None;
assert!(app.tabs[i].scene.set_layout_plot_settings("Layout1", &ps));
app
}
fn layout_paper(app: &OpenCADStudio) -> (String, f64, f64) {
let ps = app.tabs[app.active_tab]
let ps = layout_settings(app);
(ps.paper_size, ps.paper_width, ps.paper_height)
}
fn layout_settings(app: &OpenCADStudio) -> acadrust::objects::PlotSettings {
app.tabs[app.active_tab]
.scene
.plot_settings_for("Layout1")
.unwrap();
(ps.paper_size, ps.paper_width, ps.paper_height)
.unwrap()
}
fn layout_rotation(app: &OpenCADStudio) -> acadrust::objects::PlotRotation {
layout_settings(app).rotation
}
/// Store the drawing's plot settings for `Layout1` after `edit` touched them.
fn edit_layout_settings(
app: &mut OpenCADStudio,
edit: impl FnOnce(&mut acadrust::objects::PlotSettings),
) {
let i = app.active_tab;
let mut ps = app.tabs[i].scene.plot_settings_for("Layout1").unwrap();
edit(&mut ps);
assert!(app.tabs[i].scene.set_layout_plot_settings("Layout1", &ps));
}
#[test]
fn a_new_drawing_starts_with_a_compatible_default_layout() {
use acadrust::objects::{PlotRotation, PlotType, ScaledType};
let mut app = OpenCADStudio::new_for_test();
app.automation_op(r#"{"op":"new"}"#);
let _ = app.update(Message::LayoutSwitch("Layout1".into()));
let ps = layout_settings(&app);
assert_eq!(ps.paper_size, "ISO_A4_(210.00_x_297.00_MM)");
assert_eq!((ps.paper_width, ps.paper_height), (210.0, 297.0));
assert_eq!(ps.rotation, PlotRotation::Degrees90);
assert_eq!(ps.printer_name, "none_device");
assert_eq!(ps.plot_type, PlotType::Layout);
assert_eq!(ps.scale_type, ScaledType::OneToOne);
assert!(ps.flags.use_standard_scale && ps.flags.print_lineweights);
// The sheet on screen is the landscape A4 the rotation describes.
let ((x0, y0), (x1, y1)) = app.tabs[app.active_tab].scene.paper_limits().unwrap();
assert_eq!((x1 - x0, y1 - y0), (297.0, 210.0));
let mut app = OpenCADStudio::new_for_test();
app.automation_op(r#"{"op":"new"}"#);
let _ = app.on_plot_dialog_open();
assert_eq!(app.plot_dialog.orientation, "Landscape");
assert!(!app.plot_dialog.upside_down);
}
#[test]
fn orientation_is_stored_as_a_rotation_of_the_medium() {
use acadrust::objects::PlotRotation as R;
use crate::ui::window::plot::PlotFlag;
// A newly picked sheet is the catalogue's portrait medium…
let portrait_medium = [
("Portrait", false, R::None),
("Landscape", false, R::Degrees90),
("Portrait", true, R::Degrees180),
("Landscape", true, R::Degrees270),
];
// …while the drawing's own landscape `A4` medium is kept, so the
// same choices rotate relative to it.
let landscape_medium = [
("Landscape", false, R::None),
("Portrait", false, R::Degrees90),
("Landscape", true, R::Degrees180),
("Portrait", true, R::Degrees270),
];
for (pick_a3, cases) in [(true, portrait_medium), (false, landscape_medium)] {
for (orientation, upside_down, rotation) in cases {
let mut app = app_with_printer_named_sheet();
let _ = app.on_plot_dialog_open();
if pick_a3 {
let a3 = "ISO_A3_(297.00_x_420.00_MM)";
let _ = app.on_plot_dlg(PlotDlgMsg::Paper(a3.into()));
}
let _ = app.on_plot_dlg(PlotDlgMsg::Orientation(orientation.into()));
if upside_down {
let _ = app.on_plot_dlg(PlotDlgMsg::Flag(PlotFlag::UpsideDown));
}
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
let medium = if pick_a3 { (297.0, 420.0) } else { (297.0, 210.0) };
assert_eq!((ps.paper_width, ps.paper_height), medium, "{orientation}");
assert_eq!(ps.rotation, rotation, "{orientation} upside-down={upside_down}");
// The next dialog reads the same choices back out of the rotation.
let _ = app.on_plot_dialog_open();
assert_eq!(app.plot_dialog.orientation, orientation);
assert_eq!(app.plot_dialog.upside_down, upside_down);
let sheet = super::plot_dialog_sheet_mm(&app.plot_dialog);
let long_side = medium.0.max(medium.1);
assert_eq!(sheet.0 > sheet.1, orientation == "Landscape", "{sheet:?}");
assert_eq!(sheet.0.max(sheet.1), long_side);
}
}
}
#[test]
fn standard_scales_are_written_by_code_and_others_as_ratios() {
use acadrust::objects::ScaledType;
let mut app = app_with_printer_named_sheet();
let _ = app.on_plot_dialog_open();
let _ = app.on_plot_dlg(PlotDlgMsg::Area("Extents".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::Flag(crate::ui::window::plot::PlotFlag::FitToPaper));
assert!(!app.plot_dialog.fit_to_paper);
let _ = app.on_plot_dlg(PlotDlgMsg::Scale("1:100".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert_eq!(ps.scale_type, ScaledType::OneToHundred);
assert!(
!ps.flags.use_standard_scale,
"the bit stays clear, as the source application writes it"
);
assert_eq!((ps.scale_numerator, ps.scale_denominator), (1.0, 100.0));
// The stored factor follows the millimetre convention: ratio × 25.4.
assert!((ps.standard_scale_factor - 0.254).abs() < 1e-12);
let _ = app.on_plot_dialog_open();
assert_eq!(app.plot_dialog.scale, "1:100");
// A ratio the format has no code for is a custom scale, spelled as the ratio.
let _ = app.on_plot_dlg(PlotDlgMsg::Scale("1:3".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert_eq!(ps.scale_type, ScaledType::CustomScale);
assert!(!ps.flags.use_standard_scale);
assert_eq!((ps.scale_numerator, ps.scale_denominator), (1.0, 3.0));
// …and survives a reopen even though the drawing's scale list lacks it.
let _ = app.on_plot_dialog_open();
assert_eq!(app.plot_dialog.scale, "1:3");
assert!((super::plot_dialog_scale_factor(&app.plot_dialog) - 1.0 / 3.0).abs() < 1e-12);
// Fit to paper is its own scale type and carries the bit; a Layout
// plot goes back to the 1:1 the dialog holds it at.
let _ = app.on_plot_dlg(PlotDlgMsg::Flag(crate::ui::window::plot::PlotFlag::FitToPaper));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert_eq!(ps.scale_type, ScaledType::ScaleToFit);
assert!(ps.flags.use_standard_scale);
let _ = app.on_plot_dlg(PlotDlgMsg::Area("Layout".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert_eq!(ps.scale_type, ScaledType::OneToOne);
assert!(!ps.flags.use_standard_scale);
assert_eq!((ps.scale_numerator, ps.scale_denominator), (1.0, 1.0));
assert!((ps.standard_scale_factor - 25.4).abs() < 1e-12);
}
#[test]
fn a_metre_drawing_stores_the_millimetres_it_really_plots_per_unit() {
use acadrust::objects::ScaledType;
let mut app = app_with_printer_named_sheet();
// Insertion units: metres. "1:100" then plots 10 mm per drawing unit.
app.tabs[app.active_tab].scene.document.header.insertion_units = 6;
let _ = app.on_plot_dialog_open();
let _ = app.on_plot_dlg(PlotDlgMsg::Area("Extents".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::Flag(crate::ui::window::plot::PlotFlag::FitToPaper));
let _ = app.on_plot_dlg(PlotDlgMsg::Scale("1:100".into()));
assert!((super::plot_dialog_scale_factor(&app.plot_dialog) - 10.0).abs() < 1e-9);
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert_eq!(ps.scale_type, ScaledType::CustomScale, "not the format's 1:100");
assert_eq!((ps.scale_numerator, ps.scale_denominator), (10.0, 1.0));
assert!((ps.standard_scale_factor - 254.0).abs() < 1e-9);
let _ = app.on_plot_dialog_open();
assert_eq!(app.plot_dialog.scale, "1:100");
}
#[test]
fn an_inch_layout_keeps_its_unit_and_converts_the_scale() {
use acadrust::objects::{PlotPaperUnits, ScaledType};
let mut app = app_with_printer_named_sheet();
edit_layout_settings(&mut app, |ps| ps.paper_units = PlotPaperUnits::Inches);
let _ = app.on_plot_dialog_open();
let _ = app.on_plot_dlg(PlotDlgMsg::Area("Extents".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::Flag(crate::ui::window::plot::PlotFlag::FitToPaper));
let _ = app.on_plot_dlg(PlotDlgMsg::Scale("1:100".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert_eq!(
ps.paper_units,
PlotPaperUnits::Inches,
"the layout's unit is not ours to change"
);
// 1 mm = 100 units is 1 inch = 2540 units on an inch page setup; the
// standard code still names the choice, as the source application does.
assert_eq!(ps.scale_type, ScaledType::OneToHundred);
assert_eq!((ps.scale_numerator, ps.scale_denominator), (1.0, 2540.0));
assert!((ps.standard_scale_factor - 1.0 / 2540.0).abs() < 1e-15);
let _ = app.on_plot_dialog_open();
assert_eq!(app.plot_dialog.scale, "1:100");
// A layout plot keeps the paper space in millimetres: "1:1" is
// `1 in = 25.4 units`.
let _ = app.on_plot_dlg(PlotDlgMsg::Area("Layout".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert_eq!(ps.scale_type, ScaledType::OneToOne);
assert_eq!((ps.scale_numerator, ps.scale_denominator), (1.0, 25.4));
assert!((ps.standard_scale_factor - 1.0 / 25.4).abs() < 1e-15);
}
#[test]
fn a_named_setup_and_the_layout_settings_are_written_alike() {
let mut app = app_with_printer_named_sheet();
let _ = app.on_plot_dialog_open();
let _ = app.on_plot_dlg(PlotDlgMsg::Printer(crate::ui::window::plot::OUT_PDF.into()));
let _ = app.on_plot_dlg(PlotDlgMsg::Paper("ISO_A3_(297.00_x_420.00_MM)".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::Area("Extents".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::Flag(crate::ui::window::plot::PlotFlag::FitToPaper));
let _ = app.on_plot_dlg(PlotDlgMsg::Scale("1:50".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::Flag(crate::ui::window::plot::PlotFlag::UpsideDown));
let named = app.dialog_to_plotsettings();
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let layout = layout_settings(&app);
assert_eq!(layout.paper_size, named.paper_size);
assert_eq!(layout.printer_name, named.printer_name);
assert_eq!(layout.margins, named.margins);
assert_eq!(
(layout.paper_width, layout.paper_height),
(named.paper_width, named.paper_height)
);
assert_eq!(layout.rotation, named.rotation);
assert_eq!(layout.plot_type, named.plot_type);
assert_eq!((layout.origin_x, layout.origin_y), (named.origin_x, named.origin_y));
assert_eq!(layout.scale_type, named.scale_type);
assert_eq!(
(layout.scale_numerator, layout.scale_denominator),
(named.scale_numerator, named.scale_denominator)
);
assert_eq!(layout.standard_scale_factor, named.standard_scale_factor);
assert_eq!(layout.flags, named.flags);
assert_eq!(layout.shade_plot_mode, named.shade_plot_mode);
assert_eq!(layout.shade_plot_resolution, named.shade_plot_resolution);
assert_eq!(named.rotation, acadrust::objects::PlotRotation::Degrees270);
assert_eq!(named.scale_type, acadrust::objects::ScaledType::OneToFifty);
}
#[test]
fn flags_the_dialog_does_not_edit_survive_a_round_trip() {
let mut app = app_with_printer_named_sheet();
edit_layout_settings(&mut app, |ps| {
ps.flags.plot_viewport_borders = true;
ps.flags.update_paper = true;
ps.flags.zoom_to_paper_on_update = true;
ps.flags.unknown_bits = 0x8000;
ps.paper_image_origin_x = 3.5;
});
let _ = app.on_plot_dialog_open();
let _ = app.on_plot_dlg(PlotDlgMsg::Paper("ISO_A3_(297.00_x_420.00_MM)".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = layout_settings(&app);
assert!(ps.flags.plot_viewport_borders);
assert!(ps.flags.update_paper && ps.flags.zoom_to_paper_on_update);
assert_eq!(ps.flags.unknown_bits, 0x8000);
assert_eq!(ps.paper_image_origin_x, 3.5);
}
/// Open the metric page-setup fixture written by the commercial
/// application (see `tests/fixtures/plot/README.md`).
#[cfg(not(target_arch = "wasm32"))]
fn app_with_fixture() -> OpenCADStudio {
let mut app = OpenCADStudio::new_for_test();
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/plot/page-setups-metric.dxf"
);
let reply = app.automation_op(&format!(r#"{{"op":"open","path":"{path}"}}"#));
assert_eq!(reply["ok"], true, "{reply}");
app
}
/// The page-setup fields the file format stores, minus handles.
fn stored_fields(ps: &acadrust::objects::PlotSettings) -> String {
format!(
"{} | {} | {:?} | {:.6} {:.6} | {:.6} {:.6} {:.6} {:.6} | {:.6} {:.6} | {} {} \
| {:.6} / {:.6} | {:.9} | {:?} | {:?} | {:?} {:?} {}",
ps.printer_name,
ps.paper_size,
ps.paper_units,
ps.paper_width,
ps.paper_height,
ps.margins.left,
ps.margins.bottom,
ps.margins.right,
ps.margins.top,
ps.origin_x,
ps.origin_y,
ps.rotation.to_code(),
ps.plot_type.to_code(),
ps.scale_numerator,
ps.scale_denominator,
ps.standard_scale_factor,
ps.scale_type,
ps.flags,
ps.shade_plot_mode,
ps.shade_plot_resolution,
ps.shade_plot_dpi
)
}
/// Every layout of the fixture survives "open the dialog, apply" without
/// a single stored field changing — the dialog reads the source
/// application's conventions and writes them back the same way.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn fixture_page_setups_round_trip_through_the_dialog_unchanged() {
use acadrust::objects::{PlotRotation, ScaledType};
let mut app = app_with_fixture();
let a3_medium = (297.0106506347656, 419.9889831542968);
let arch_d_medium = (914.4000244140626, 609.5999755859375);
let expectations = [
("A4 1-100", PlotRotation::None, (297.0, 210.0), true),
("A3 - plotter", PlotRotation::Degrees90, a3_medium, false),
("ARCH D - PLOTTER", PlotRotation::None, arch_d_medium, true),
];
for (layout, rotation, medium, pdf) in expectations {
let orientation = "Landscape";
let _ = app.update(Message::LayoutSwitch(layout.into()));
let i = app.active_tab;
let before = app.tabs[i].scene.plot_settings_for(layout).unwrap();
assert_eq!(before.rotation, rotation, "{layout}");
assert_eq!((before.paper_width, before.paper_height), medium, "{layout}");
assert_eq!(before.scale_type, ScaledType::OneToOne, "{layout}");
let _ = app.on_plot_dialog_open();
let d = &app.plot_dialog;
assert_eq!(d.orientation, orientation, "{layout}");
assert!(!d.upside_down);
assert_eq!(d.area, "Layout");
assert_eq!(d.scale, "1:1", "{layout}: a 1:1 plot in either paper unit");
assert_eq!(d.to_file, pdf, "{layout}");
assert_eq!(super::plot_dialog_sheet_mm(d).0 > super::plot_dialog_sheet_mm(d).1, true);
assert!(d.lineweights && d.apply_plot_styles && d.paperspace_last, "{layout}");
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let after = app.tabs[i].scene.plot_settings_for(layout).unwrap();
assert_eq!(stored_fields(&after), stored_fields(&before), "{layout}");
}
// The system printer's sheet keeps its driver's margins and lands on
// the layout the way the source application places it: the medium's
// top margin on the left, its left margin at the bottom.
let _ = app.update(Message::LayoutSwitch("A3 - plotter".into()));
let ((x0, y0), (x1, y1)) = app.tabs[app.active_tab].scene.paper_limits().unwrap();
assert!((x0 + 20.02365112304687).abs() < 1e-9 && (y0 + 4.995333194732666).abs() < 1e-9);
assert!((x1 - 399.96533203125).abs() < 1e-6 && (y1 - 292.015317440033).abs() < 1e-6);
}
/// Picking a new sheet on the fixture's PDF layout writes our canonical
/// portrait medium with the orientation in the rotation and the PDF
/// driver's margins for that medium.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn fixture_pdf_layout_takes_a_new_sheet_in_canonical_form() {
use acadrust::objects::{PaperMargin, PlotRotation};
let mut app = app_with_fixture();
let _ = app.update(Message::LayoutSwitch("A4 1-100".into()));
let _ = app.on_plot_dialog_open();
let _ = app.on_plot_dlg(PlotDlgMsg::Paper("ISO_A3_(297.00_x_420.00_MM)".into()));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = app.tabs[app.active_tab].scene.plot_settings_for("A4 1-100").unwrap();
assert_eq!(ps.printer_name, "DWG To PDF.pc3");
assert_eq!(ps.paper_size, "ISO_A3_(297.00_x_420.00_MM)");
assert_eq!((ps.paper_width, ps.paper_height), (297.0, 420.0));
assert_eq!(ps.rotation, PlotRotation::Degrees90);
assert_eq!(ps.margins, PaperMargin::new(5.0, 17.0, 6.0, 18.0));
// The sheet sits at minus its displayed margins: top on the left,
// left at the bottom.
let ((x0, y0), _) = app.tabs[app.active_tab].scene.paper_limits().unwrap();
assert!((x0 + 18.0).abs() < 1e-9 && (y0 + 5.0).abs() < 1e-9, "{x0} {y0}");
}
#[test]
fn scale_names_parse_to_their_ratios() {
use crate::scene::Scene;
assert_eq!(Scene::parse_scale_name_ratio("1:250"), Some((1.0, 250.0)));
assert_eq!(Scene::parse_scale_name_ratio("2:1"), Some((2.0, 1.0)));
assert_eq!(Scene::parse_scale_name_ratio("1/8\" = 1'-0\""), Some((0.125, 12.0)));
assert_eq!(Scene::parse_scale_name_ratio("3/32\" = 1'-0\""), Some((0.09375, 12.0)));
assert_eq!(Scene::parse_scale_name_ratio("1'-0\" = 1'-0\""), Some((12.0, 12.0)));
assert_eq!(Scene::parse_scale_name_ratio("6\" = 1'-0\""), Some((6.0, 12.0)));
assert_eq!(Scene::parse_scale_name_ratio("Fit"), None);
assert_eq!(Scene::parse_scale_name_ratio("1:0"), None);
assert_eq!(super::ratio_scale_name(0.004), "1:250");
assert_eq!(super::ratio_scale_name(25.4), "25.4:1");
assert_eq!(super::ratio_scale_name(1.0 / 3.0), "1:3");
}
#[test]
@@ -5267,7 +5747,9 @@ mod plot_paper_tests {
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let (name, w, h) = layout_paper(&app);
assert_eq!(name, "A4", "the driver's own spelling must survive the dialog");
// …and so must the driver's landscape medium: unrotated, as stored.
assert_eq!((w, h), (297.0, 210.0));
assert_eq!(layout_rotation(&app), acadrust::objects::PlotRotation::None);
}
#[test]
@@ -5279,7 +5761,8 @@ mod plot_paper_tests {
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let (name, w, h) = layout_paper(&app);
assert_eq!(name, "ISO_A3_(297.00_x_420.00_MM)");
assert_eq!((w, h), (420.0, 297.0));
assert_eq!((w, h), (297.0, 420.0));
assert_eq!(layout_rotation(&app), acadrust::objects::PlotRotation::Degrees90);
// The next dialog remembers the sheet the user chose.
assert_eq!(app.plot_paper.canonical, "ISO_A3_(297.00_x_420.00_MM)");
}
@@ -5346,7 +5829,7 @@ mod plot_paper_tests {
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = app.tabs[i].scene.plot_settings_for("Layout1").unwrap();
assert_eq!(ps.margins, acadrust::objects::PaperMargin::new(5.0, 17.0, 6.0, 18.0));
assert_eq!((ps.paper_width, ps.paper_height), (420.0, 297.0));
assert_eq!((ps.paper_width, ps.paper_height), (297.0, 420.0));
}
#[test]
@@ -5394,7 +5877,8 @@ mod plot_paper_tests {
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
let ps = app.tabs[app.active_tab].scene.plot_settings_for("Layout1").unwrap();
assert_eq!(ps.paper_size, "Roll_24_(609.60_x_1500.00_MM)");
assert_eq!((ps.paper_width, ps.paper_height), (1500.0, 609.6));
assert_eq!((ps.paper_width, ps.paper_height), (609.6, 1500.0));
assert_eq!(ps.rotation, acadrust::objects::PlotRotation::Degrees90);
assert_eq!(ps.margins, acadrust::objects::PaperMargin::new(3.0, 17.0, 6.0, 4.0));
// Re-adding the same size replaces the definition instead of duplicating it.
let _ = app.on_plot_dlg(custom(C::Open));
@@ -5507,7 +5991,11 @@ cupsPrintQuality/Print Quality: *Normal High\n";
assert_eq!(app.plot_dialog.paper, "Roll_24_(609.60_x_1500.00_MM)");
assert_eq!(super::plot_dialog_sheet_mm(&app.plot_dialog), (1500.0, 609.6));
let _ = app.on_plot_dlg(PlotDlgMsg::SetCurrent);
assert_eq!(layout_paper(&app).0, "Roll_24_(609.60_x_1500.00_MM)");
let (name, w, h) = layout_paper(&app);
assert_eq!(name, "Roll_24_(609.60_x_1500.00_MM)");
// The drawing's own landscape medium stays as it was stored.
assert_eq!((w, h), (1500.0, 609.6));
assert_eq!(layout_rotation(&app), acadrust::objects::PlotRotation::None);
}
}
+1 -2
View File
@@ -1508,8 +1508,7 @@ impl OpenCADStudio {
Message::ClearScene => {
let i = self.active_tab;
self.push_undo_snapshot(i, "CLEAR");
self.tabs[i].scene.clear();
crate::io::linetypes::populate_document(&mut self.tabs[i].scene.document);
self.tabs[i].scene.reset_to_new_drawing();
self.tabs[i].properties = PropertiesPanel::empty();
let doc_layers = self.tabs[i].scene.document.layers.clone();
let vp_info = self.tabs[i].scene.viewport_list();
+4 -18
View File
@@ -3051,6 +3051,7 @@ impl OpenCADStudio {
vp_size,
self.show_constraint_values,
self.constraint_bar_display,
self.constraint_bar_mode,
cursor,
)?;
let set = self.tabs[i].scene.parametric_constraint_set(scope)?;
@@ -4577,6 +4578,7 @@ properties={:.1}ms picked={}",
canvas_sz,
self.show_constraint_values,
self.constraint_bar_display,
self.constraint_bar_mode,
p_full,
)
})
@@ -6031,24 +6033,7 @@ properties={:.1}ms picked={}",
if let acadrust::objects::ObjectType::Layout(l) = obj {
if l.name == new_name {
l.flags = layout_flags;
l.min_limits = (0.0, 0.0);
l.max_limits = (297.0, 210.0);
l.min_extents = (0.0, 0.0, 0.0);
l.max_extents = (297.0, 210.0, 0.0);
l.paper_width = 297.0;
l.paper_height = 210.0;
l.plot_paper_units = 1;
l.plot_scale_numerator = 1.0;
l.plot_scale_denominator = 1.0;
l.plot_scale_type = 16;
l.plot_scale_factor = 1.0;
l.plot_type = 5;
l.plot_flags.use_standard_scale = true;
l.plot_flags.print_lineweights = true;
l.plot_flags.plot_plot_styles = !plot_style.is_empty();
l.plot_flags.show_plot_styles = !plot_style.is_empty();
l.plot_style_sheet = plot_style;
l.paper_size = "ISO_A4_(297.00_x_210.00_MM)".into();
crate::scene::apply_default_page_setup(l, &plot_style);
break;
}
}
@@ -6683,6 +6668,7 @@ mod selection_preview_tests {
(800.0, 600.0),
true,
3,
4095,
)[0].1;
let point = (-30..=30).find_map(|y| {
(-30..=30).find_map(|x| {
+21 -1
View File
@@ -611,7 +611,8 @@ bg={bg_ms:.1}ms n={view_count}"
};
let control_polygon = tab.selected_handle.and_then(|handle| {
let spline = match tab.scene.document.get_entity(handle) {
Some(acadrust::EntityType::Spline(spline)) if spline.cv_frame_visible => spline,
Some(acadrust::EntityType::Spline(spline))
if crate::entities::spline::shows_control_vertices(spline) => spline,
_ => return None,
};
if tab
@@ -833,6 +834,23 @@ bg={bg_ms:.1}ms n={view_count}"
.active_cmd
.as_ref()
.is_some_and(|cmd| !cmd.needs_entity_pick() && !cmd.is_selection_gathering());
let constraint_cursor_badge = if is_paper {
None
} else {
tab.scene.hover_highlight.and_then(|handle| {
tab.scene
.parametric_constraint_set(tab.current_parametric_scope())
.and_then(|set| {
set.constraints_touching(handle)
.find(|constraint| {
constraint.kind
== crate::scene::parametric_constraints::ConstraintKind::Concentric
})
.or_else(|| set.constraints_touching(handle).next())
})
.map(|constraint| constraint.kind.glyph_symbol().to_string())
})
};
let constraint_glyphs: Vec<(
iced::Point,
[f32; 2],
@@ -850,6 +868,7 @@ bg={bg_ms:.1}ms n={view_count}"
sel_ref.vp_size,
self.show_constraint_values,
self.constraint_bar_display,
self.constraint_bar_mode,
)
.into_iter()
.map(|(id, point, direction, label, is_conflicting, hover_points)| {
@@ -910,6 +929,7 @@ bg={bg_ms:.1}ms n={view_count}"
constraint_glyphs,
self.constraint_glyph_tooltip
.map(|kind| crate::t!(kind.label()).into_owned()),
constraint_cursor_badge,
)
};
+27 -2
View File
@@ -1304,6 +1304,16 @@ pub struct CoincidentPick {
pub whole_curve: bool,
}
/// The two input forms accepted by the Horizontal geometric constraint.
/// Object picks are resolved while the entity snapshot is available; point
/// picks are resolved by the host against the live document so two points on
/// the same entity remain distinguishable.
#[derive(Clone, Copy, Debug)]
pub enum HorizontalConstraintSelection {
Reference(crate::scene::parametric_constraints::ParametricRef),
Points(CoincidentPick, CoincidentPick),
}
/// Construction options shared by SWEEP creation and its live preview.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SweepOptions {
@@ -1550,6 +1560,14 @@ pub enum CmdResult {
/// Undo-history label, e.g. `"Horizontal constraint"`.
label: &'static str,
},
/// Adds a Horizontal relation against the UCS X direction captured when
/// the command starts. The direction is persisted with the constraint so
/// later edits and save/reopen do not silently fall back to world X.
AddHorizontalConstraint {
selection: HorizontalConstraintSelection,
direction: acadrust::types::Vector3,
label: &'static str,
},
/// Adds an ordered perpendicular relation. The first picked direction and
/// the second direction's start point stay fixed during the initial solve;
/// those temporary anchors are not persisted as geometric constraints.
@@ -1568,6 +1586,13 @@ pub enum CmdResult {
second: crate::scene::parametric_constraints::ParametricRef,
label: &'static str,
},
/// Adds an ordered concentric relation. The first picked center remains
/// fixed during the initial solve while the second curve moves rigidly.
AddConcentricConstraint {
first: crate::scene::parametric_constraints::ParametricRef,
second: crate::scene::parametric_constraints::ParametricRef,
label: &'static str,
},
/// Opens the Auto Constrain settings dialog from the selection prompt.
OpenAutoConstrainSettings,
/// Adds an ordered Coincident relation. Point/point selections create a
@@ -2826,14 +2851,14 @@ mod constraint_registry_tests {
"CPCONSTRAINT",
"MPCONSTRAINT",
"OCCONSTRAINT",
"HCONSTRAINT",
"GCHORIZONTAL",
"VCONSTRAINT",
"PCONSTRAINT",
"QCONSTRAINT",
"GCPERPENDICULAR",
"ECONSTRAINT",
"TCONSTRAINT",
"NCONSTRAINT",
"GCCONCENTRIC",
"NRCONSTRAINT",
"LCONSTRAINT",
"FXCONSTRAINT",
+21 -3
View File
@@ -212,9 +212,9 @@ fn properties(arc: &Arc) -> Vec<PropSection> {
ro(t!("Total angle").as_ref(), "total_angle", format_angle(total_angle.to_radians())),
ro(t!("Arc length").as_ref(), "arc_length", format_length(arc_length)),
ro(t!("Area").as_ref(), "area", format_area(area)),
ro(t!("Normal X").as_ref(), "normal_x", format!("{:.4}", arc.normal.x)),
ro(t!("Normal Y").as_ref(), "normal_y", format!("{:.4}", arc.normal.y)),
ro(t!("Normal Z").as_ref(), "normal_z", format!("{:.4}", arc.normal.z)),
edit(t!("Normal X").as_ref(), "normal_x", arc.normal.x),
edit(t!("Normal Y").as_ref(), "normal_y", arc.normal.y),
edit(t!("Normal Z").as_ref(), "normal_z", arc.normal.z),
],
}]
}
@@ -244,6 +244,24 @@ fn apply_geom_prop(arc: &mut Arc, field: &str, value: &str) {
"radius" if v > 0.0 => arc.radius = v,
"start_angle" => arc.start_angle = v.to_radians(),
"end_angle" => arc.end_angle = v.to_radians(),
"normal_x" | "normal_y" | "normal_z" => {
let center = arc.center_wcs();
let mut normal = cadkernel::space::Vec3::new(arc.normal.x, arc.normal.y, arc.normal.z);
match field {
"normal_x" => normal.x = v,
"normal_y" => normal.y = v,
"normal_z" => normal.z = v,
_ => {}
}
if let Some(normal) = normal.normalize() {
arc.normal = acadrust::types::Vector3::new(normal.x, normal.y, normal.z);
let (x, y, z) = crate::scene::view::transform::wcs_point_to_ocs(
(center.x, center.y, center.z),
(normal.x, normal.y, normal.z),
);
arc.center = acadrust::types::Vector3::new(x, y, z);
}
}
_ => {}
}
}
+39 -4
View File
@@ -3,7 +3,7 @@ use crate::t;
use crate::command::EntityTransform;
use crate::entities::common::{
center_grip, edit_prop as edit, parse_f64, ro_prop as ro, square_grip,
center_grip, edit_prop as edit, parse_f64, square_grip,
};
use crate::entities::traits::RenderConvertible;
use crate::scene::convert::acad_to_render::{extrusion_wall_tris, RenderEntity, RenderObject};
@@ -169,9 +169,9 @@ fn properties(circle: &Circle) -> Vec<PropSection> {
edit(t!("Diameter").as_ref(), "diameter", r * 2.0),
edit(t!("Circumference").as_ref(), "circumference", 2.0 * PI * r),
edit(t!("Area").as_ref(), "area", PI * r * r),
ro(t!("Normal X").as_ref(), "normal_x", format!("{:.4}", circle.normal.x)),
ro(t!("Normal Y").as_ref(), "normal_y", format!("{:.4}", circle.normal.y)),
ro(t!("Normal Z").as_ref(), "normal_z", format!("{:.4}", circle.normal.z)),
edit(t!("Normal X").as_ref(), "normal_x", circle.normal.x),
edit(t!("Normal Y").as_ref(), "normal_y", circle.normal.y),
edit(t!("Normal Z").as_ref(), "normal_z", circle.normal.z),
],
}]
}
@@ -202,6 +202,28 @@ fn apply_geom_prop(circle: &mut Circle, field: &str, value: &str) {
"diameter" if v > 0.0 => circle.radius = v / 2.0,
"circumference" if v > 0.0 => circle.radius = v / (2.0 * PI),
"area" if v > 0.0 => circle.radius = (v / PI).sqrt(),
"normal_x" | "normal_y" | "normal_z" => {
let center = circle.center_wcs();
let mut normal = cadkernel::space::Vec3::new(
circle.normal.x,
circle.normal.y,
circle.normal.z,
);
match field {
"normal_x" => normal.x = v,
"normal_y" => normal.y = v,
"normal_z" => normal.z = v,
_ => {}
}
if let Some(normal) = normal.normalize() {
circle.normal = acadrust::types::Vector3::new(normal.x, normal.y, normal.z);
let (x, y, z) = crate::scene::view::transform::wcs_point_to_ocs(
(center.x, center.y, center.z),
(normal.x, normal.y, normal.z),
);
circle.center = acadrust::types::Vector3::new(x, y, z);
}
}
_ => {}
}
}
@@ -358,6 +380,19 @@ impl crate::entities::traits::MassPropsCalc for Circle {
mod tests {
use super::*;
#[test]
fn editing_normal_preserves_world_center() {
let mut circle = Circle::from_coords(2.0, 3.0, 4.0, 5.0);
let center = circle.center_wcs();
apply_geom_prop(&mut circle, "normal_x", "1");
assert!((circle.center_wcs() - center).length() < 1.0e-9);
let normal_length =
(circle.normal.x.powi(2) + circle.normal.y.powi(2) + circle.normal.z.powi(2)).sqrt();
assert!((normal_length - 1.0).abs() < 1.0e-12);
}
#[test]
fn quadrant_grips_offer_interactive_radius() {
use crate::entities::traits::Grippable;
+596 -120
View File
File diff suppressed because it is too large. Load diff
+36 -3
View File
@@ -187,9 +187,9 @@ fn properties(ell: &Ellipse) -> Vec<PropSection> {
ro(t!("Start parameter").as_ref(), "start_param", format!("{:.4}", ell.start_parameter)),
ro(t!("End parameter").as_ref(), "end_param", format!("{:.4}", ell.end_parameter)),
ro(t!("Length").as_ref(), "length", format_length(props.perimeter)),
ro(t!("Normal X").as_ref(), "normal_x", format!("{:.4}", ell.normal.x)),
ro(t!("Normal Y").as_ref(), "normal_y", format!("{:.4}", ell.normal.y)),
ro(t!("Normal Z").as_ref(), "normal_z", format!("{:.4}", ell.normal.z)),
edit(t!("Normal X").as_ref(), "normal_x", ell.normal.x),
edit(t!("Normal Y").as_ref(), "normal_y", ell.normal.y),
edit(t!("Normal Z").as_ref(), "normal_z", ell.normal.z),
],
}]
}
@@ -220,6 +220,26 @@ fn apply_geom_prop(ell: &mut Ellipse, field: &str, value: &str) {
"ratio" if v > 0.0 => ell.minor_axis_ratio = v,
"start_angle" => ell.start_parameter = v.to_radians(),
"end_angle" => ell.end_parameter = v.to_radians(),
"normal_x" | "normal_y" | "normal_z" => {
let mut normal = [ell.normal.x, ell.normal.y, ell.normal.z];
match field {
"normal_x" => normal[0] = v,
"normal_y" => normal[1] = v,
"normal_z" => normal[2] = v,
_ => {}
}
let Some(normal) = cadkernel::space::Vec3::from(normal).normalize() else {
return;
};
let Some(major) = cadkernel::space::reorient_axis_to_plane(
[ell.major_axis.x, ell.major_axis.y, ell.major_axis.z],
normal.to_array(),
) else {
return;
};
ell.normal = acadrust::types::Vector3::new(normal.x, normal.y, normal.z);
ell.major_axis = acadrust::types::Vector3::new(major[0], major[1], major[2]);
}
_ => {}
}
}
@@ -424,6 +444,19 @@ mod grip_tests {
(v.major_axis.x * v.major_axis.x + v.major_axis.y * v.major_axis.y).sqrt()
}
#[test]
fn editing_normal_reorients_major_axis_in_kernel() {
let mut e = ell(10.0, 0.5);
apply_geom_prop(&mut e, "normal_x", "1");
let normal = DVec3::new(e.normal.x, e.normal.y, e.normal.z);
let major = DVec3::new(e.major_axis.x, e.major_axis.y, e.major_axis.z);
assert!((normal.length() - 1.0).abs() < 1.0e-12);
assert!((major.length() - 10.0).abs() < 1.0e-9);
assert!(normal.dot(major).abs() < 1.0e-9);
}
#[test]
fn minor_grip_below_major_updates_ratio_only() {
let mut e = ell(10.0, 0.5);
+159 -19
View File
@@ -18,7 +18,13 @@ pub(crate) fn uses_fit_method(spline: &Spline) -> bool {
}
pub(crate) fn shows_fit_points(spline: &Spline) -> bool {
uses_fit_method(spline) && (!spline.cv_frame_visible || spline.flags.periodic)
!spline.fit_points.is_empty() && (!spline.cv_frame_visible || spline.flags.periodic)
}
pub(crate) fn shows_control_vertices(spline: &Spline) -> bool {
!shows_fit_points(spline)
&& !(uses_fit_method(spline) && spline.flags.periodic)
&& control_vertices(spline).len() >= 2
}
pub(crate) fn fit_nurbs3(spline: &Spline) -> Option<NurbsCurve3> {
@@ -105,12 +111,21 @@ pub(crate) fn spline_knot_points(spline: &Spline) -> Vec<glam::DVec3> {
}
pub(crate) fn replace_with_nurbs(spline: &mut Spline, curve: &NurbsCurve3) {
let mut fit_points = spline.fit_points.clone();
spline.degree = curve.degree() as i32;
spline.knots = curve.knots().to_vec();
spline.control_points = curve.control_points().iter()
.map(|point| acadrust::types::Vector3::new(point[0], point[1], point[2])).collect();
spline.weights = curve.weights().to_vec();
spline.fit_points.clear();
if !fit_points.is_empty() {
if let (Some(first), Some(point)) = (fit_points.first_mut(), spline.control_points.first()) {
*first = *point;
}
if let (Some(last), Some(point)) = (fit_points.last_mut(), spline.control_points.last()) {
*last = *point;
}
}
spline.fit_points = fit_points;
spline.begin_tangent = acadrust::types::Vector3::ZERO;
spline.end_tangent = acadrust::types::Vector3::ZERO;
spline.flags.rational = spline.weights.windows(2)
@@ -615,7 +630,15 @@ fn index_prop(label: &str, field: &'static str, index: usize, count: usize) -> P
fn convert_to_control_method(spline: &mut Spline) -> bool {
if !uses_fit_method(spline) {
return true;
let valid = spline.control_points.len() >= 2;
if valid {
spline.fit_points.clear();
spline.begin_tangent = acadrust::types::Vector3::ZERO;
spline.end_tangent = acadrust::types::Vector3::ZERO;
spline.dwg_flags1 &= !1;
spline.dxf_flags &= !(32 | 1024);
}
return valid;
}
let Some(planar) = crate::entities::curve::spline_curve(spline) else {
return false;
@@ -647,18 +670,74 @@ fn convert_to_control_method(spline: &mut Spline) -> bool {
}
fn convert_to_fit_method(spline: &mut Spline) -> bool {
uses_fit_method(spline)
if uses_fit_method(spline) {
return true;
}
if spline.fit_points.len() < 2 {
return false;
}
spline.control_points.clear();
spline.knots.clear();
spline.weights.clear();
spline.flags.rational = false;
spline.dwg_flags1 |= 1;
spline.dxf_flags |= 32 | 1024;
true
}
fn derived_fit_points(spline: &Spline) -> Vec<acadrust::types::Vector3> {
if spline.flags.closed || spline.flags.periodic {
return Vec::new();
}
let Some(curve) = nurbs3(spline) else {
return Vec::new();
};
let (start, end) = curve.domain();
if !(start.is_finite() && end.is_finite() && end > start) {
return Vec::new();
}
let tolerance = (end - start).abs().max(1.0) * 1.0e-12;
let mut parameters = vec![start];
for knot in curve.knots().iter().copied() {
if knot > start + tolerance
&& knot < end - tolerance
&& parameters
.last()
.is_none_or(|previous| (knot - *previous).abs() > tolerance)
{
parameters.push(knot);
}
}
parameters.push(end);
parameters
.into_iter()
.map(|parameter| {
let point = curve.point_at_knot(parameter);
acadrust::types::Vector3::new(point[0], point[1], point[2])
})
.collect()
}
fn can_show_fit_points(spline: &Spline) -> bool {
spline.fit_points.len() >= 2 || derived_fit_points(spline).len() >= 2
}
fn prepare_fit_point_view(spline: &mut Spline) -> bool {
if spline.fit_points.len() < 2 {
spline.fit_points = derived_fit_points(spline);
}
spline.fit_points.len() >= 2
}
fn grips(spline: &Spline) -> Vec<GripDef> {
let fit_method = uses_fit_method(spline);
let derived_control = control_vertices(spline);
let show_control_vertices = (spline.cv_frame_visible || !fit_method)
&& !(fit_method && spline.flags.periodic)
let show_fit = shows_fit_points(spline);
let show_control_vertices = !show_fit
&& !(uses_fit_method(spline) && spline.flags.periodic)
&& derived_control.len() >= 2;
let source = if show_control_vertices {
derived_control
} else if fit_method {
} else if show_fit {
spline.fit_points.clone()
} else {
spline.control_points.clone()
@@ -885,7 +964,7 @@ fn apply_geom_prop(spline: &mut Spline, field: &str, value: &str) {
match field {
"spline_method" => {
if value == "Fit" {
if convert_to_fit_method(spline) {
if prepare_fit_point_view(spline) {
spline.cv_frame_visible = false;
}
} else if value == "Control Vertices" {
@@ -896,6 +975,12 @@ fn apply_geom_prop(spline: &mut Spline, field: &str, value: &str) {
return;
}
"knot_param" => {
if shows_fit_points(spline)
&& !uses_fit_method(spline)
&& !convert_to_fit_method(spline)
{
return;
}
spline.knot_parameterization = match value {
"Chord" => 0,
"Square Root" => 1,
@@ -930,9 +1015,30 @@ fn apply_geom_prop(spline: &mut Spline, field: &str, value: &str) {
{
return;
}
if matches!(field, "ctrl_pt_x" | "ctrl_pt_y" | "ctrl_pt_z" | "weight")
&& uses_fit_method(spline)
&& !convert_to_control_method(spline)
if matches!(field, "ctrl_pt_x" | "ctrl_pt_y" | "ctrl_pt_z" | "weight") {
if !shows_fit_points(spline) && !spline.fit_points.is_empty() {
if !convert_to_control_method(spline) {
return;
}
} else if uses_fit_method(spline) && !convert_to_control_method(spline) {
return;
}
}
if shows_fit_points(spline)
&& !uses_fit_method(spline)
&& matches!(
field,
"fit_pt_x"
| "fit_pt_y"
| "fit_pt_z"
| "start_tan_x"
| "start_tan_y"
| "start_tan_z"
| "end_tan_x"
| "end_tan_y"
| "end_tan_z"
)
&& !convert_to_fit_method(spline)
{
return;
}
@@ -1015,16 +1121,23 @@ fn apply_grip(spline: &mut Spline, grip_id: usize, apply: GripApply) {
return;
}
// First CV edit makes the displayed kernel controls authoritative.
let fit_method = uses_fit_method(spline);
if spline.cv_frame_visible && fit_method && !spline.flags.periodic {
let editing_fit = shows_fit_points(spline);
if editing_fit && !uses_fit_method(spline) {
if !convert_to_fit_method(spline) {
return;
}
} else if !editing_fit
&& (uses_fit_method(spline) || !spline.fit_points.is_empty())
&& !spline.flags.periodic
{
if !convert_to_control_method(spline) {
return;
}
}
let target = if (spline.cv_frame_visible && !spline.flags.periodic) || !fit_method {
spline.control_points.get_mut(grip_id)
} else {
let target = if editing_fit {
spline.fit_points.get_mut(grip_id)
} else {
spline.control_points.get_mut(grip_id)
};
if let Some(cp) = target {
match apply {
@@ -1088,9 +1201,10 @@ impl crate::entities::traits::Grippable for Spline {
let fit_method = uses_fit_method(self);
let can_show_control = control_vertices(self).len() >= 2
&& !(fit_method && self.flags.periodic);
let can_show_fit = can_show_fit_points(self);
return if !shows_fit_points(self) {
vec![
(can_show_control && fit_method).then_some(GripMenuItem {
can_show_fit.then_some(GripMenuItem {
label: "Fit",
action: GripMenuAction::ShowFit,
}),
@@ -1131,7 +1245,7 @@ impl crate::entities::traits::Grippable for Spline {
use crate::scene::model::object::GripMenuAction as A;
match action {
A::ShowFit => {
if convert_to_fit_method(self) {
if prepare_fit_point_view(self) {
self.cv_frame_visible = false;
return;
}
@@ -1276,4 +1390,30 @@ mod tests {
acadrust::types::Vector3::new(0.0, 2.5, 0.0)
);
}
#[test]
fn showing_derived_fit_points_does_not_change_the_curve() {
let mut spline = Spline::default();
spline.degree = 3;
spline.control_points = vec![
acadrust::types::Vector3::new(0.0, 0.0, 0.0),
acadrust::types::Vector3::new(1.0, 3.0, 0.0),
acadrust::types::Vector3::new(4.0, 3.0, 0.0),
acadrust::types::Vector3::new(5.0, 0.0, 0.0),
];
spline.knots = cadkernel::space::clamped_uniform_knots(3, 4);
let before = nurbs3(&spline).unwrap().point_at(0.37);
assert!(prepare_fit_point_view(&mut spline));
spline.cv_frame_visible = false;
assert!(shows_fit_points(&spline));
assert!(!uses_fit_method(&spline));
let after = nurbs3(&spline).unwrap().point_at(0.37);
assert!(
cadkernel::space::Vec3::from(before)
.distance(cadkernel::space::Vec3::from(after))
< 1.0e-12
);
}
}
+2 -2
View File
@@ -197,7 +197,7 @@ pub fn text_local_bounds(
/// Expand DXF `%%x` special-character sequences that appear in both TEXT and MTEXT values:
/// - `%%d` / `%%D` → `°`
/// - `%%p` / `%%P` → `±`
/// - `%%c` / `%%C` → `⌀`
/// - `%%c` / `%%C` → `∅` (U+2205, the native diameter sign)
/// - `%%u` / `%%U` → underline toggle (stripped — not renderable with stroke fonts)
/// - `%%o` / `%%O` → overline toggle (stripped)
/// - `%%%%` → `%`
@@ -224,7 +224,7 @@ pub fn resolve_dxf_special_chars(s: &str) -> String {
}
Some('c') => {
chars.next();
out.push('⌀');
out.push('∅');
}
Some('u') | Some('o') => {
chars.next();
+15
View File
@@ -68,6 +68,21 @@ impl SelectObjectsCommand {
}
}
/// Standard selection behavior routed to a private apply command while
/// retaining the public command name in the visible prompt.
pub fn routed(prompt_cmd: &str, pending_cmd: &str) -> Self {
Self {
prompt_cmd: prompt_cmd.to_string(),
pending_cmd: pending_cmd.to_string(),
handles: Vec::new(),
commit_on_enter: true,
show_options: true,
pick: None,
pick_crossing: true,
auto_constrain_settings: false,
}
}
/// Single-object variant: the first completed selection action applies
/// immediately, with no Enter (used by commands that act on one object).
pub fn instant(pending_cmd: &str) -> Self {
+185
View File
@@ -0,0 +1,185 @@
use acadrust::{EntityType, Handle};
use glam::DVec3;
use crate::command::{CadCommand, CmdResult};
use crate::scene::parametric_constraints::ParametricRef;
use crate::t;
pub struct ConcentricConstraintCommand {
first: Option<ParametricRef>,
picked_entity: Option<EntityType>,
}
impl ConcentricConstraintCommand {
pub fn new() -> Self {
Self {
first: None,
picked_entity: None,
}
}
pub fn with_first(first: ParametricRef) -> Self {
Self {
first: Some(first),
picked_entity: None,
}
}
fn invalid_selection() -> CmdResult {
CmdResult::ReportError(
t!("Invalid selection for Concentric. Select a circle, arc, ellipse or polyline arc segment.")
.into_owned(),
)
}
fn polyline_segment_is_arc(entity: &EntityType, index: usize) -> bool {
match entity {
EntityType::LwPolyline(polyline) => polyline
.vertices
.get(index)
.is_some_and(|vertex| vertex.bulge.abs() > 1.0e-12),
EntityType::Polyline2D(polyline) => polyline
.vertices
.get(index)
.is_some_and(|vertex| vertex.bulge.abs() > 1.0e-12),
_ => false,
}
}
fn picked_reference(entity: &EntityType, handle: Handle, point: DVec3) -> Option<ParametricRef> {
match entity {
EntityType::Circle(_) | EntityType::Arc(_) | EntityType::Ellipse(_) => {
Some(ParametricRef::center(handle))
}
EntityType::LwPolyline(_) | EntityType::Polyline2D(_) => {
let planar = crate::entities::curve::entity_curve(entity)?;
let local = planar.plane.project(point.to_array())?;
let segments = planar.curve.segments();
let (index, _) = cadkernel::geom2d::nearest_of(segments.iter(), local)?;
matches!(segments.get(index), Some(cadkernel::geom2d::Curve::Arc(_)))
.then(|| ParametricRef::segment_center(handle, index))
}
_ => None,
}
}
pub fn preselected_reference(entity: &EntityType, handle: Handle) -> Option<ParametricRef> {
match entity {
EntityType::Circle(_) | EntityType::Arc(_) | EntityType::Ellipse(_) => {
Some(ParametricRef::center(handle))
}
EntityType::LwPolyline(polyline) => {
let segment_count = if polyline.is_closed {
polyline.vertices.len()
} else {
polyline.vertices.len().saturating_sub(1)
};
(segment_count == 1 && Self::polyline_segment_is_arc(entity, 0))
.then(|| ParametricRef::segment_center(handle, 0))
}
EntityType::Polyline2D(polyline) => {
let segment_count = if polyline.is_closed() {
polyline.vertices.len()
} else {
polyline.vertices.len().saturating_sub(1)
};
(segment_count == 1 && Self::polyline_segment_is_arc(entity, 0))
.then(|| ParametricRef::segment_center(handle, 0))
}
_ => None,
}
}
}
impl CadCommand for ConcentricConstraintCommand {
fn name(&self) -> &'static str {
"GCCONCENTRIC"
}
fn prompt(&self) -> String {
if self.first.is_some() {
t!("GCCONCENTRIC Select second object:").into_owned()
} else {
t!("GCCONCENTRIC Select first object:").into_owned()
}
}
fn needs_entity_pick(&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 on_entity_pick(&mut self, handle: Handle, point: DVec3) -> CmdResult {
if handle.is_null() {
return CmdResult::NeedPoint;
}
let Some(entity) = self.picked_entity.take() else {
return CmdResult::NeedPoint;
};
let Some(reference) = Self::picked_reference(&entity, handle, point) else {
return Self::invalid_selection();
};
let Some(first) = self.first else {
self.first = Some(reference);
return CmdResult::NeedPoint;
};
if first == reference {
return Self::invalid_selection();
}
CmdResult::AddConcentricConstraint {
first,
second: reference,
label: "Concentric constraint",
}
}
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
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn polyline_pick_keeps_the_selected_arc_center() {
let handle = Handle::new(13);
let mut polyline = acadrust::entities::LwPolyline::new();
polyline.vertices = vec![
acadrust::entities::LwVertex::from_coords(0.0, 0.0),
acadrust::entities::LwVertex::with_bulge(
acadrust::types::Vector2::new(5.0, 0.0),
1.0,
),
acadrust::entities::LwVertex::from_coords(10.0, 0.0),
];
let reference = ConcentricConstraintCommand::picked_reference(
&EntityType::LwPolyline(polyline),
handle,
DVec3::new(8.0, 2.0, 0.0),
)
.expect("arc segment");
assert_eq!(reference, ParametricRef::segment_center(handle, 1));
}
}
+102
View File
@@ -0,0 +1,102 @@
use acadrust::Handle;
use glam::DVec3;
use crate::command::{CadCommand, CmdOption, CmdResult};
pub struct ConstraintBarOptionCommand {
handles: Vec<Handle>,
}
impl ConstraintBarOptionCommand {
pub fn new(handles: Vec<Handle>) -> Self {
Self { handles }
}
fn finish(&mut self, command: &str) -> CmdResult {
CmdResult::Relaunch(command.to_string(), std::mem::take(&mut self.handles))
}
}
impl CadCommand for ConstraintBarOptionCommand {
fn name(&self) -> &'static str {
"CONSTRAINTBAR"
}
fn prompt(&self) -> String {
"CONSTRAINTBAR Enter an option [Show/Hide/Reset] <Show>:".to_string()
}
fn options(&self) -> Vec<CmdOption> {
vec![
CmdOption::new("Show", "S"),
CmdOption::new("Hide", "H"),
CmdOption::new("Reset", "R"),
]
}
fn wants_text_input(&self) -> bool {
true
}
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let keyword = text.trim().trim_start_matches('_').to_ascii_uppercase();
match keyword.as_str() {
"S" | "SHOW" => Some(self.finish("GCSHOW")),
"H" | "HIDE" => Some(self.finish("GCHIDE")),
"R" | "RESET" => Some(self.finish("CONSTRAINTBAR_RESET")),
_ => None,
}
}
fn on_point(&mut self, _point: DVec3) -> CmdResult {
CmdResult::NeedPoint
}
fn on_enter(&mut self) -> CmdResult {
self.finish("GCSHOW")
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}
inventory::submit!(crate::command::CommandRegistration {
names: &["CONSTRAINTBAR"]
});
#[cfg(test)]
mod tests {
use super::*;
fn relaunch(result: CmdResult) -> (String, Vec<Handle>) {
let CmdResult::Relaunch(command, handles) = result else {
panic!("expected relaunch");
};
(command, handles)
}
#[test]
fn enter_defaults_to_show_and_keeps_the_selection() {
let handles = vec![Handle::new(2), Handle::new(5)];
let mut command = ConstraintBarOptionCommand::new(handles.clone());
assert_eq!(relaunch(command.on_enter()), ("GCSHOW".to_string(), handles));
}
#[test]
fn hide_and_reset_route_to_their_apply_commands() {
let handle = Handle::new(7);
let mut hide = ConstraintBarOptionCommand::new(vec![handle]);
assert_eq!(
relaunch(hide.on_text_input("hide").unwrap()),
("GCHIDE".to_string(), vec![handle])
);
let mut reset = ConstraintBarOptionCommand::new(vec![handle]);
assert_eq!(
relaunch(reset.on_text_input("r").unwrap()),
("CONSTRAINTBAR_RESET".to_string(), vec![handle])
);
}
}
+3 -3
View File
@@ -14,14 +14,14 @@ impl GeomConstraintCommand {
fn dispatch(keyword: &str) -> Option<&'static str> {
Some(match keyword {
"H" | "HORIZONTAL" => "HCONSTRAINT",
"H" | "HORIZONTAL" => "GCHORIZONTAL",
"V" | "VERTICAL" => "VCONSTRAINT",
"P" | "PERPENDICULAR" => "GCPERPENDICULAR",
"PA" | "PARALLEL" => "PCONSTRAINT",
"T" | "TANGENT" => "TCONSTRAINT",
"SM" | "SMOOTH" => "SMOOTHCONSTRAINT",
"SM" | "SMOOTH" => "GCSMOOTH",
"C" | "COINCIDENT" => "GCCOINCIDENT",
"CON" | "CONCENTRIC" => "NCONSTRAINT",
"CON" | "CONCENTRIC" => "GCCONCENTRIC",
"COL" | "COLLINEAR" | "COLINEAR" => "LCONSTRAINT",
"SY" | "SYMMETRIC" => "SYCONSTRAINT",
"E" | "EQUAL" => "ECONSTRAINT",
+343
View File
@@ -0,0 +1,343 @@
use acadrust::{EntityType, Handle};
use glam::DVec3;
use crate::command::{
CadCommand, CmdOption, CmdResult, CoincidentPick, HorizontalConstraintSelection, WorkingPlane,
};
use crate::scene::parametric_constraints::{
directional_axis_endpoints, is_parametric_point_near, ParametricRef,
};
#[derive(Clone, Copy)]
enum Step {
ObjectOrTwoPoints,
FirstPoint,
SecondPoint(CoincidentPick),
}
/// Interactive front end for the Horizontal geometric constraint.
pub struct HorizontalConstraintCommand {
step: Step,
picked_entity: Option<EntityType>,
plane: WorkingPlane,
}
impl HorizontalConstraintCommand {
pub fn new() -> Self {
Self {
step: Step::ObjectOrTwoPoints,
picked_entity: None,
plane: WorkingPlane::default(),
}
}
fn point_pick(handle: Option<Handle>, point: DVec3) -> CoincidentPick {
CoincidentPick {
handle,
point,
whole_curve: false,
}
}
fn direction(&self) -> acadrust::types::Vector3 {
let direction = self.plane.x.normalize_or(DVec3::X);
acadrust::types::Vector3::new(direction.x, direction.y, direction.z)
}
fn invalid_object() -> CmdResult {
CmdResult::ReportError(
"Horizontal: select a line, straight polyline segment, text, MText, or an ellipse axis."
.to_string(),
)
}
fn invalid_point() -> CmdResult {
CmdResult::ReportError(
"Horizontal: select an endpoint, center, midpoint, or polyline vertex.".to_string(),
)
}
fn segment_is_straight(entity: &EntityType, index: usize) -> bool {
match entity {
EntityType::LwPolyline(polyline) => polyline
.vertices
.get(index)
.is_some_and(|vertex| vertex.bulge.abs() <= 1.0e-12),
EntityType::Polyline2D(polyline) => polyline
.vertices
.get(index)
.is_some_and(|vertex| vertex.bulge.abs() <= 1.0e-12),
_ => false,
}
}
fn distance_to_axis(point: DVec3, endpoints: [acadrust::types::Vector3; 2]) -> f64 {
cadkernel::space::Vec3::from(point.to_array())
.distance_to_line(
cadkernel::space::Vec3::new(endpoints[0].x, endpoints[0].y, endpoints[0].z),
cadkernel::space::Vec3::new(endpoints[1].x, endpoints[1].y, endpoints[1].z),
)
.unwrap_or(f64::INFINITY)
}
fn ellipse_reference(
entity: &EntityType,
handle: Handle,
point: DVec3,
) -> Option<ParametricRef> {
let major = ParametricRef::ellipse_major_axis(handle);
let minor = ParametricRef::ellipse_minor_axis(handle);
let major_distance =
Self::distance_to_axis(point, directional_axis_endpoints(entity, major)?);
let minor_distance =
Self::distance_to_axis(point, directional_axis_endpoints(entity, minor)?);
Some(if minor_distance < major_distance {
minor
} else {
major
})
}
fn picked_reference(
entity: &EntityType,
handle: Handle,
point: DVec3,
) -> Option<ParametricRef> {
match entity {
EntityType::Line(_) | EntityType::Ray(_) | EntityType::XLine(_) => {
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()?;
Self::segment_is_straight(entity, index)
.then_some(ParametricRef::segment(handle, index))
}
EntityType::Text(_) | EntityType::MText(_) => {
Some(ParametricRef::text_baseline(handle))
}
EntityType::Ellipse(_) => Self::ellipse_reference(entity, handle, point),
_ => None,
}
}
pub fn preselected_reference(entity: &EntityType, handle: Handle) -> Option<ParametricRef> {
match entity {
EntityType::Line(_) | EntityType::Ray(_) | EntityType::XLine(_) => {
Some(ParametricRef::whole(handle))
}
EntityType::Text(_) | EntityType::MText(_) => {
Some(ParametricRef::text_baseline(handle))
}
EntityType::Ellipse(_) => Some(ParametricRef::ellipse_major_axis(handle)),
EntityType::LwPolyline(polyline) => {
let count = if polyline.is_closed {
polyline.vertices.len()
} else {
polyline.vertices.len().saturating_sub(1)
};
(count == 1 && Self::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 && Self::segment_is_straight(entity, 0))
.then_some(ParametricRef::segment(handle, 0))
}
_ => None,
}
}
fn finish_points(&self, first: CoincidentPick, second: CoincidentPick) -> CmdResult {
CmdResult::AddHorizontalConstraint {
selection: HorizontalConstraintSelection::Points(first, second),
direction: self.direction(),
label: "Horizontal constraint",
}
}
}
impl CadCommand for HorizontalConstraintCommand {
fn name(&self) -> &'static str {
"GCHORIZONTAL"
}
fn prompt(&self) -> String {
match self.step {
Step::ObjectOrTwoPoints => {
"GCHORIZONTAL Select an object or [2Points] <2Points>:".to_string()
}
Step::FirstPoint => "GCHORIZONTAL Select first point:".to_string(),
Step::SecondPoint(_) => "GCHORIZONTAL Select second point:".to_string(),
}
}
fn options(&self) -> Vec<CmdOption> {
matches!(self.step, Step::ObjectOrTwoPoints)
.then(|| vec![CmdOption::new("2Points", "2P")])
.unwrap_or_default()
}
fn wants_text_input(&self) -> bool {
true
}
fn point_step_accepts_keywords(&self) -> bool {
matches!(self.step, Step::ObjectOrTwoPoints)
}
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::ObjectOrTwoPoints)
&& matches!(keyword.as_str(), "2" | "2P" | "2POINT" | "2POINTS")
{
self.step = Step::FirstPoint;
Some(CmdResult::NeedPoint)
} else {
None
}
}
fn set_working_plane(&mut self, plane: WorkingPlane) {
self.plane = plane;
}
fn needs_entity_pick(&self) -> bool {
true
}
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 on_entity_pick(&mut self, handle: Handle, point: DVec3) -> CmdResult {
if handle.is_null() {
return self.on_point(point);
}
let Some(entity) = self.picked_entity.take() else {
return CmdResult::NeedPoint;
};
match self.step {
Step::ObjectOrTwoPoints => {
let Some(reference) = Self::picked_reference(&entity, handle, point) else {
return Self::invalid_object();
};
CmdResult::AddHorizontalConstraint {
selection: HorizontalConstraintSelection::Reference(reference),
direction: self.direction(),
label: "Horizontal constraint",
}
}
Step::FirstPoint | Step::SecondPoint(_) => {
let world = acadrust::types::Vector3::new(point.x, point.y, point.z);
if !is_parametric_point_near(&entity, world) {
return Self::invalid_point();
}
let pick = Self::point_pick(Some(handle), point);
match self.step {
Step::FirstPoint => {
self.step = Step::SecondPoint(pick);
CmdResult::NeedPoint
}
Step::SecondPoint(first) => self.finish_points(first, pick),
Step::ObjectOrTwoPoints => unreachable!(),
}
}
}
}
fn on_point(&mut self, point: DVec3) -> CmdResult {
let pick = Self::point_pick(None, point);
match self.step {
Step::ObjectOrTwoPoints | Step::FirstPoint => {
self.step = Step::SecondPoint(pick);
CmdResult::NeedPoint
}
Step::SecondPoint(first) => self.finish_points(first, pick),
}
}
fn on_enter(&mut self) -> CmdResult {
if matches!(self.step, Step::ObjectOrTwoPoints) {
self.step = Step::FirstPoint;
CmdResult::NeedPoint
} else {
CmdResult::Cancel
}
}
fn on_escape(&mut self) -> CmdResult {
CmdResult::Cancel
}
}
#[cfg(test)]
mod tests {
use super::*;
use acadrust::entities::Line;
use acadrust::types::Vector3;
#[test]
fn object_pick_captures_the_working_x_direction() {
let handle = Handle::new(7);
let mut command = HorizontalConstraintCommand::new();
command.set_working_plane(WorkingPlane::new(DVec3::ZERO, DVec3::Y, DVec3::NEG_X));
command.inject_picked_entity(EntityType::Line(Line::from_points(
Vector3::ZERO,
Vector3::new(2.0, 3.0, 0.0),
)));
let CmdResult::AddHorizontalConstraint {
selection: HorizontalConstraintSelection::Reference(reference),
direction,
..
} = command.on_entity_pick(handle, DVec3::ZERO)
else {
panic!("object pick must create the constraint");
};
assert_eq!(reference, ParametricRef::whole(handle));
assert!((direction - Vector3::UNIT_Y).length() < 1.0e-12);
}
#[test]
fn enter_starts_the_two_point_flow() {
let mut command = HorizontalConstraintCommand::new();
assert!(matches!(command.on_enter(), CmdResult::NeedPoint));
assert!(matches!(
command.on_point(DVec3::new(1.0, 2.0, 0.0)),
CmdResult::NeedPoint
));
let CmdResult::AddHorizontalConstraint {
selection: HorizontalConstraintSelection::Points(first, second),
direction,
..
} = command.on_point(DVec3::new(4.0, 5.0, 0.0))
else {
panic!("second point must create the constraint");
};
assert_eq!(first.point, DVec3::new(1.0, 2.0, 0.0));
assert_eq!(second.point, DVec3::new(4.0, 5.0, 0.0));
assert!((direction - Vector3::UNIT_X).length() < 1.0e-12);
}
}
inventory::submit!(crate::command::CommandRegistration {
names: &["GCHORIZONTAL"]
});
+16 -7
View File
@@ -3,26 +3,35 @@
//! resulting constraints through the geometry kernel.
mod coincident;
mod concentric;
mod constraint_bar;
mod equal_distance;
mod geom_constraint;
#[path = "horizontal.rs"]
mod horizontal_command;
#[path = "perpendicular.rs"]
mod perpendicular_command;
mod point_on_entity;
mod smooth;
#[path = "tangent.rs"]
mod tangent_command;
mod tools;
mod value;
pub use coincident::{coincident_tool, CoincidentConstraintCommand};
pub use concentric::ConcentricConstraintCommand;
pub use constraint_bar::ConstraintBarOptionCommand;
pub use equal_distance::{equal_distance_tool, EqualDistanceConstraintCommand};
pub use geom_constraint::GeomConstraintCommand;
pub use horizontal_command::HorizontalConstraintCommand;
pub use perpendicular_command::{PerpendicularConstraintCommand, PerpendicularPick};
pub use point_on_entity::{
center_point_tool, midpoint_tool, point_on_curve_tool, PointOnEntityConstraintCommand,
};
pub use smooth::SmoothConstraintCommand;
pub use tangent_command::TangentConstraintCommand;
pub use tools::{
colinear, concentric, equal, fixed, horizontal, normal, parallel, perpendicular, symmetric,
tangent, vertical,
colinear, concentric as concentric_tool, equal, fixed, horizontal, normal, parallel,
perpendicular, symmetric, tangent, vertical,
};
pub use value::{
angle_tool, dimensional_tools, distance_tool, AngleConstraintCommand,
@@ -62,10 +71,10 @@ impl CadModule for ParametricModule {
RibbonItem::LargeTool(colinear::tool()),
RibbonItem::LargeTool(perpendicular::tool()),
RibbonItem::LargeTool(command(
"SMOOTHCONSTRAINT", "Smooth",
"GCSMOOTH", "Smooth",
include_bytes!("../../../assets/icons/constrain/smooth.svg"),
)),
RibbonItem::LargeTool(concentric::tool()),
RibbonItem::LargeTool(concentric_tool::tool()),
RibbonItem::LargeTool(horizontal::tool()),
RibbonItem::LargeTool(symmetric::tool()),
RibbonItem::LargeTool(fixed::tool()),
@@ -136,7 +145,7 @@ impl CadModule for ParametricModule {
inventory::submit!(crate::command::CommandRegistration {
names: &[
"AUTOCONSTRAIN", "CONSTRAINTSETTINGS", "SMOOTHCONSTRAINT", "GCSHOW", "GCHIDE", "GCRESET",
"AUTOCONSTRAIN", "CONSTRAINTSETTINGS", "GCSMOOTH", "GCSHOW", "GCHIDE", "GCRESET",
"GCSHOWALL", "GCHIDEALL", "DCSHOW", "DCHIDE", "DCSHOWALL", "DCHIDEALL",
"DCCONVERT", "DELCONSTRAINT",
]
@@ -168,8 +177,8 @@ mod tests {
groups[0].tools.iter().map(item_id).collect::<Vec<_>>(),
[
"AUTOCONSTRAIN", "CCONSTRAINT", "PCONSTRAINT", "TCONSTRAINT",
"LCONSTRAINT", "QCONSTRAINT", "SMOOTHCONSTRAINT", "NCONSTRAINT",
"HCONSTRAINT", "SYCONSTRAINT", "FXCONSTRAINT", "VCONSTRAINT",
"LCONSTRAINT", "QCONSTRAINT", "GCSMOOTH", "GCCONCENTRIC",
"GCHORIZONTAL", "SYCONSTRAINT", "FXCONSTRAINT", "VCONSTRAINT",
"ECONSTRAINT", "GCVISIBILITY", "GCSHOWALL", "GCHIDEALL",
]
);
+58 -23
View File
@@ -33,24 +33,37 @@ impl PerpendicularConstraintCommand {
}
fn distance_to_axis(point: DVec3, endpoints: [acadrust::types::Vector3; 2]) -> f64 {
let start = DVec3::new(endpoints[0].x, endpoints[0].y, endpoints[0].z);
let end = DVec3::new(endpoints[1].x, endpoints[1].y, endpoints[1].z);
let direction = end - start;
if direction.length_squared() <= 1.0e-24 {
return f64::INFINITY;
}
(point - start).cross(direction.normalize()).length()
cadkernel::space::Vec3::from(point.to_array())
.distance_to_line(
cadkernel::space::Vec3::new(endpoints[0].x, endpoints[0].y, endpoints[0].z),
cadkernel::space::Vec3::new(endpoints[1].x, endpoints[1].y, endpoints[1].z),
)
.unwrap_or(f64::INFINITY)
}
fn ellipse_reference(entity: &EntityType, handle: Handle, point: DVec3) -> Option<ParametricRef> {
fn ellipse_reference(
entity: &EntityType,
handle: Handle,
point: DVec3,
) -> Option<ParametricRef> {
let major = ParametricRef::ellipse_major_axis(handle);
let minor = ParametricRef::ellipse_minor_axis(handle);
let major_distance = Self::distance_to_axis(point, directional_axis_endpoints(entity, major)?);
let minor_distance = Self::distance_to_axis(point, directional_axis_endpoints(entity, minor)?);
Some(if minor_distance < major_distance { minor } else { major })
let major_distance =
Self::distance_to_axis(point, directional_axis_endpoints(entity, major)?);
let minor_distance =
Self::distance_to_axis(point, directional_axis_endpoints(entity, minor)?);
Some(if minor_distance < major_distance {
minor
} else {
major
})
}
fn picked_reference(entity: &EntityType, handle: Handle, point: DVec3) -> Option<PerpendicularPick> {
fn picked_reference(
entity: &EntityType,
handle: Handle,
point: DVec3,
) -> Option<PerpendicularPick> {
let (reference, fixed_reference, start_reference) = match entity {
EntityType::Line(_) => (
ParametricRef::whole(handle),
@@ -58,7 +71,8 @@ impl PerpendicularConstraintCommand {
ParametricRef::point(handle, 0),
),
EntityType::LwPolyline(_) | EntityType::Polyline2D(_) => {
let (source, _, _) = crate::scene::centerline::picked_source(entity, handle, point)?;
let (source, _, _) =
crate::scene::centerline::picked_source(entity, handle, point)?;
let index = usize::try_from(source.segment_index).ok()?;
(
ParametricRef::segment(handle, index),
@@ -101,11 +115,12 @@ impl PerpendicularConstraintCommand {
} else {
polyline.vertices.len().saturating_sub(1)
};
(segment_count == 1 && polyline.vertices.first()?.bulge.abs() <= 1.0e-12)
.then_some(PerpendicularPick {
reference: ParametricRef::segment(handle, 0),
fixed_reference: ParametricRef::segment(handle, 0),
start_reference: ParametricRef::point(handle, 0),
let index = (0..segment_count)
.find(|index| polyline.vertices[*index].bulge.abs() <= 1.0e-12)?;
Some(PerpendicularPick {
reference: ParametricRef::segment(handle, index),
fixed_reference: ParametricRef::segment(handle, index),
start_reference: ParametricRef::point(handle, index as i32),
})
}
EntityType::Polyline2D(polyline) => {
@@ -114,11 +129,12 @@ impl PerpendicularConstraintCommand {
} else {
polyline.vertices.len().saturating_sub(1)
};
(segment_count == 1 && polyline.vertices.first()?.bulge.abs() <= 1.0e-12)
.then_some(PerpendicularPick {
reference: ParametricRef::segment(handle, 0),
fixed_reference: ParametricRef::segment(handle, 0),
start_reference: ParametricRef::point(handle, 0),
let index = (0..segment_count)
.find(|index| polyline.vertices[*index].bulge.abs() <= 1.0e-12)?;
Some(PerpendicularPick {
reference: ParametricRef::segment(handle, index),
fixed_reference: ParametricRef::segment(handle, index),
start_reference: ParametricRef::point(handle, index as i32),
})
}
_ => None,
@@ -232,4 +248,23 @@ mod tests {
assert_eq!(first_fixed, ParametricRef::whole(first));
assert_eq!(second_start, ParametricRef::point(second, 0));
}
#[test]
fn preselection_uses_the_first_straight_polyline_segment() {
let handle = Handle::new(11);
let mut polyline = acadrust::entities::LwPolyline::new();
polyline.vertices = vec![
acadrust::entities::LwVertex::with_bulge(acadrust::types::Vector2::new(0.0, 0.0), 1.0),
acadrust::entities::LwVertex::from_coords(4.0, 0.0),
acadrust::entities::LwVertex::from_coords(8.0, 0.0),
];
let pick = PerpendicularConstraintCommand::preselected_reference(
&EntityType::LwPolyline(polyline),
handle,
)
.expect("straight segment");
assert_eq!(pick.reference, ParametricRef::segment(handle, 1));
assert_eq!(pick.start_reference, ParametricRef::point(handle, 1));
}
}
+261
View File
@@ -0,0 +1,261 @@
use acadrust::{EntityType, Handle};
use glam::DVec3;
use crate::command::{CadCommand, CmdResult};
use crate::scene::parametric_constraints::{ConstraintKind, ParametricRef};
use crate::t;
#[derive(Clone, Copy)]
struct SmoothTarget {
endpoint: ParametricRef,
curve: ParametricRef,
}
pub struct SmoothConstraintCommand {
source: Option<ParametricRef>,
picked_entity: Option<EntityType>,
}
impl SmoothConstraintCommand {
pub fn new() -> Self {
Self {
source: None,
picked_entity: None,
}
}
fn point(point: acadrust::types::Vector3) -> DVec3 {
DVec3::new(point.x, point.y, point.z)
}
fn nearest_marker(points: &[acadrust::types::Vector3], point: DVec3) -> Option<i32> {
points
.iter()
.enumerate()
.min_by(|(_, left), (_, right)| {
(Self::point(**left) - point)
.length_squared()
.total_cmp(&(Self::point(**right) - point).length_squared())
})
.map(|(index, _)| index as i32)
}
fn source_reference(entity: &EntityType, handle: Handle, point: DVec3) -> Option<ParametricRef> {
let EntityType::Spline(spline) = entity else {
return None;
};
if spline.flags.closed || spline.flags.periodic {
return None;
}
let points = crate::scene::dimension_assoc::source_points(entity);
let endpoints = [*points.first()?, *points.last()?];
let marker = Self::nearest_marker(&endpoints, point)?;
Some(ParametricRef::point(handle, marker))
}
fn target_reference(entity: &EntityType, handle: Handle, point: DVec3) -> Option<SmoothTarget> {
match entity {
EntityType::Line(_) | EntityType::Arc(_) => {
let points = crate::scene::dimension_assoc::source_points(entity);
let endpoints = [*points.first()?, *points.last()?];
let marker = Self::nearest_marker(&endpoints, point)?;
Some(SmoothTarget {
endpoint: ParametricRef::point(handle, marker),
curve: ParametricRef::whole(handle),
})
}
EntityType::Spline(spline) if !spline.flags.closed && !spline.flags.periodic => {
let points = crate::scene::dimension_assoc::source_points(entity);
let endpoints = [*points.first()?, *points.last()?];
let marker = Self::nearest_marker(&endpoints, point)?;
Some(SmoothTarget {
endpoint: ParametricRef::point(handle, marker),
curve: ParametricRef::whole(handle),
})
}
EntityType::LwPolyline(_) | EntityType::Polyline2D(_) => {
let planar = crate::entities::curve::entity_curve(entity)?;
let local = planar.plane.project(point.to_array())?;
let segments = planar.curve.segments();
let (segment, _) = cadkernel::geom2d::nearest_of(segments.iter(), local)?;
let points = crate::scene::dimension_assoc::source_points(entity);
let closed = match entity {
EntityType::LwPolyline(polyline) => polyline.is_closed,
EntityType::Polyline2D(polyline) => polyline.is_closed(),
_ => false,
};
let end = if segment + 1 < points.len() {
segment + 1
} else if closed {
0
} else {
return None;
};
let candidates = [points.get(segment).copied()?, points.get(end).copied()?];
let side = Self::nearest_marker(&candidates, point)? as usize;
let vertex = if side == 0 { segment } else { end };
Some(SmoothTarget {
endpoint: ParametricRef::point(handle, vertex as i32),
curve: ParametricRef::segment(handle, segment),
})
}
_ => None,
}
}
pub fn preselected_refs(
first: (&EntityType, Handle),
second: (&EntityType, Handle),
) -> Option<Vec<ParametricRef>> {
let source_points = crate::scene::dimension_assoc::source_points(first.0);
let source_ends = [*source_points.first()?, *source_points.last()?];
let source_point = source_ends
.iter()
.copied()
.min_by(|left, right| {
let target_points = crate::scene::dimension_assoc::source_points(second.0);
let distance = |source: acadrust::types::Vector3| {
target_points
.iter()
.map(|target| (source - *target).length_squared())
.fold(f64::INFINITY, f64::min)
};
distance(*left).total_cmp(&distance(*right))
})?;
let source = Self::source_reference(first.0, first.1, Self::point(source_point))?;
let target_points = crate::scene::dimension_assoc::source_points(second.0);
let target_point = target_points
.iter()
.copied()
.min_by(|left, right| {
(Self::point(*left) - Self::point(source_point))
.length_squared()
.total_cmp(
&(Self::point(*right) - Self::point(source_point)).length_squared(),
)
})?;
let target = Self::target_reference(second.0, second.1, Self::point(target_point))?;
let mut refs = vec![source, target.endpoint];
if target.curve.marker.is_some() {
refs.push(target.curve);
}
Some(refs)
}
fn invalid_source() -> CmdResult {
CmdResult::ReportError(
t!("Invalid first selection for Smooth. Select an endpoint of an open spline.")
.into_owned(),
)
}
fn invalid_target() -> CmdResult {
CmdResult::ReportError(
t!("Invalid second selection for Smooth. Select an endpoint of a line, arc, polyline segment or open spline.")
.into_owned(),
)
}
}
impl CadCommand for SmoothConstraintCommand {
fn name(&self) -> &'static str {
"GCSMOOTH"
}
fn prompt(&self) -> String {
if self.source.is_some() {
t!("GCSMOOTH Select second curve endpoint:").into_owned()
} else {
t!("GCSMOOTH Select first spline curve endpoint:").into_owned()
}
}
fn needs_entity_pick(&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 on_entity_pick(&mut self, handle: Handle, point: DVec3) -> CmdResult {
if handle.is_null() {
return CmdResult::NeedPoint;
}
let Some(entity) = self.picked_entity.take() else {
return CmdResult::NeedPoint;
};
let Some(source) = self.source else {
let Some(source) = Self::source_reference(&entity, handle, point) else {
return Self::invalid_source();
};
self.source = Some(source);
return CmdResult::NeedPoint;
};
let Some(target) = Self::target_reference(&entity, handle, point) else {
return Self::invalid_target();
};
if source.entity == target.endpoint.entity {
return Self::invalid_target();
}
let mut refs = vec![source, target.endpoint];
if target.curve.marker.is_some() {
refs.push(target.curve);
}
CmdResult::AddParametricConstraint {
kind: ConstraintKind::Smooth,
refs,
driving_param: None,
label: "Smooth constraint",
}
}
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
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn polyline_target_keeps_the_picked_arc_segment_and_endpoint() {
let handle = Handle::new(7);
let mut polyline = acadrust::entities::LwPolyline::new();
polyline.vertices = vec![
acadrust::entities::LwVertex::from_coords(0.0, 0.0),
acadrust::entities::LwVertex::with_bulge(
acadrust::types::Vector2::new(5.0, 0.0),
1.0,
),
acadrust::entities::LwVertex::from_coords(10.0, 0.0),
];
let target = SmoothConstraintCommand::target_reference(
&EntityType::LwPolyline(polyline),
handle,
DVec3::new(10.0, 0.0, 0.0),
)
.expect("arc endpoint");
assert_eq!(target.curve, ParametricRef::segment(handle, 1));
assert_eq!(target.endpoint, ParametricRef::point(handle, 2));
}
}
+6 -6
View File
@@ -6,12 +6,12 @@ pub mod horizontal {
use super::*;
pub fn tool() -> ToolDef {
ToolDef {
id: "HCONSTRAINT",
id: "GCHORIZONTAL",
label: "Horizontal",
icon: IconKind::Svg(include_bytes!(
"../../../assets/icons/constrain/horizontal.svg"
)),
event: ModuleEvent::Command("HCONSTRAINT".to_string()),
event: ModuleEvent::Command("GCHORIZONTAL".to_string()),
}
}
}
@@ -88,12 +88,12 @@ pub mod concentric {
use super::*;
pub fn tool() -> ToolDef {
ToolDef {
id: "NCONSTRAINT",
id: "GCCONCENTRIC",
label: "Concentric",
icon: IconKind::Svg(include_bytes!(
"../../../assets/icons/constrain/concentric.svg"
)),
event: ModuleEvent::Command("NCONSTRAINT".to_string()),
event: ModuleEvent::Command("GCCONCENTRIC".to_string()),
}
}
}
@@ -160,14 +160,14 @@ pub mod symmetric {
// ── Autocomplete registry ─────────────────────────────────
inventory::submit!(crate::command::CommandRegistration {
names: &[
"HCONSTRAINT",
"GCHORIZONTAL",
"VCONSTRAINT",
"PCONSTRAINT",
"QCONSTRAINT",
"GCPERPENDICULAR",
"ECONSTRAINT",
"TCONSTRAINT",
"NCONSTRAINT",
"GCCONCENTRIC",
"NRCONSTRAINT",
"LCONSTRAINT",
"FXCONSTRAINT",
+69
View File
@@ -3110,6 +3110,75 @@ mod tests {
assert_eq!(line_wire.world_width, 10.0);
}
#[test]
fn split_mixed_polyline_keeps_exact_line_intersections() {
let tangents = vec![
TangentGeom::Line {
p1: [-10.0, 0.0, 0.0],
p2: [0.0, 0.0, 0.0],
},
TangentGeom::Arc {
center: [0.0, 4.0, 0.0],
axis_x: [1.0, 0.0, 0.0],
axis_y: [0.0, 1.0, 0.0],
radius: 4.0,
start_angle: -std::f64::consts::FRAC_PI_2,
end_angle: std::f64::consts::FRAC_PI_2,
},
TangentGeom::Line {
p1: [0.0, 8.0, 0.0],
p2: [10.0, 8.0, 0.0],
},
];
let vertices = vec![
[-10.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 8.0, 0.0],
[10.0, 8.0, 0.0],
];
let wires = split_mixed_polyline(
&tangents,
&vertices,
"mixed",
[1.0; 4],
false,
0.0,
[0.0; 8],
1.0,
Vec::new(),
None,
true,
&[(0.0, 0.0); 3],
0.0,
Vec::new(),
Vec::new(),
);
let line_wire = wires
.iter()
.find(|wire| {
wire.tangent_geoms
.iter()
.all(|geom| matches!(geom, TangentGeom::Line { .. }))
})
.expect("straight-segment wire");
let circle = WireModel {
tangent_geoms: vec![TangentGeom::PlanarCircle {
center: [5.0, 4.0, 0.0],
axis_x: [1.0, 0.0, 0.0],
axis_y: [0.0, 1.0, 0.0],
radius: 5.0,
}],
..Default::default()
};
let mut points = crate::snap::exact_curve_intersections(line_wire, &circle)
.expect("analytical intersections");
points.sort_by(|left, right| left.x.total_cmp(&right.x));
assert_eq!(points.len(), 2, "unexpected intersections: {points:?}");
assert!((points[0] - glam::DVec3::new(2.0, 8.0, 0.0)).length() < 1.0e-9);
assert!((points[1] - glam::DVec3::new(8.0, 8.0, 0.0)).length() < 1.0e-9);
}
#[test]
fn test_split_mixed_polyline_zero_width_segments_after_tapered_segment() {
let tg_line = TangentGeom::Line {
+112 -33
View File
@@ -56,8 +56,6 @@ struct GroupBuilder<'a> {
/// Real entity handles that ended up with a geometry node — what
/// `AssocGeomDependency` objects get created for, in first-touch order.
referenced_entities: Vec<Handle>,
horizontal_datum: Option<i32>,
vertical_datum: Option<i32>,
}
impl<'a> GroupBuilder<'a> {
@@ -68,8 +66,6 @@ impl<'a> GroupBuilder<'a> {
next_node_id: FIRST_NODE_ID,
entities: FxHashMap::default(),
referenced_entities: Vec::new(),
horizontal_datum: None,
vertical_datum: None,
}
}
@@ -454,11 +450,17 @@ impl<'a> GroupBuilder<'a> {
return Some(*existing);
}
let segment_midpoint = ParametricRef::point(handle, marker).segment_midpoint_index();
let segment_center = ParametricRef::point(handle, marker).segment_center_index();
let polyline = matches!(
self.document.get_entity(handle),
Some(EntityType::LwPolyline(_) | EntityType::Polyline2D(_))
);
let (curve_id, point_type) = if let Some(segment) = segment_midpoint {
let (curve_id, point_type) = if let Some(segment) = segment_center {
(
self.segment_node(handle, segment)?,
implicit_point_type::CENTER,
)
} else if let Some(segment) = segment_midpoint {
(
self.segment_node(handle, segment)?,
implicit_point_type::MID,
@@ -551,6 +553,9 @@ impl<'a> GroupBuilder<'a> {
if r.segment_midpoint_index().is_some() {
return self.point_node(r.entity, r.marker?);
}
if r.segment_center_index().is_some() {
return self.point_node(r.entity, r.marker?);
}
if let Some(segment) = r.segment_index() {
return self.segment_node(r.entity, segment);
}
@@ -653,15 +658,7 @@ impl<'a> GroupBuilder<'a> {
Some(node_id)
}
fn datum_line(&mut self, horizontal: bool) -> i32 {
let cached = if horizontal {
self.horizontal_datum
} else {
self.vertical_datum
};
if let Some(node_id) = cached {
return node_id;
}
fn datum_line(&mut self, direction: Vector3) -> i32 {
let node_id = self.alloc_node_id();
self.push_node(
node_id,
@@ -670,18 +667,13 @@ impl<'a> GroupBuilder<'a> {
geometry_dependency: Handle::NULL,
geometry_node_id: node_id,
point: Vector3::ZERO,
direction: if horizontal {
Vector3::UNIT_X
direction: if direction.length_squared() > 1.0e-24 {
direction.normalize()
} else {
Vector3::UNIT_Y
Vector3::UNIT_X
},
},
);
if horizontal {
self.horizontal_datum = Some(node_id);
} else {
self.vertical_datum = Some(node_id);
}
node_id
}
@@ -771,7 +763,13 @@ fn constraint_node(
) -> Option<i32> {
let refs: &[ParametricRef] = &constraint.refs;
if constraint.kind == ConstraintKind::Smooth {
let [first, second] = refs else { return None };
let (first, second, second_curve_ref) = match refs {
[first, second] => (*first, *second, ParametricRef::whole(second.entity)),
[first, second, second_curve] if second.entity == second_curve.entity => {
(*first, *second, *second_curve)
}
_ => return None,
};
let endpoint_parameter = |reference: ParametricRef| {
let entity = document.get_entity(reference.entity)?;
let EntityType::Spline(spline) = entity else {
@@ -791,15 +789,15 @@ fn constraint_node(
}?;
Some(Some(value))
};
let first_parameter = endpoint_parameter(*first)?;
let second_parameter = endpoint_parameter(*second)?;
let first_parameter = endpoint_parameter(first)?;
let second_parameter = endpoint_parameter(second)?;
if first_parameter.is_none() && second_parameter.is_none() {
return None;
}
let first_curve = builder.geometry_node(first.entity)?;
let second_curve = builder.geometry_node(second.entity)?;
let first_point = builder.ref_node(*first)?;
let second_point = builder.ref_node(*second)?;
let second_curve = builder.ref_node(second_curve_ref)?;
let first_point = builder.ref_node(first)?;
let second_point = builder.ref_node(second)?;
let coincidence = builder.alloc_node_id();
builder.push_node(
@@ -917,7 +915,12 @@ fn constraint_node(
.map(|reference| builder.ref_node(*reference))
.collect::<Option<_>>()?;
let horizontal = constraint.kind == ConstraintKind::Horizontal;
let datum = builder.datum_line(horizontal);
let fallback = if horizontal {
Vector3::UNIT_X
} else {
Vector3::UNIT_Y
};
let datum = builder.datum_line(constraint.axis_direction.unwrap_or(fallback));
let node_id = builder.alloc_node_id();
builder.push_node(
node_id,
@@ -1647,6 +1650,21 @@ fn group_requires_preservation(document: &CadDocument, group: &Assoc2dConstraint
})
}
fn work_plane_vector(work_plane: &[Vector3; 3], local: Vector3) -> Option<Vector3> {
let [origin, axis_x, axis_y] = *work_plane;
let plane = cadkernel::space::Plane::from_axes(
[origin.x, origin.y, origin.z],
[axis_x.x, axis_x.y, axis_x.z],
[axis_y.x, axis_y.y, axis_y.z],
);
let mut world = cadkernel::space::Vec3::from(plane.vector_at([local.x, local.y]));
if local.z != 0.0 {
world = world + cadkernel::space::Vec3::from(plane.normal()?) * local.z;
}
let world = world.normalize()?;
Some(Vector3::new(world.x, world.y, world.z))
}
fn polyline_segment_reference(
document: &CadDocument,
entity: Handle,
@@ -2073,6 +2091,9 @@ pub(super) fn native_constraint_set(
implicit_point_type::MID => {
ParametricRef::segment_midpoint(curve.entity, segment)
}
implicit_point_type::CENTER => {
ParametricRef::segment_center(curve.entity, segment)
}
_ => continue,
}
} else {
@@ -2130,7 +2151,7 @@ pub(super) fn native_constraint_set(
owned_constraint_ids,
..
} if kind == ConstraintKind::Smooth => {
let endpoints = owned_constraint_ids
let mut endpoints: Vec<ParametricRef> = owned_constraint_ids
.iter()
.filter_map(|id| group.nodes.iter().find(|child| child.node_id == *id))
.find(|child| {
@@ -2146,6 +2167,23 @@ pub(super) fn native_constraint_set(
.collect()
})
.unwrap_or_default();
if let Some(target) = endpoints.get(1).copied() {
let segment = owned_constraint_ids
.iter()
.filter_map(|id| group.nodes.iter().find(|child| child.node_id == *id))
.filter(|child| {
child.class_name.eq_ignore_ascii_case("AcTangentConstraint")
})
.flat_map(|child| child.connections.iter())
.filter_map(|id| refs.get(id).copied())
.find(|reference| {
reference.entity == target.entity
&& reference.segment_index().is_some()
});
if let Some(segment) = segment {
endpoints.push(segment);
}
}
(endpoints, Vec::new())
}
_ => (
@@ -2192,6 +2230,7 @@ pub(super) fn native_constraint_set(
ConstraintKind::DistanceDirected => matches!(targets.len(), 2 | 3),
ConstraintKind::EqualDistance => targets.len() == 4,
ConstraintKind::RigidSet => !targets.is_empty() && rigid_points.len() >= 2,
ConstraintKind::Smooth => matches!(targets.len(), 2 | 3),
_ => targets.len() == 2,
};
if !valid_target_count {
@@ -2215,6 +2254,31 @@ pub(super) fn native_constraint_set(
if let Some(constraint) = set.constraints.last_mut() {
constraint.enabled = enabled;
constraint.rigid_points = rigid_points;
if matches!(kind, ConstraintKind::Horizontal | ConstraintKind::Vertical) {
let datum_id = match &node.data {
AssocConstraintNodeData::Parallel {
datum_line_index, ..
} => *datum_line_index,
_ => None,
};
let local_direction = datum_id.and_then(|datum_id| {
group.nodes.iter().find_map(|datum| {
(datum.node_id == datum_id).then_some(&datum.data).and_then(|data| {
match data {
AssocConstraintNodeData::Line { direction, .. } => {
Some(*direction)
}
_ => None,
}
})
})
});
if let Some(world) =
local_direction.and_then(|local| work_plane_vector(&group.work_plane, local))
{
constraint.axis_direction = Some(world);
}
}
if let AssocConstraintNodeData::Distance {
direction_type,
distance,
@@ -2845,14 +2909,15 @@ mod tests {
fn horizontal_and_vertical_constraints_round_trip_through_dwg_and_dxf() {
for ext in ["dwg", "dxf"] {
let mut scene = Scene::new();
let a = line_entity(&mut scene, (0.0, 0.0), (10.0, 0.0));
let a = line_entity(&mut scene, (0.0, 0.0), (6.0, 8.0));
let b = line_entity(&mut scene, (10.0, 0.0), (10.0, 5.0));
let horizontal_direction = Vector3::new(0.6, 0.8, 0.0);
scene
.parametric_constraint_set_mut(ParametricScope::ModelSpace)
.add(
.add_axis_constraint(
ConstraintKind::Horizontal,
vec![ParametricRef::whole(a)],
None,
horizontal_direction,
);
scene
.parametric_constraint_set_mut(ParametricScope::ModelSpace)
@@ -2918,6 +2983,20 @@ mod tests {
assert!(datums.iter().all(|datum| group.nodes.iter().any(|node| {
node.node_id == *datum && node.class_name == "AcConstrainedDatumLine"
})));
let mut restored = Scene::new();
restored.document = reloaded;
restored.load_parametric_constraints_from_document();
let horizontal = restored
.parametric_constraint_set(ParametricScope::ModelSpace)
.unwrap()
.constraints
.iter()
.find(|constraint| constraint.kind == ConstraintKind::Horizontal)
.unwrap();
assert!(
(horizontal.axis_direction.unwrap() - horizontal_direction).length() < 1.0e-12
);
}
}
+21
View File
@@ -2709,4 +2709,25 @@ impl Scene {
self.named_parameters = crate::scene::named_parameters::ParameterTable::new();
self.bump_geometry();
}
/// Reset to the drawing File → New produces. Every path that starts a
/// fresh drawing (the New tab, CLEAR, the automation `new` op) goes
/// through here so they all agree on what a blank drawing contains.
pub fn reset_to_new_drawing(&mut self) {
self.clear();
self.populate_new_drawing_defaults();
}
/// What a blank document gets on top of the codec's defaults: the
/// standard linetypes and a compatible page setup on every paper layout.
pub fn populate_new_drawing_defaults(&mut self) {
crate::io::linetypes::populate_document(&mut self.document);
for obj in self.document.objects.values_mut() {
if let acadrust::objects::ObjectType::Layout(l) = obj {
if l.name != "Model" {
crate::scene::apply_default_page_setup(l, "");
}
}
}
}
}
+92 -7
View File
@@ -33,6 +33,7 @@ pub(crate) mod centermark;
pub(crate) mod dimension_assoc;
pub(crate) mod dimension_assoc_chain;
pub use dimension_assoc::{ReferenceStatus, ResolvedReference};
pub use page_setup::{apply_default_page_setup, rotated_margins};
mod dwg_native_constraints;
mod entity;
#[cfg(test)]
@@ -3245,6 +3246,23 @@ impl Scene {
);
}
pub fn bump_entities_with_parametric_transform_policy(
&mut self,
changes: &[(Handle, ChangeKind)],
driven_refs: &[parametric_constraints::ParametricRef],
transformed_refs: &[parametric_constraints::ParametricRef],
retained_originals: &[(Handle, EntityType)],
) {
self.bump_entities_with_solve_policy(
changes,
driven_refs,
true,
retained_originals,
transformed_refs,
true,
);
}
fn bump_entities_with_solve_policy(
&mut self,
changes: &[(Handle, ChangeKind)],
@@ -4361,13 +4379,8 @@ impl Scene {
None
})?;
// `paper_limits()` already swaps the sheet for a 90°/270° rotation, so the
// margins must rotate to the same edges: a margin on a physical side moves
// to the displayed side that side rotates onto.
let (ml, mb, mr, mt) = match rot {
1 | 3 => (bottom, left, top, right),
2 => (right, top, left, bottom),
_ => (left, bottom, right, top),
};
// margins must rotate to the same edges.
let (ml, mb, mr, mt) = page_setup::rotated_margins((left, bottom, right, top), rot);
// Plot margins are millimetres like the paper size; scale them into the
// layout's paper-space units so the inset matches the (already scaled)
// sheet rect. Without this an inch paper space insets an ~8-inch sheet
@@ -4953,6 +4966,78 @@ impl Scene {
.then_some(owner)
}
/// Millimetres in one unit of the paper side of this drawing's scale
/// family: 25.4 for an imperial drawing (whose `1/8" = 1'-0"` style scales
/// measure paper in inches), 1 for a metric one. Plot-scale factors built
/// from [`Scene::scale_list`] are expressed per this unit; page setups
/// store theirs per the layout's own paper unit, so the two are converted
/// through this value.
pub(crate) fn scale_family_unit_mm(&self) -> f64 {
if self.prefers_imperial_scales() == Some(true) {
25.4
} else {
1.0
}
}
/// The `paper : drawing` ratio behind a scale-list name, from the
/// drawing's own `Scale` object when it has one, otherwise from the
/// built-in family. A ratio keeps the plot scale readable in a page setup
/// (`1 : 250` rather than `0.004 : 1`).
pub(crate) fn scale_ratio(&self, name: &str) -> Option<(f64, f64)> {
use acadrust::objects::ObjectType;
let stored = self.document.objects.values().find_map(|o| match o {
ObjectType::Scale(s) if !s.is_temporary && s.name.eq_ignore_ascii_case(name) => {
Some((s.paper_units, s.drawing_units))
}
_ => None,
});
stored
.or_else(|| Self::parse_scale_name_ratio(name))
.filter(|(paper, drawing)| *paper > 0.0 && *drawing > 0.0)
}
/// The `paper : drawing` ratio spelled by a scale name: `1:250` gives
/// `(1, 250)`, an architectural `1/8" = 1'-0"` gives `(0.125, 12)` in
/// inches. Anything else is not a scale name.
pub(crate) fn parse_scale_name_ratio(name: &str) -> Option<(f64, f64)> {
if let Some((paper, drawing)) = name.split_once(':') {
let paper: f64 = paper.trim().parse().ok()?;
let drawing: f64 = drawing.trim().parse().ok()?;
return (paper > 0.0 && drawing > 0.0).then_some((paper, drawing));
}
let (paper, drawing) = name.split_once('=')?;
let paper = Self::parse_feet_inches(paper)?;
let drawing = Self::parse_feet_inches(drawing)?;
(paper > 0.0 && drawing > 0.0).then_some((paper, drawing))
}
/// Inches in a `F'-I"` / `I"` / `F'` length, where the inch part may be a
/// fraction (`3/32"`).
fn parse_feet_inches(text: &str) -> Option<f64> {
let text = text.trim();
let (feet, inches) = match text.split_once('\'') {
Some((feet, rest)) => (
feet.trim().parse::<f64>().ok()?,
rest.trim_start_matches('-').trim(),
),
None => (0.0, text),
};
let inches = inches.trim_end_matches('"').trim();
let inches = if inches.is_empty() {
0.0
} else if let Some((num, den)) = inches.split_once('/') {
let den: f64 = den.trim().parse().ok()?;
if den <= 0.0 {
return None;
}
num.trim().parse::<f64>().ok()? / den
} else {
inches.parse::<f64>().ok()?
};
Some(feet * 12.0 + inches)
}
/// Handle of the real (non-temporary) `Scale` object with this display name.
/// Scales are matched by their `name` field, not the dictionary key — some
/// files key the entries by an internal identifier (`*A1`, `A0`, …) that
+80 -1
View File
@@ -161,6 +161,80 @@ impl Scene {
.filter(|&h| !self.is_layer_locked(h))
.collect();
let handles = &handles[..];
let retained_originals: Vec<(Handle, EntityType)> = handles
.iter()
.filter_map(|handle| {
self.document
.get_entity(*handle)
.cloned()
.map(|entity| (*handle, entity))
})
.collect();
let transformed_refs: Vec<_> = handles
.iter()
.copied()
.map(parametric_constraints::ParametricRef::whole)
.collect();
let mut driven_refs = Vec::new();
if !matches!(t, EntityTransform::Translate(_)) {
for set in &self.parametric_constraints {
for constraint in &set.constraints {
if !constraint.enabled
|| !matches!(
constraint.kind,
parametric_constraints::ConstraintKind::Parallel
| parametric_constraints::ConstraintKind::Perpendicular
| parametric_constraints::ConstraintKind::Colinear
)
{
continue;
}
let selected_refs = constraint
.refs
.iter()
.filter(|reference| handles.contains(&reference.entity))
.count();
if selected_refs == 0 || selected_refs == constraint.refs.len() {
continue;
}
for reference in constraint
.refs
.iter()
.copied()
.filter(|reference| !handles.contains(&reference.entity))
{
let anchor = if let Some(index) = reference.segment_index() {
parametric_constraints::ParametricRef::point(
reference.entity,
index as i32,
)
} else if reference.directional_axis().is_some()
&& matches!(
self.document.get_entity(reference.entity),
Some(EntityType::Ellipse(_))
)
{
parametric_constraints::ParametricRef::center(reference.entity)
} else {
parametric_constraints::ParametricRef::point(reference.entity, 0)
};
let follows_selected_point = set.constraints.iter().any(|link| {
link.enabled
&& link.kind
== parametric_constraints::ConstraintKind::Coincident
&& link.refs.contains(&anchor)
&& link
.refs
.iter()
.any(|item| handles.contains(&item.entity))
});
if !follows_selected_point && !driven_refs.contains(&anchor) {
driven_refs.push(anchor);
}
}
}
}
}
// Preserve readable text orientation when MIRRTEXT is disabled.
let preserve_text_orientation =
matches!(t, EntityTransform::Mirror { .. }) && !self.document.header.mirror_text;
@@ -290,7 +364,12 @@ impl Scene {
// per-handle, keeping the block cache + all other memoized wires.
let changes: Vec<(Handle, ChangeKind)> =
handles.iter().map(|&h| (h, ChangeKind::Modified)).collect();
self.bump_entities(&changes);
self.bump_entities_with_parametric_transform_policy(
&changes,
&driven_refs,
&transformed_refs,
&retained_originals,
);
self.refresh_meshes_for_handles(&refresh_solid_handles);
}
+52 -1
View File
@@ -5,9 +5,60 @@
//! dictionary + objects consistent so the result round-trips through DWG/DXF.
use super::Scene;
use acadrust::objects::{Dictionary, ObjectType, PlotSettings};
use acadrust::objects::{Dictionary, Layout, ObjectType, PlotSettings};
use acadrust::Handle;
/// Give a freshly created paper layout the page setup a new drawing starts
/// with — ISO A4 landscape on no plotter, plotted 1:1 as a layout — stored the
/// way the file format expects it: the portrait medium under its canonical
/// name with the orientation in the rotation code. `plot_style` names the
/// plot style table to attach, or is empty.
pub fn apply_default_page_setup(layout: &mut Layout, plot_style: &str) {
use acadrust::objects::{PlotPaperUnits, PlotRotation, PlotType, ScaledType};
let a4 = crate::io::paper_catalog::default_paper();
let (paper_width, paper_height) = a4.portrait_mm();
layout.min_limits = (0.0, 0.0);
layout.max_limits = (paper_height, paper_width);
layout.min_extents = (0.0, 0.0, 0.0);
layout.max_extents = (paper_height, paper_width, 0.0);
layout.paper_width = paper_width;
layout.paper_height = paper_height;
layout.plot_rotation = PlotRotation::Degrees90.to_code();
layout.plot_paper_units = PlotPaperUnits::Millimeters.to_code();
layout.plot_type = PlotType::Layout.to_code();
layout.plot_scale_type = ScaledType::OneToOne.to_code();
layout.plot_scale_numerator = 1.0;
layout.plot_scale_denominator = 1.0;
layout.plot_scale_factor = 1.0;
layout.plot_flags.use_standard_scale = true;
layout.plot_flags.print_lineweights = true;
layout.plot_flags.draw_viewports_first = true;
layout.plot_flags.plot_plot_styles = !plot_style.is_empty();
layout.plot_flags.show_plot_styles = !plot_style.is_empty();
layout.plot_style_sheet = plot_style.to_string();
layout.paper_size = a4.canonical.to_string();
layout.plot_printer_name = crate::io::plot_device::PlotDevice::None.canonical_name();
}
/// The unprintable margins of a sheet as they appear on the rotated layout,
/// `(left, bottom, right, top)`. Stored margins belong to the medium's own
/// edges; a plot rotated by a quarter turn (`rotation` is the file's 0–3
/// code) shows the medium turned on the layout, so each margin moves to the
/// edge its side lands on — verified against limits written by the
/// commercial application: at 90° the medium's top margin is the layout's
/// left one and its left margin the layout's bottom one.
pub fn rotated_margins(
(left, bottom, right, top): (f64, f64, f64, f64),
rotation: i16,
) -> (f64, f64, f64, f64) {
match rotation {
1 => (top, left, bottom, right),
2 => (right, top, left, bottom),
3 => (bottom, right, top, left),
_ => (left, bottom, right, top),
}
}
impl Scene {
/// Handle of the `ACAD_PLOTSETTINGS` dictionary, located robustly.
///
+220 -53
View File
@@ -14,8 +14,8 @@ use acadrust::types::{Handle, Vector3};
/// ordered per-entity-type point list when non-negative (0/1 = a line's
/// start/end, ...), or names a special case when negative (-3 = a
/// circle/arc's center; -2 = a bounded curve's midpoint). Polyline segment
/// and segment-midpoint references use private negative ranges so they stay
/// distinct from vertex markers.
/// segment-midpoint, and curved-segment-center references use private
/// negative ranges so they stay distinct from vertex markers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ParametricRef {
pub entity: Handle,
@@ -28,6 +28,7 @@ pub struct ParametricRef {
const POLYLINE_SEGMENT_MARKER_BASE: i32 = -1_000_000;
const POLYLINE_SEGMENT_MIDPOINT_MARKER_BASE: i32 = -2_000_000;
const POLYLINE_SEGMENT_CENTER_MARKER_BASE: i32 = -3_000_000;
const ELLIPSE_MAJOR_AXIS_MARKER: i32 = -4;
const ELLIPSE_MINOR_AXIS_MARKER: i32 = -5;
const TEXT_BASELINE_MARKER: i32 = -6;
@@ -88,10 +89,25 @@ impl ParametricRef {
pub fn segment_midpoint_index(self) -> Option<usize> {
let marker = self.marker?;
(marker <= POLYLINE_SEGMENT_MIDPOINT_MARKER_BASE)
(marker <= POLYLINE_SEGMENT_MIDPOINT_MARKER_BASE
&& marker > POLYLINE_SEGMENT_CENTER_MARKER_BASE)
.then(|| (POLYLINE_SEGMENT_MIDPOINT_MARKER_BASE - marker) as usize)
}
/// Select the center of one curved polyline segment.
pub fn segment_center(entity: Handle, index: usize) -> Self {
Self {
entity,
marker: Some(POLYLINE_SEGMENT_CENTER_MARKER_BASE - index as i32),
}
}
pub fn segment_center_index(self) -> Option<usize> {
let marker = self.marker?;
(marker <= POLYLINE_SEGMENT_CENTER_MARKER_BASE)
.then(|| (POLYLINE_SEGMENT_CENTER_MARKER_BASE - marker) as usize)
}
/// Select the displayed baseline of a Text or MText entity.
pub fn text_baseline(entity: Handle) -> Self {
Self {
@@ -373,6 +389,10 @@ pub struct ParametricConstraint {
/// identifies the direction line for the line-relative modes.
pub(crate) distance_direction_type: u8,
pub(crate) distance_direction: Option<Vector3>,
/// World-space datum direction captured for Horizontal/Vertical. Native
/// files store the same vector on the connected constrained datum line.
/// `None` keeps legacy world-X/world-Y behavior.
pub(crate) axis_direction: Option<Vector3>,
/// Which of the four directed sectors an angular constraint measures.
pub(crate) angle_sector: u8,
}
@@ -460,11 +480,71 @@ impl ParametricConstraintSet {
rigid_points: Vec::new(),
distance_direction_type: 0,
distance_direction: None,
axis_direction: None,
angle_sector: angle_sector::PARALLEL_COUNTERCLOCKWISE,
});
id
}
/// Appends a Horizontal/Vertical constraint tied to an explicit datum
/// direction rather than silently interpreting it in world coordinates.
pub fn add_axis_constraint(
&mut self,
kind: ConstraintKind,
refs: Vec<ParametricRef>,
direction: Vector3,
) -> ConstraintId {
let fallback = if kind == ConstraintKind::Vertical {
Vector3::UNIT_Y
} else {
Vector3::UNIT_X
};
let direction = if direction.length_squared() > 1.0e-24 {
direction.normalize()
} else {
fallback
};
let id = self.add(kind, refs, None);
if let Some(constraint) = self.constraints.last_mut() {
constraint.axis_direction = Some(direction);
}
id
}
pub fn contains_axis_constraint(
&self,
kind: ConstraintKind,
refs: &[ParametricRef],
direction: Vector3,
) -> bool {
let fallback = if kind == ConstraintKind::Vertical {
Vector3::UNIT_Y
} else {
Vector3::UNIT_X
};
let direction = if direction.length_squared() > 1.0e-24 {
direction.normalize()
} else {
fallback
};
self.constraints.iter().any(|constraint| {
if !constraint.enabled || constraint.kind != kind {
return false;
}
let same_refs = constraint.refs == refs
|| (refs.len() == 2
&& constraint.refs.len() == 2
&& constraint.refs[0] == refs[1]
&& constraint.refs[1] == refs[0]);
if !same_refs {
return false;
}
let existing = constraint.axis_direction.unwrap_or(fallback);
existing.length_squared() > 1.0e-24
&& existing.normalize().dot(&direction).abs() >= 1.0 - 1.0e-10
})
}
/// Removes a constraint by id. Returns whether one was actually removed.
pub fn remove(&mut self, id: ConstraintId) -> bool {
let before = self.constraints.len();
@@ -503,7 +583,7 @@ impl ParametricConstraintSet {
/// endpoint's equivalent of `dimension_assoc::resolve_reference`, restricted
/// to the marker conventions constraint endpoints actually use (whole-entity
/// `None`, an ordinary `source_points()` index, the `-3` center case, or a
/// bounded curve/segment midpoint).
/// bounded curve/segment midpoint, or a curved polyline-segment center).
///
/// Solver-side registration reads raw entity fields directly. This helper is
/// for UI-side consumers that need the current world-space position.
@@ -524,12 +604,20 @@ pub(crate) fn resolve_point(entity: &acadrust::EntityType, marker: i32) -> Optio
let point = curve.point_at(0.5);
return Some(Vector3::new(point[0], point[1], point[2]));
}
let segment = ParametricRef {
let reference = ParametricRef {
entity: Handle::NULL,
marker: Some(marker),
};
if let Some(segment) = reference.segment_center_index() {
let planar = crate::entities::curve::entity_curve(entity)?;
let curve = planar.curve.segments().into_iter().nth(segment)?;
let cadkernel::geom2d::Curve::Arc(arc) = curve else {
return None;
};
let point = planar.plane.point_at(arc.centre);
return Some(Vector3::new(point[0], point[1], point[2]));
}
.segment_midpoint_index();
if let Some(segment) = segment {
if let Some(segment) = reference.segment_midpoint_index() {
let planar = crate::entities::curve::entity_curve(entity)?;
let curve = planar.curve.segments().into_iter().nth(segment)?;
let point = planar.plane.point_at(curve.point_at(0.5));
@@ -687,6 +775,27 @@ pub(crate) fn parametric_curve_ref_for_pick(
}
impl ConstraintKind {
/// Per-kind visibility bit used by CONSTRAINTBARMODE for the standard
/// geometric-constraint family. Helper relations which have no standard
/// bit stay visible under the normal display policy.
pub const fn bar_mode_bit(self) -> Option<i16> {
match self {
Self::Horizontal => Some(1),
Self::Vertical => Some(2),
Self::Perpendicular => Some(4),
Self::Parallel => Some(8),
Self::Tangent => Some(16),
Self::Smooth => Some(32),
Self::Coincident => Some(64),
Self::Concentric => Some(128),
Self::Colinear => Some(256),
Self::Symmetric => Some(512),
Self::Equal => Some(1024),
Self::Fixed => Some(2048),
_ => None,
}
}
pub const fn label(self) -> &'static str {
match self {
Self::Coincident => "Coincident",
@@ -810,6 +919,18 @@ fn glyph_placement_for_reference(
let anchor = (start + end) * 0.5;
return Some((anchor, segment_normal(start, end)));
}
if let Some(segment) = r.segment_center_index() {
let planar = crate::entities::curve::entity_curve(entity)?;
let curve = planar.curve.segments().into_iter().nth(segment)?;
let on_arc = planar.plane.point_at(curve.point_at(0.5));
let cadkernel::geom2d::Curve::Arc(arc) = curve else {
return None;
};
let center = planar.plane.point_at(arc.centre);
let center = Vector3::new(center[0], center[1], center[2]);
let on_arc = Vector3::new(on_arc[0], on_arc[1], on_arc[2]);
return Some((on_arc, on_arc - center));
}
if let Some(segment) = r.segment_index() {
let anchor = resolve_point(
entity,
@@ -1083,10 +1204,15 @@ impl super::Scene {
&self,
scope: ParametricScope,
id: ConstraintId,
kind: ConstraintKind,
related_entity_selected: bool,
display_mode: i16,
bar_mode: i16,
) -> bool {
self.is_parametric_constraint_visible(scope, id)
&& kind
.bar_mode_bit()
.is_none_or(|bit| bar_mode & bit != 0)
&& (self.shown_parametric_constraints.contains(&(scope, id))
|| (display_mode & 2 != 0 && related_entity_selected))
}
@@ -1437,40 +1563,6 @@ impl super::Scene {
inferred
}
pub fn smooth_constraint_refs(&self, handles: &[Handle]) -> Option<Vec<ParametricRef>> {
let [first, second] = handles else {
return None;
};
let first_entity = self.document.get_entity(*first)?;
let second_entity = self.document.get_entity(*second)?;
let (spline_handle, spline, target_handle, target) = match (first_entity, second_entity) {
(acadrust::EntityType::Spline(spline), target) => (*first, spline, *second, target),
(target, acadrust::EntityType::Spline(spline)) => (*second, spline, *first, target),
_ => return None,
};
if spline.flags.closed || spline.flags.periodic {
return None;
}
let spline_points =
super::dimension_assoc::source_points(&acadrust::EntityType::Spline(spline.clone()));
let target_points = super::dimension_assoc::source_points(target);
let spline_ends = [*spline_points.first()?, *spline_points.last()?];
let target_ends = [*target_points.first()?, *target_points.last()?];
let mut best = (f64::INFINITY, 0, 0);
for (source_marker, source) in spline_ends.iter().enumerate() {
for (target_marker, target) in target_ends.iter().enumerate() {
let distance = (*source - *target).length_squared();
if distance < best.0 {
best = (distance, source_marker, target_marker);
}
}
}
Some(vec![
ParametricRef::point(spline_handle, best.1 as i32),
ParametricRef::point(target_handle, best.2 as i32),
])
}
/// The constraint set for `scope`, if one has been created.
pub fn parametric_constraint_set(
&self,
@@ -1521,6 +1613,7 @@ impl super::Scene {
vp_size: (f32, f32),
show_values: bool,
display_mode: i16,
bar_mode: i16,
) -> Vec<(
ConstraintId,
iced::Point,
@@ -1555,7 +1648,14 @@ impl super::Scene {
.iter()
.any(|reference| self.selected.contains(&reference.entity)
|| self.preview_hidden.contains(&reference.entity));
self.should_display_parametric_constraint(scope, c.id, selected, display_mode)
self.should_display_parametric_constraint(
scope,
c.id,
c.kind,
selected,
display_mode,
bar_mode,
)
})
.flat_map(|c| {
let is_conflicting = set.conflicts.iter().any(|(id, _)| *id == c.id);
@@ -1627,6 +1727,7 @@ impl super::Scene {
vp_size: (f32, f32),
show_values: bool,
display_mode: i16,
bar_mode: i16,
p: iced::Point,
) -> Option<ConstraintId> {
let placements = self.constraint_glyph_placements_screen(
@@ -1634,6 +1735,7 @@ impl super::Scene {
vp_size,
show_values,
display_mode,
bar_mode,
);
let glyphs: Vec<(iced::Point, [f32; 2], String, bool)> = placements
.iter()
@@ -1671,6 +1773,7 @@ impl super::Scene {
ConstraintKind,
Vec<ParametricRef>,
Option<DrivingValue>,
Option<Vector3>,
)> = Vec::new();
for (scope_index, set) in self.parametric_constraints.iter().enumerate() {
for c in &set.constraints {
@@ -1685,16 +1788,27 @@ impl super::Scene {
marker: r.marker,
})
.collect();
to_add.push((scope_index, c.kind, new_refs, c.driving_param.clone()));
to_add.push((
scope_index,
c.kind,
new_refs,
c.driving_param.clone(),
c.axis_direction,
));
}
}
if to_add.is_empty() {
return;
}
let mut touched: Vec<Handle> = Vec::new();
for (scope_index, kind, refs, driving_param) in to_add {
for (scope_index, kind, refs, driving_param, axis_direction) in to_add {
touched.extend(refs.iter().map(|r| r.entity));
self.parametric_constraints[scope_index].add(kind, refs, driving_param);
self.parametric_constraints[scope_index]
.constraints
.last_mut()
.expect("the copied constraint was just added")
.axis_direction = axis_direction;
}
touched.sort();
touched.dedup();
@@ -1790,6 +1904,7 @@ mod tests {
rigid_points: Vec::new(),
distance_direction_type: 0,
distance_direction: None,
axis_direction: None,
angle_sector: angle_sector::PARALLEL_COUNTERCLOCKWISE,
};
let (anchor, direction) =
@@ -1825,6 +1940,7 @@ mod tests {
rigid_points: Vec::new(),
distance_direction_type: 0,
distance_direction: None,
axis_direction: None,
angle_sector: angle_sector::PARALLEL_COUNTERCLOCKWISE,
};
let tangent = relation(
@@ -2213,18 +2329,34 @@ mod tests {
vec![ParametricRef::whole(h(1))],
None,
);
assert!(!scene.should_display_parametric_constraint(scope, id, false, 3));
assert!(scene.should_display_parametric_constraint(scope, id, true, 2));
assert!(!scene.should_display_parametric_constraint(scope, id, true, 1));
assert!(!scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, false, 3, 4095
));
assert!(scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, true, 2, 4095
));
assert!(!scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, true, 1, 4095
));
scene.note_parametric_constraint_applied(scope, id, 1);
assert!(scene.should_display_parametric_constraint(scope, id, false, 0));
assert!(scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, false, 0, 4095
));
scene.set_parametric_constraint_visibility(scope, None, false, false);
assert!(!scene.should_display_parametric_constraint(scope, id, true, 3));
assert!(!scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, true, 3, 4095
));
scene.set_parametric_constraint_visibility(scope, None, false, true);
assert!(scene.should_display_parametric_constraint(scope, id, false, 0));
assert!(scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, false, 0, 4095
));
scene.note_parametric_constraint_applied(scope, id, 0);
assert!(!scene.should_display_parametric_constraint(scope, id, false, 3));
assert!(scene.should_display_parametric_constraint(scope, id, true, 2));
assert!(!scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, false, 3, 4095
));
assert!(scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, true, 2, 4095
));
}
#[test]
@@ -2238,7 +2370,9 @@ mod tests {
);
scene.hidden_parametric_constraints.insert((scope, id));
assert!(!scene.should_display_parametric_constraint(scope, id, true, 2));
assert!(!scene.should_display_parametric_constraint(
scope, id, ConstraintKind::Horizontal, true, 2, 4095
));
}
#[test]
@@ -2313,4 +2447,37 @@ mod tests {
vec![h(1), h(2), h(3)]
);
}
#[test]
fn duplicating_an_axis_constraint_keeps_its_direction() {
let mut scene = super::super::Scene::new();
let line = |y| {
acadrust::EntityType::Line(acadrust::entities::Line::from_points(
Vector3::new(0.0, y, 0.0),
Vector3::new(4.0, y + 1.0, 0.0),
))
};
let source = scene.add_entity(line(0.0));
let copied = scene.add_entity(line(10.0));
let direction = Vector3::new(3.0, 4.0, 0.0);
scene
.parametric_constraint_set_mut(ParametricScope::ModelSpace)
.add_axis_constraint(
ConstraintKind::Horizontal,
vec![ParametricRef::whole(source)],
direction,
);
let mut handle_map = rustc_hash::FxHashMap::default();
handle_map.insert(source, copied);
scene.duplicate_parametric_constraints_for(&handle_map);
let constraints = &scene
.parametric_constraint_set(ParametricScope::ModelSpace)
.unwrap()
.constraints;
assert_eq!(constraints.len(), 2);
assert_eq!(constraints[1].refs, vec![ParametricRef::whole(copied)]);
assert_eq!(constraints[1].axis_direction, Some(direction.normalize()));
}
}
+669 -85
View File
@@ -513,6 +513,12 @@ fn resolve_constraint_point(
if let Some(point) = geometry.point_for_marker(marker) {
return Some(point);
}
if let Some(segment) = reference
.segment_center_index()
.and_then(|index| geometry.arc_segment(index))
{
return Some(segment.arc.circle.center);
}
let midpoint_line = reference
.segment_midpoint_index()
@@ -794,6 +800,175 @@ fn refs_share_supported_plane(document: &acadrust::CadDocument, refs: &[Parametr
plane_z.is_some()
}
fn concentric_reference_geometry(
document: &acadrust::CadDocument,
reference: ParametricRef,
) -> Option<(Vector3, cadkernel::space::Plane)> {
let marker = reference.marker?;
if marker != -3 && reference.segment_center_index().is_none() {
return None;
}
let entity = document.get_entity(reference.entity)?;
let center = super::parametric_constraints::resolve_point(entity, marker)?;
let plane = crate::entities::curve::entity_curve(entity)?.plane;
Some((center, plane))
}
fn concentric_refs_share_plane(
document: &acadrust::CadDocument,
refs: &[ParametricRef],
) -> bool {
let [first, second] = refs else {
return false;
};
if first == second {
return false;
}
let Some((first_center, first_plane)) = concentric_reference_geometry(document, *first) else {
return false;
};
let Some((second_center, second_plane)) = concentric_reference_geometry(document, *second)
else {
return false;
};
let (Some(first_normal), Some(second_normal)) = (first_plane.normal(), second_plane.normal())
else {
return false;
};
let parallel = (first_normal[0] * second_normal[0]
+ first_normal[1] * second_normal[1]
+ first_normal[2] * second_normal[2])
.abs()
>= 1.0 - 1.0e-9;
let points = [
first_plane.origin,
second_plane.origin,
[first_center.x, first_center.y, first_center.z],
[second_center.x, second_center.y, second_center.z],
];
let tolerance = cadkernel::space::coplanarity_tolerance(&points);
parallel
&& first_plane
.distance_to(second_plane.origin)
.is_some_and(|distance| distance.abs() <= tolerance)
&& first_plane
.distance_to([second_center.x, second_center.y, second_center.z])
.is_some_and(|distance| distance.abs() <= tolerance)
}
fn ref_is_driven(driven: &[ParametricRef], reference: ParametricRef) -> bool {
driven.iter().any(|candidate| {
candidate.entity == reference.entity
&& (candidate.marker == reference.marker || candidate.marker.is_none())
})
}
fn apply_spatial_concentric_constraints(
document: &acadrust::CadDocument,
set: &ParametricConstraintSet,
driven_refs: &[ParametricRef],
initial_fixed_refs: &[ParametricRef],
results: &mut Vec<(Handle, EntityType)>,
) {
let current_entity = |handle: Handle, results: &[(Handle, EntityType)]| {
results
.iter()
.rev()
.find(|(candidate, _)| *candidate == handle)
.map(|(_, entity)| entity.clone())
.or_else(|| document.get_entity(handle).cloned())
};
let mut handles = Vec::<Handle>::new();
let mut relations = Vec::new();
let mut fixed = Vec::new();
let mut points = Vec::new();
for constraint in set.constraints.iter().filter(|constraint| {
constraint.enabled
&& constraint.kind == ConstraintKind::Concentric
&& !refs_share_supported_plane(document, &constraint.refs)
&& concentric_refs_share_plane(document, &constraint.refs)
}) {
let [first, second] = constraint.refs.as_slice() else {
continue;
};
if first.entity == second.entity {
continue;
}
let (Some(first_entity), Some(second_entity)) = (
current_entity(first.entity, results),
current_entity(second.entity, results),
) else {
continue;
};
let (Some(first_marker), Some(second_marker)) = (first.marker, second.marker) else {
continue;
};
let (Some(first_center), Some(second_center)) = (
super::parametric_constraints::resolve_point(&first_entity, first_marker),
super::parametric_constraints::resolve_point(&second_entity, second_marker),
) else {
continue;
};
let first_index = handles
.iter()
.position(|handle| *handle == first.entity)
.unwrap_or_else(|| {
handles.push(first.entity);
handles.len() - 1
});
let second_index = handles
.iter()
.position(|handle| *handle == second.entity)
.unwrap_or_else(|| {
handles.push(second.entity);
handles.len() - 1
});
let first_point = [first_center.x, first_center.y, first_center.z];
let second_point = [second_center.x, second_center.y, second_center.z];
relations.push((first_index, first_point, second_index, second_point));
points.extend([first_point, second_point]);
if ref_is_driven(driven_refs, *first) || ref_is_driven(initial_fixed_refs, *first) {
fixed.push(first_index);
}
if ref_is_driven(driven_refs, *second) || ref_is_driven(initial_fixed_refs, *second) {
fixed.push(second_index);
}
}
if relations.is_empty() {
return;
}
fixed.sort_unstable();
fixed.dedup();
let tolerance = cadkernel::space::coplanarity_tolerance(&points).max(MOVE_EPS);
let Some(translations) = cadkernel::space::solve_rigid_point_coincidence(
handles.len(),
&relations,
&fixed,
tolerance,
) else {
return;
};
for (handle, translation) in handles.into_iter().zip(translations) {
let translation = glam::DVec3::from_array(translation);
if translation.length() <= tolerance {
continue;
}
let Some(mut entity) = current_entity(handle, results) else {
continue;
};
crate::scene::view::dispatch::apply_transform(
&mut entity,
&crate::command::EntityTransform::Translate(translation),
);
if let Some((_, current)) = results.iter_mut().find(|(candidate, _)| *candidate == handle) {
*current = entity;
} else {
results.push((handle, entity));
}
}
}
fn resolved_target(params: &ParameterTable, constraint: &ParametricConstraint) -> Option<f64> {
let value = constraint.driving_param.as_ref()?.resolve(params).ok()?;
if !value.is_finite() {
@@ -901,6 +1076,37 @@ fn build_constraint(
let point_ref = |sys: &mut System, cache: &mut HashMap<_, _>, r: ParametricRef| {
resolve_constraint_point(document, sys, cache, r)
};
let directional_line =
|sys: &mut System, cache: &mut HashMap<_, _>, r: ParametricRef| {
let geometry = resolve_ref(document, sys, cache, r)?;
let minor_axis = matches!(
r.directional_axis(),
Some(super::parametric_constraints::DirectionalAxis::EllipseMinor)
);
let line = match geometry {
EntityGeom::TextLine(line)
if matches!(
r.directional_axis(),
Some(super::parametric_constraints::DirectionalAxis::TextBaseline)
) => line,
EntityGeom::Line(line) | EntityGeom::Ray(line) | EntityGeom::XLine(line)
if r.marker.is_none() => line,
EntityGeom::Polyline { .. } => geometry.line_segment(r.segment_index()?)?,
EntityGeom::Ellipse(ellipse)
if matches!(
r.directional_axis(),
Some(
super::parametric_constraints::DirectionalAxis::EllipseMajor
| super::parametric_constraints::DirectionalAxis::EllipseMinor
)
) => GLine {
p1: ellipse.center,
p2: ellipse.focus1,
},
_ => return None,
};
Some((line, minor_axis))
};
let point_on_bounded_arc = |sys: &mut System, point: GPoint, arc: GArc| {
let initial = BoundedArcValue::initial_parameter(sys.store(), point, arc);
@@ -933,30 +1139,49 @@ fn build_constraint(
ConstraintKind::Coincident | ConstraintKind::Concentric | ConstraintKind::CenterPoint => {
point_pair_equal(sys, cache, &c.refs)
}
ConstraintKind::Horizontal => match c.refs.as_slice() {
[r] => whole_line(sys, cache, *r)
.map(|line| {
vec![Rc::new(Equal::new(line.p1.y, line.p2.y, 1.0)) as Rc<dyn Constraint>]
ConstraintKind::Horizontal | ConstraintKind::Vertical => {
let fallback = if c.kind == ConstraintKind::Vertical {
Vector3::UNIT_Y
} else {
Vector3::UNIT_X
};
let direction = c.axis_direction.unwrap_or(fallback);
let length = direction.x.hypot(direction.y);
let (dx, dy) = if length > 1.0e-12 {
(direction.x / length, direction.y / length)
} else {
(fallback.x, fallback.y)
};
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)),
};
match c.refs.as_slice() {
[reference] => directional_line(sys, cache, *reference)
.map(|(line, minor_axis)| {
if minor_axis {
vec![Rc::new(PerpendicularConstraint::new(
sys.store(),
line,
datum,
)) as Rc<dyn Constraint>]
} else {
vec![Rc::new(ParallelConstraint::new(sys.store(), line, datum))
as Rc<dyn Constraint>]
}
})
.unwrap_or_default(),
[a, b] => match (point_ref(sys, cache, *a), point_ref(sys, cache, *b)) {
(Some(a), Some(b)) => vec![Rc::new(Equal::new(a.y, b.y, 1.0))],
(Some(a), Some(b)) => vec![Rc::new(ParallelConstraint::new(
sys.store(),
GLine { p1: a, p2: b },
datum,
))],
_ => Vec::new(),
},
_ => Vec::new(),
},
ConstraintKind::Vertical => match c.refs.as_slice() {
[r] => whole_line(sys, cache, *r)
.map(|line| {
vec![Rc::new(Equal::new(line.p1.x, line.p2.x, 1.0)) as Rc<dyn Constraint>]
})
.unwrap_or_default(),
[a, b] => match (point_ref(sys, cache, *a), point_ref(sys, cache, *b)) {
(Some(a), Some(b)) => vec![Rc::new(Equal::new(a.x, b.x, 1.0))],
_ => Vec::new(),
},
_ => Vec::new(),
},
}
}
ConstraintKind::Parallel => {
let [a, b] = c.refs.as_slice() else {
return Vec::new();
@@ -972,39 +1197,6 @@ fn build_constraint(
let [a, b] = c.refs.as_slice() else {
return Vec::new();
};
let directional_line =
|sys: &mut System, cache: &mut HashMap<_, _>, r: ParametricRef| {
let geometry = resolve_ref(document, sys, cache, r)?;
let minor_axis = matches!(
r.directional_axis(),
Some(super::parametric_constraints::DirectionalAxis::EllipseMinor)
);
let line = match geometry {
EntityGeom::TextLine(line)
if matches!(
r.directional_axis(),
Some(super::parametric_constraints::DirectionalAxis::TextBaseline)
) => line,
EntityGeom::Line(line) | EntityGeom::Ray(line) | EntityGeom::XLine(line)
if r.marker.is_none() => line,
EntityGeom::Polyline { .. } => {
geometry.line_segment(r.segment_index()?)?
}
EntityGeom::Ellipse(ellipse)
if matches!(
r.directional_axis(),
Some(
super::parametric_constraints::DirectionalAxis::EllipseMajor
| super::parametric_constraints::DirectionalAxis::EllipseMinor
)
) => GLine {
p1: ellipse.center,
p2: ellipse.focus1,
},
_ => return None,
};
Some((line, minor_axis))
};
let (Some((fixed, fixed_minor)), Some((moving, moving_minor))) =
(directional_line(sys, cache, *a), directional_line(sys, cache, *b))
else {
@@ -1697,26 +1889,167 @@ fn build_constraint(
}
}
fn smooth_target_jet(entity: &EntityType, marker: i32) -> Option<cadkernel::space::CurveJet> {
let parameter = match marker {
0 => 0.0,
1 => 1.0,
fn smooth_refs(refs: &[ParametricRef]) -> Option<(ParametricRef, ParametricRef, ParametricRef)> {
match refs {
[source, target_endpoint] => Some((
*source,
*target_endpoint,
ParametricRef::whole(target_endpoint.entity),
)),
[source, target_endpoint, target_curve]
if target_endpoint.entity == target_curve.entity =>
{
Some((*source, *target_endpoint, *target_curve))
}
_ => None,
}
}
fn smooth_target_planar_curve(
entity: &EntityType,
curve_reference: ParametricRef,
) -> Option<cadkernel::space::PlanarCurve> {
let planar = crate::entities::curve::entity_curve(entity)?;
let Some(segment) = curve_reference.segment_index() else {
return (!planar.is_closed()).then_some(planar);
};
let curve = planar.curve.segments().into_iter().nth(segment)?;
Some(cadkernel::space::PlanarCurve::new(planar.plane, curve))
}
fn smooth_endpoint_parameter(
entity: &EntityType,
endpoint_reference: ParametricRef,
curve: &cadkernel::space::PlanarCurve,
) -> Option<f64> {
let marker = endpoint_reference.marker?;
let endpoint = super::parametric_constraints::resolve_point(entity, marker)?;
let endpoint = cadkernel::space::Vec3::new(endpoint.x, endpoint.y, endpoint.z);
let start = cadkernel::space::Vec3::from(curve.point_at(0.0));
let end = cadkernel::space::Vec3::from(curve.point_at(1.0));
Some(if endpoint.distance(start) <= endpoint.distance(end) {
0.0
} else {
1.0
})
}
fn smooth_target_jet(
entity: &EntityType,
endpoint_reference: ParametricRef,
curve_reference: ParametricRef,
) -> Option<cadkernel::space::CurveJet> {
if curve_reference.segment_index().is_none() {
if let EntityType::Spline(spline) = entity {
let endpoint = match endpoint_reference.marker {
Some(0) => cadkernel::space::SplineEnd::Start,
Some(1) => cadkernel::space::SplineEnd::End,
_ => return None,
};
let curve = crate::entities::curve::entity_curve(entity)?;
if curve.is_closed() {
return None;
let nurbs = crate::entities::spline::nurbs3(spline)?;
return cadkernel::space::CurveJet::from_nurbs(&nurbs, endpoint);
}
let step = if marker == 0 { 1.0e-4 } else { -1.0e-4 };
}
let curve = smooth_target_planar_curve(entity, curve_reference)?;
let parameter = smooth_endpoint_parameter(entity, endpoint_reference, &curve)?;
let point = curve.point_at(parameter);
let tangent = curve.tangent_at(parameter);
let next = curve.point_at(parameter + step);
let third = curve.point_at(parameter + 2.0 * step);
Some(cadkernel::space::CurveJet {
match &curve.curve {
cadkernel::geom2d::Curve::Line(_) => {
cadkernel::space::CurveJet::linear(point, tangent)
}
cadkernel::geom2d::Curve::Arc(arc) => cadkernel::space::CurveJet::circular(
point,
tangent,
curvature: cadkernel::space::curve::curvature_through(point, next, third),
})
curve.plane.point_at(arc.centre),
),
_ => None,
}
}
fn smooth_spline_plane(spline: &acadrust::entities::Spline) -> Option<cadkernel::space::Plane> {
let source = if crate::entities::spline::uses_fit_method(spline) {
&spline.fit_points
} else {
&spline.control_points
};
let origin = source.first()?;
let origin_vector = cadkernel::space::Vec3::new(origin.x, origin.y, origin.z);
let along = source
.iter()
.skip(1)
.map(|point| cadkernel::space::Vec3::new(point.x, point.y, point.z) - origin_vector)
.find(|vector| vector.length_squared() > 1.0e-24)?;
let normal = source
.iter()
.skip(1)
.map(|point| cadkernel::space::Vec3::new(point.x, point.y, point.z) - origin_vector)
.map(|vector| along.cross(vector))
.find(|vector| vector.length_squared() > 1.0e-24)?;
let plane = cadkernel::space::Plane::orthonormal(
origin_vector.to_array(),
along.to_array(),
normal.to_array(),
)?;
let points: Vec<_> = source.iter().map(|point| [point.x, point.y, point.z]).collect();
let tolerance = cadkernel::space::coplanarity_tolerance(&points);
source
.iter()
.all(|point| plane.contains([point.x, point.y, point.z], tolerance))
.then_some(plane)
}
fn smooth_entity_plane(
entity: &EntityType,
curve_reference: ParametricRef,
) -> Option<cadkernel::space::Plane> {
if let EntityType::Spline(spline) = entity {
return crate::entities::curve::entity_curve(entity)
.map(|curve| curve.plane)
.or_else(|| smooth_spline_plane(spline));
}
smooth_target_planar_curve(entity, curve_reference).map(|curve| curve.plane)
}
fn smooth_refs_share_plane(
document: &acadrust::CadDocument,
source_ref: ParametricRef,
target_curve_ref: ParametricRef,
) -> bool {
let Some(source_entity) = document.get_entity(source_ref.entity) else {
return false;
};
let Some(source_plane) = smooth_entity_plane(source_entity, ParametricRef::whole(source_ref.entity))
else {
return false;
};
let Some(target_entity) = document.get_entity(target_curve_ref.entity) else {
return false;
};
let Some(target_plane) = smooth_entity_plane(target_entity, target_curve_ref) else {
return false;
};
let points = [source_plane.origin, target_plane.origin];
let tolerance = cadkernel::space::coplanarity_tolerance(&points);
if let EntityType::Line(line) = target_entity {
return source_plane
.contains([line.start.x, line.start.y, line.start.z], tolerance)
&& source_plane
.contains([line.end.x, line.end.y, line.end.z], tolerance);
}
let (Some(source_normal), Some(target_normal)) =
(source_plane.normal(), target_plane.normal())
else {
return false;
};
cadkernel::space::Vec3::from(source_normal)
.cross(cadkernel::space::Vec3::from(target_normal))
.length()
<= 1.0e-9
&& source_plane.contains(target_plane.origin, tolerance)
&& target_plane.contains(source_plane.origin, tolerance)
}
fn apply_smooth_constraints(
@@ -1729,7 +2062,9 @@ fn apply_smooth_constraints(
.iter()
.filter(|constraint| constraint.enabled && constraint.kind == ConstraintKind::Smooth)
{
let [source_ref, target_ref] = constraint.refs.as_slice() else {
let Some((source_ref, target_ref, target_curve_ref)) =
smooth_refs(&constraint.refs)
else {
continue;
};
let source = results
@@ -1750,10 +2085,7 @@ fn apply_smooth_constraints(
Some(1) => cadkernel::space::SplineEnd::End,
_ => continue,
};
let Some(target_marker) = target_ref.marker else {
continue;
};
let Some(target_jet) = smooth_target_jet(&target, target_marker) else {
let Some(target_jet) = smooth_target_jet(&target, target_ref, target_curve_ref) else {
continue;
};
let Some(curve) = crate::entities::spline::nurbs3(&spline) else {
@@ -1842,6 +2174,7 @@ fn polyline_ref_order(
}
let position = if let Some(index) = reference.segment_index()
.or_else(|| reference.segment_midpoint_index())
.or_else(|| reference.segment_center_index())
{
2 * index + 1
} else {
@@ -1868,7 +2201,21 @@ fn constrained_line_axes(constraints: &[&ParametricConstraint]) -> HashMap<Param
for c in constraints.iter().filter(|c| c.enabled) {
if let [reference] = c.refs.as_slice() {
if matches!(c.kind, ConstraintKind::Horizontal | ConstraintKind::Vertical) {
axes.insert(*reference, c.kind == ConstraintKind::Vertical);
let fallback = if c.kind == ConstraintKind::Vertical {
Vector3::UNIT_Y
} else {
Vector3::UNIT_X
};
let direction = c.axis_direction.unwrap_or(fallback);
let length = direction.x.hypot(direction.y);
if length > 1.0e-12 {
let (x, y) = (direction.x.abs() / length, direction.y.abs() / length);
if x >= 1.0 - 1.0e-10 {
axes.insert(*reference, false);
} else if y >= 1.0 - 1.0e-10 {
axes.insert(*reference, true);
}
}
}
}
}
@@ -1976,6 +2323,7 @@ fn solve_scope(
rigid_points: Vec::new(),
distance_direction_type: distance_direction_type::UNDIRECTED,
distance_direction: None,
axis_direction: None,
angle_sector: angle_sector::PARALLEL_COUNTERCLOCKWISE,
};
for constraint in build_constraint(
@@ -1993,7 +2341,13 @@ fn solve_scope(
let has_smooth = constraints.iter()
.any(|constraint| constraint.enabled && constraint.kind == ConstraintKind::Smooth);
if cache.is_empty() && !has_smooth {
let has_spatial_concentric = constraints.iter().any(|constraint| {
constraint.enabled
&& constraint.kind == ConstraintKind::Concentric
&& !refs_share_supported_plane(document, &constraint.refs)
&& concentric_refs_share_plane(document, &constraint.refs)
});
if cache.is_empty() && !has_smooth && !has_spatial_concentric {
return None;
}
@@ -2123,7 +2477,7 @@ fn solve_scope(
for (handle, geom) in &cache {
if initial_fixed_refs
.iter()
.any(|reference| reference.entity == *handle)
.any(|reference| reference.entity == *handle && reference.marker.is_none())
{
continue;
}
@@ -2295,7 +2649,12 @@ fn solve_scope(
};
let directional = set.constraints.iter().any(|constraint| {
constraint.enabled
&& constraint.kind == ConstraintKind::Perpendicular
&& matches!(
constraint.kind,
ConstraintKind::Horizontal
| ConstraintKind::Vertical
| ConstraintKind::Perpendicular
)
&& constraint.refs.iter().any(|reference| {
reference.entity == *handle && reference.directional_axis().is_some()
})
@@ -2336,7 +2695,12 @@ fn solve_scope(
};
let directional = set.constraints.iter().any(|constraint| {
constraint.enabled
&& constraint.kind == ConstraintKind::Perpendicular
&& matches!(
constraint.kind,
ConstraintKind::Horizontal
| ConstraintKind::Vertical
| ConstraintKind::Perpendicular
)
&& constraint.refs.iter().any(|reference| {
reference.entity == *handle
&& matches!(
@@ -2821,8 +3185,8 @@ fn solve_scope(
}
}
(EntityType::Spline(spline), EntityGeom::Spline { curve, control_z }) => {
let mut changed =
spline.fit_points.len() > 0 || spline.control_points.len() != curve.poles.len();
let mut changed = crate::entities::spline::uses_fit_method(spline)
|| spline.control_points.len() != curve.poles.len();
let control_points: Vec<_> = curve
.poles
.iter()
@@ -2839,11 +3203,25 @@ fn solve_scope(
.collect();
if changed {
let mut updated = spline.clone();
if crate::entities::spline::uses_fit_method(spline) {
updated.cv_frame_visible = true;
}
updated.degree = curve.degree as i32;
updated.knots = curve.knots.clone();
updated.control_points = control_points;
updated.weights = curve.weights.iter().map(|id| store.get(*id)).collect();
updated.fit_points.clear();
if !updated.fit_points.is_empty() {
if let (Some(first), Some(point)) =
(updated.fit_points.first_mut(), updated.control_points.first())
{
*first = *point;
}
if let (Some(last), Some(point)) =
(updated.fit_points.last_mut(), updated.control_points.last())
{
*last = *point;
}
}
updated.begin_tangent = Vector3::ZERO;
updated.end_tangent = Vector3::ZERO;
updated.flags.rational = updated
@@ -2859,6 +3237,13 @@ fn solve_scope(
}
}
apply_smooth_constraints(document, set, &mut results);
apply_spatial_concentric_constraints(
document,
set,
driven_refs,
initial_fixed_refs,
&mut results,
);
Some((results, dof, conflicts))
}
@@ -2871,13 +3256,8 @@ impl Scene {
refs: &[ParametricRef],
driving_param: Option<&super::named_parameters::DrivingValue>,
) -> Result<(), &'static str> {
if !refs_share_supported_plane(&self.document, refs) {
return Err(
"Constraint references must be supported entities on the same world-XY plane.",
);
}
if kind == ConstraintKind::Smooth {
let [source_ref, target_ref] = refs else {
let Some((source_ref, target_ref, target_curve_ref)) = smooth_refs(refs) else {
return Err("Smooth requires one spline endpoint and one target endpoint.");
};
if source_ref.entity == target_ref.entity {
@@ -2895,13 +3275,16 @@ impl Scene {
Some(1) => cadkernel::space::SplineEnd::End,
_ => return Err("Smooth requires a spline endpoint."),
};
let Some(target_marker) = target_ref.marker else {
let Some(_) = target_ref.marker else {
return Err("Smooth requires a target endpoint.");
};
let Some(target) = self.document.get_entity(target_ref.entity) else {
return Err("Smooth target does not exist.");
};
let Some(target_jet) = smooth_target_jet(target, target_marker) else {
if !smooth_refs_share_plane(&self.document, source_ref, target_curve_ref) {
return Err("Smooth requires both curves to lie on the same plane.");
}
let Some(target_jet) = smooth_target_jet(target, target_ref, target_curve_ref) else {
return Err("The selected target does not support endpoint smoothing.");
};
let Some(curve) = crate::entities::spline::nurbs3(spline) else {
@@ -2912,6 +3295,26 @@ impl Scene {
}
return Ok(());
}
if kind == ConstraintKind::Concentric {
if !concentric_refs_share_plane(&self.document, refs) {
return Err(
"Concentric requires two supported circular curves on the same plane.",
);
}
if !refs_share_supported_plane(&self.document, refs) {
if refs[0].entity == refs[1].entity {
return Err(
"Concentric cannot move two curved segments of the same object on this plane.",
);
}
return Ok(());
}
}
if !refs_share_supported_plane(&self.document, refs) {
return Err(
"Constraint references must be supported entities on the same world-XY plane.",
);
}
let validation_target = match driving_param {
Some(super::named_parameters::DrivingValue::Named(name))
if !self.named_parameters.contains(name) =>
@@ -2930,6 +3333,7 @@ impl Scene {
rigid_points: Vec::new(),
distance_direction_type: 0,
distance_direction: None,
axis_direction: None,
angle_sector: angle_sector::PARALLEL_COUNTERCLOCKWISE,
};
let mut system = System::new();
@@ -3159,6 +3563,17 @@ mod tests {
use acadrust::entities::EntityType;
use acadrust::types::Vector3;
fn spatial_circle(center: Vector3, radius: f64) -> acadrust::entities::Circle {
let normal = Vector3::UNIT_Y;
let (x, y, z) = crate::scene::view::transform::wcs_point_to_ocs(
(center.x, center.y, center.z),
(normal.x, normal.y, normal.z),
);
let mut circle = acadrust::entities::Circle::from_coords(x, y, z, radius);
circle.normal = normal;
circle
}
#[test]
fn polyline_constraint_order_follows_stored_vertices_for_open_and_closed_polylines() {
use acadrust::entities::{LwPolyline, LwVertex, Polyline2D, Vertex2D};
@@ -3820,4 +4235,173 @@ mod tests {
assert!(jet.tangent[1].abs() < 1e-9, "jet={jet:?}");
assert!(cadkernel::space::Vec3::from(jet.curvature).length() < 5e-3);
}
#[test]
fn smooth_constraint_uses_the_selected_polyline_arc_curvature() {
let mut scene = Scene::new();
let mut target = acadrust::entities::LwPolyline::new();
target.vertices = vec![
acadrust::entities::LwVertex::with_bulge(
acadrust::types::Vector2::new(0.0, 0.0),
1.0,
),
acadrust::entities::LwVertex::from_coords(10.0, 0.0),
];
let target = scene.add_entity(EntityType::LwPolyline(target));
let mut spline = acadrust::entities::Spline::new();
spline.degree = 3;
spline.control_points = vec![
Vector3::new(2.0, 1.0, 0.0),
Vector3::new(3.0, 2.0, 0.0),
Vector3::new(4.0, 3.0, 0.0),
Vector3::new(5.0, 3.0, 0.0),
];
spline.knots = cadkernel::space::clamped_uniform_knots(3, 4);
let spline = scene.add_entity(EntityType::Spline(spline));
scene
.parametric_constraint_set_mut(ParametricScope::ModelSpace)
.add(
ConstraintKind::Smooth,
vec![
ParametricRef::point(spline, 0),
ParametricRef::point(target, 0),
ParametricRef::segment(target, 0),
],
None,
);
scene.bump_entities(&[(target, super::ChangeKind::Modified)]);
let EntityType::Spline(spline) = scene.document.get_entity(spline).unwrap() else {
panic!("expected spline");
};
let curve = crate::entities::spline::nurbs3(spline).unwrap();
let jet =
cadkernel::space::CurveJet::from_nurbs(&curve, cadkernel::space::SplineEnd::Start)
.unwrap();
assert!(cadkernel::space::Vec3::from(jet.point).length() < 1.0e-9);
assert!(jet.tangent[0].abs() < 1.0e-9, "jet={jet:?}");
assert!(
(cadkernel::space::Vec3::from(jet.curvature).length() - 0.2).abs() < 2.0e-4,
"jet={jet:?}"
);
}
#[test]
fn smooth_constraint_accepts_a_stale_normal_on_an_arbitrary_plane() {
let mut scene = Scene::new();
let target = scene.add_entity(EntityType::Line(
acadrust::entities::Line::from_points(
Vector3::new(0.0, 0.0, 1.0),
Vector3::new(5.0, 0.0, 1.0),
),
));
let mut source = acadrust::entities::Spline::new();
source.degree = 3;
source.normal = Vector3::UNIT_Z;
source.control_points = vec![
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(2.0, 0.0, 2.0),
Vector3::new(4.0, 0.0, 2.0),
Vector3::new(5.0, 0.0, 3.0),
];
source.knots = cadkernel::space::clamped_uniform_knots(3, 4);
let source = scene.add_entity(EntityType::Spline(source));
let refs = vec![
ParametricRef::point(source, 0),
ParametricRef::point(target, 0),
];
assert!(scene
.validate_parametric_constraint(ConstraintKind::Smooth, &refs, None)
.is_ok());
scene
.parametric_constraint_set_mut(ParametricScope::ModelSpace)
.add(ConstraintKind::Smooth, refs, None);
scene.bump_entities(&[(target, super::ChangeKind::Modified)]);
let EntityType::Spline(source) = scene.document.get_entity(source).unwrap() else {
panic!("expected spline");
};
let curve = crate::entities::spline::nurbs3(source).unwrap();
let jet =
cadkernel::space::CurveJet::from_nurbs(&curve, cadkernel::space::SplineEnd::Start)
.unwrap();
assert!(cadkernel::space::Vec3::from(jet.point)
.distance(cadkernel::space::Vec3::new(0.0, 0.0, 1.0))
< 1.0e-9);
assert!(jet.tangent[1].abs() < 1.0e-9 && jet.tangent[2].abs() < 1.0e-9);
}
#[test]
fn spatial_concentric_initial_solve_keeps_the_first_circle_fixed() {
let mut scene = Scene::new();
let first = scene.add_entity(EntityType::Circle(spatial_circle(Vector3::ZERO, 2.0)));
let second = scene.add_entity(EntityType::Circle(spatial_circle(
Vector3::new(5.0, 0.0, 3.0),
4.0,
)));
let first_ref = ParametricRef::center(first);
let second_ref = ParametricRef::center(second);
scene
.parametric_constraint_set_mut(ParametricScope::ModelSpace)
.add(
ConstraintKind::Concentric,
vec![first_ref, second_ref],
None,
);
scene.bump_entities_with_initial_parametric_policy(
&[
(first, super::ChangeKind::Modified),
(second, super::ChangeKind::Modified),
],
&[first_ref],
true,
);
let EntityType::Circle(first_circle) = scene.document.get_entity(first).unwrap() else {
panic!("expected circle");
};
let EntityType::Circle(second_circle) = scene.document.get_entity(second).unwrap() else {
panic!("expected circle");
};
assert!(first_circle.center_wcs().length() < 1.0e-9);
assert!(second_circle.center_wcs().length() < 1.0e-9);
assert!((second_circle.radius - 4.0).abs() < 1.0e-12);
}
#[test]
fn spatial_concentric_chain_follows_the_driven_end() {
let mut scene = Scene::new();
let handles = [1.0, 2.0, 3.0].map(|radius| {
scene.add_entity(EntityType::Circle(spatial_circle(Vector3::ZERO, radius)))
});
let set = scene.parametric_constraint_set_mut(ParametricScope::ModelSpace);
set.add(
ConstraintKind::Concentric,
vec![ParametricRef::center(handles[0]), ParametricRef::center(handles[1])],
None,
);
set.add(
ConstraintKind::Concentric,
vec![ParametricRef::center(handles[1]), ParametricRef::center(handles[2])],
None,
);
let driven_center = Vector3::new(8.0, 0.0, -3.0);
*scene.document.get_entity_mut(handles[2]).unwrap() =
EntityType::Circle(spatial_circle(driven_center, 3.0));
scene.bump_entities_with_parametric_driven(
&[(handles[2], super::ChangeKind::Modified)],
&[ParametricRef::whole(handles[2])],
);
for handle in handles {
let EntityType::Circle(circle) = scene.document.get_entity(handle).unwrap() else {
panic!("expected circle");
};
assert!((circle.center_wcs() - driven_center).length() < 1.0e-9);
}
}
}
+171 -36
View File
@@ -2765,66 +2765,118 @@ impl WirePlane {
}
fn wire_plane(wire: &WireModel) -> Option<WirePlane> {
let [geom] = wire.tangent_geoms.as_slice() else {
return None;
};
let (origin, axis_x, axis_y) = match geom {
TangentGeom::Circle { center, .. } => (DVec3::new(center[0] as f64, center[1] as f64, center[2] as f64), DVec3::X, DVec3::Y),
TangentGeom::PlanarCircle { center, axis_x, axis_y, .. } | TangentGeom::Arc { center, axis_x, axis_y, .. } => (
for geom in &wire.tangent_geoms {
let plane_axes = match geom {
TangentGeom::Circle { center, .. } => Some((
DVec3::new(center[0] as f64, center[1] as f64, center[2] as f64),
DVec3::X,
DVec3::Y,
)),
TangentGeom::PlanarCircle { center, axis_x, axis_y, .. }
| TangentGeom::Arc { center, axis_x, axis_y, .. } => Some((
DVec3::new(center[0], center[1], center[2]),
DVec3::new(axis_x[0], axis_x[1], axis_x[2]),
DVec3::new(axis_y[0], axis_y[1], axis_y[2]),
),
)),
TangentGeom::PlanarEllipse { center, major_axis, normal, .. } => {
let origin = DVec3::new(center[0], center[1], center[2]);
let n = DVec3::new(normal[0], normal[1], normal[2]).normalize();
let major = DVec3::new(major_axis[0], major_axis[1], major_axis[2]);
if major.length() <= 1e-12 {
return None;
None
} else {
Some((origin, major.normalize(), n.cross(major.normalize())))
}
(origin, major.normalize(), n.cross(major.normalize()))
}
TangentGeom::Line { .. } => return None,
TangentGeom::Line { .. } => None,
};
Some(WirePlane { origin, axis_x, axis_y, normal: axis_x.cross(axis_y).normalize() })
if let Some((origin, axis_x, axis_y)) = plane_axes {
return Some(WirePlane { origin, axis_x, axis_y, normal: axis_x.cross(axis_y).normalize() });
}
}
None
}
fn curve_in_frame(wire: &WireModel, frame: &WirePlane, tol: f64) -> Option<Curve> {
fn tangent_line_endpoints(
wire: &WireModel,
p1: [f32; 3],
p2: [f32; 3],
) -> (DVec3, DVec3) {
if wire.points.len() == 2 && wire.tangent_geoms.len() == 1 {
return (wp_f64(wire, 0), wp_f64(wire, 1));
}
let matches = |vertex: [f64; 3], point: [f32; 3]| {
(vertex[0] as f32 - point[0]).abs() < 1e-3
&& (vertex[1] as f32 - point[1]).abs() < 1e-3
&& (vertex[2] as f32 - point[2]).abs() < 1e-3
};
let count = wire.key_vertices.len();
if count >= 2 {
for start in 0..count {
let end = (start + 1) % count;
if matches(wire.key_vertices[start], p1) && matches(wire.key_vertices[end], p2) {
return (
DVec3::from_array(wire.key_vertices[start]),
DVec3::from_array(wire.key_vertices[end]),
);
}
}
}
(
Vec3::from_array(p1).as_dvec3(),
Vec3::from_array(p2).as_dvec3(),
)
}
fn curves_in_frame(wire: &WireModel, frame: &WirePlane, tol: f64) -> Option<Vec<Curve>> {
use cadkernel::geom2d::{Arc as KArc, Circle as KCircle, Ellipse as KEllipse, EllipseArc as KEllipseArc, Line as KLine};
let mut curves = Vec::new();
if wire.tangent_geoms.is_empty() {
if wire.points.len() != 2 {
return None;
}
let (p0, p1) = (wp_f64(wire, 0), wp_f64(wire, 1));
return (frame.contains(p0, tol) && frame.contains(p1, tol)).then(|| Curve::Line(KLine { start: frame.to_2d(p0), end: frame.to_2d(p1) }));
if !frame.contains(p0, tol) || !frame.contains(p1, tol) {
return None;
}
return Some(vec![Curve::Line(KLine {
start: frame.to_2d(p0),
end: frame.to_2d(p1),
})]);
}
let [geom] = wire.tangent_geoms.as_slice() else {
return None;
};
let angle_in_frame = |world_point: DVec3, centre: DVec3| {
let (p2, c2) = (frame.to_2d(world_point), frame.to_2d(centre));
(p2[1] - c2[1]).atan2(p2[0] - c2[0])
};
for geom in &wire.tangent_geoms {
match geom {
TangentGeom::Line { p1, p2 } => {
let (p1, p2) = if wire.points.len() == 2 {
(wp_f64(wire, 0), wp_f64(wire, 1))
} else {
(Vec3::from_array(*p1).as_dvec3(), Vec3::from_array(*p2).as_dvec3())
};
(frame.contains(p1, tol) && frame.contains(p2, tol)).then(|| Curve::Line(KLine { start: frame.to_2d(p1), end: frame.to_2d(p2) }))
let (p1, p2) = tangent_line_endpoints(wire, *p1, *p2);
if !frame.contains(p1, tol) || !frame.contains(p2, tol) {
return None;
}
curves.push(Curve::Line(KLine { start: frame.to_2d(p1), end: frame.to_2d(p2) }));
}
TangentGeom::Circle { center, radius } => {
let c = DVec3::new(center[0] as f64, center[1] as f64, center[2] as f64);
(DVec3::Z.cross(frame.normal).length() <= tol && frame.contains(c, tol)).then(|| Curve::Circle(KCircle { centre: frame.to_2d(c), radius: *radius as f64 }))
if DVec3::Z.cross(frame.normal).length() > tol || !frame.contains(c, tol) {
return None;
}
curves.push(Curve::Circle(KCircle { centre: frame.to_2d(c), radius: *radius as f64 }));
}
TangentGeom::PlanarCircle { center, axis_x, axis_y, radius } => {
let c = DVec3::new(center[0], center[1], center[2]);
let n = DVec3::new(axis_x[0], axis_x[1], axis_x[2]).cross(DVec3::new(axis_y[0], axis_y[1], axis_y[2])).normalize();
(n.cross(frame.normal).length() <= tol && frame.contains(c, tol)).then(|| Curve::Circle(KCircle { centre: frame.to_2d(c), radius: *radius }))
if n.cross(frame.normal).length() > tol || !frame.contains(c, tol) {
return None;
}
curves.push(Curve::Circle(KCircle { centre: frame.to_2d(c), radius: *radius }));
}
TangentGeom::Arc { center, axis_x, axis_y, radius, start_angle, end_angle } => {
let c = DVec3::new(center[0], center[1], center[2]);
@@ -2836,13 +2888,13 @@ fn curve_in_frame(wire: &WireModel, frame: &WirePlane, tol: f64) -> Option<Curve
let arc = KArc { centre: frame.to_2d(c), radius: *radius, start_angle: *start_angle, end_angle: *end_angle };
let sweep = arc.sweep();
if (sweep - std::f64::consts::TAU).abs() <= 1e-12 {
return Some(Curve::Circle(KCircle { centre: arc.centre, radius: *radius }));
}
curves.push(Curve::Circle(KCircle { centre: arc.centre, radius: *radius }));
} else {
let boundary = if n.dot(frame.normal) < 0.0 { *end_angle } else { *start_angle };
let start_angle = angle_in_frame(c + *radius * (boundary.cos() * ax + boundary.sin() * ay), c);
Some(Curve::Arc(KArc { start_angle, end_angle: start_angle + sweep, ..arc }))
curves.push(Curve::Arc(KArc { start_angle, end_angle: start_angle + sweep, ..arc }));
}
}
TangentGeom::PlanarEllipse { center, major_axis, normal, minor_axis_ratio, start_param, end_param } => {
let c = DVec3::new(center[0], center[1], center[2]);
let ell_normal = DVec3::new(normal[0], normal[1], normal[2]).normalize();
@@ -2866,30 +2918,49 @@ fn curve_in_frame(wire: &WireModel, frame: &WirePlane, tol: f64) -> Option<Curve
} else {
(*start_param, *end_param)
};
Some(Curve::Ellipse(KEllipseArc {
curves.push(Curve::Ellipse(KEllipseArc {
ellipse: KEllipse { centre: frame.to_2d(c), major_radius, minor_radius, major_axis: major_axis_2d },
start_parameter,
end_parameter,
}))
}));
}
}
}
fn exact_curve_intersections(wire_a: &WireModel, wire_b: &WireModel) -> Option<Vec<DVec3>> {
Some(curves)
}
pub(crate) fn exact_curve_intersections(
wire_a: &WireModel,
wire_b: &WireModel,
) -> Option<Vec<DVec3>> {
let frame = wire_plane(wire_a).or_else(|| wire_plane(wire_b))?;
const PLANE_TOL: f64 = 1e-7;
let curve_a = curve_in_frame(wire_a, &frame, PLANE_TOL)?;
let curve_b = curve_in_frame(wire_b, &frame, PLANE_TOL)?;
let curves_a = curves_in_frame(wire_a, &frame, PLANE_TOL)?;
let curves_b = curves_in_frame(wire_b, &frame, PLANE_TOL)?;
// Two lines have nothing this path can improve on (the segment sweep is
// already exact for a straight pair); avoid the extra work.
if matches!(curve_a, Curve::Line(_)) && matches!(curve_b, Curve::Line(_)) {
let a_all_lines = curves_a.iter().all(|c| matches!(c, Curve::Line(_)));
let b_all_lines = curves_b.iter().all(|c| matches!(c, Curve::Line(_)));
if a_all_lines && b_all_lines {
return None;
}
let tolerance = cadkernel::geom2d::Tolerance::new(1e-9_f64.max(PLANE_TOL));
let crossings = cadkernel::geom2d::intersect(&curve_a, &curve_b, tolerance);
let points: Vec<DVec3> = crossings.into_iter().map(|c| frame.to_3d(c.point)).collect();
let mut points: Vec<DVec3> = Vec::new();
for ca in &curves_a {
for cb in &curves_b {
let crossings = cadkernel::geom2d::intersect(ca, cb, tolerance);
for c in crossings {
let pt = frame.to_3d(c.point);
if !points.iter().any(|existing| existing.distance_squared(pt) <= 1e-12) {
points.push(pt);
}
}
}
}
Some(points)
}
@@ -4182,4 +4253,68 @@ mod ext_tests {
assert!((res.world.y - 0.5).abs() < 1e-9, "y rounds to 0.5: {:?}", res.world);
}
#[test]
fn exact_curve_intersections_handles_multisegment_polyline_against_circle_at_vertex() {
let polyline = WireModel {
key_vertices: vec![[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 10.0, 0.0]],
tangent_geoms: vec![
TangentGeom::Line { p1: [-10.0, 0.0, 0.0], p2: [0.0, 0.0, 0.0] },
TangentGeom::Line { p1: [0.0, 0.0, 0.0], p2: [0.0, 10.0, 0.0] },
],
..Default::default()
};
let circle = WireModel {
tangent_geoms: vec![TangentGeom::PlanarCircle {
center: [0.0, 5.0, 0.0],
axis_x: [1.0, 0.0, 0.0],
axis_y: [0.0, 1.0, 0.0],
radius: 5.0,
}],
..Default::default()
};
let pts = exact_curve_intersections(&polyline, &circle)
.expect("polyline must analytically intersect circle");
assert_eq!(pts.len(), 2, "expected intersections at (0,0) and (0,10), got {pts:?}");
let mut ys: Vec<f64> = pts.iter().map(|p| p.y).collect();
ys.sort_by(f64::total_cmp);
assert!((ys[0] - 0.0).abs() < 1e-9, "expected corner intersection at y=0, got {}", ys[0]);
assert!((ys[1] - 10.0).abs() < 1e-9, "expected endpoint intersection at y=10, got {}", ys[1]);
for p in &pts {
assert!(p.x.abs() < 1e-9, "expected x=0, got {}", p.x);
assert!(p.z.abs() < 1e-9, "expected z=0, got {}", p.z);
}
}
#[test]
fn exact_curve_intersections_handles_polyline_with_bulge_arc_against_circle() {
let polyline = WireModel {
tangent_geoms: vec![
TangentGeom::Line { p1: [-10.0, 0.0, 0.0], p2: [0.0, 0.0, 0.0] },
TangentGeom::Arc {
center: [0.0, 4.0, 0.0],
axis_x: [1.0, 0.0, 0.0],
axis_y: [0.0, 1.0, 0.0],
radius: 4.0,
start_angle: -std::f64::consts::FRAC_PI_2,
end_angle: std::f64::consts::FRAC_PI_2,
},
],
..Default::default()
};
let circle = WireModel {
tangent_geoms: vec![TangentGeom::PlanarCircle {
center: [0.0, 0.0, 0.0],
axis_x: [1.0, 0.0, 0.0],
axis_y: [0.0, 1.0, 0.0],
radius: 5.0,
}],
..Default::default()
};
let pts = exact_curve_intersections(&polyline, &circle)
.expect("polyline with arc must intersect circle");
assert!(!pts.is_empty());
let line_pt = pts.iter().find(|p| (p.x - -5.0).abs() < 1e-9 && p.y.abs() < 1e-9);
assert!(line_pt.is_some(), "expected line crossing at (-5, 0, 0), got {pts:?}");
}
}
+67 -2
View File
@@ -38,12 +38,36 @@ fn constraint_glyph_size(label: &str) -> Size {
if is_compact_coincident_glyph(label) {
return Size::new(COINCIDENT_GLYPH_SIZE, COINCIDENT_GLYPH_SIZE);
}
if label == "G²" {
let side = CONSTRAINT_GLYPH_SIZE + CONSTRAINT_GLYPH_PAD_Y * 2.0;
return Size::new(side, side);
}
let w = label.chars().count() as f32 * CONSTRAINT_GLYPH_SIZE * 0.62
+ CONSTRAINT_GLYPH_PAD_X * 2.0;
let h = CONSTRAINT_GLYPH_SIZE + CONSTRAINT_GLYPH_PAD_Y * 2.0;
Size::new(w, h)
}
fn draw_smooth_constraint_glyph(frame: &mut canvas::Frame, center: Point, color: Color) {
let curve = canvas::Path::new(|builder| {
for step in 0..=16 {
let x = -7.0 + step as f32 * 0.875;
let y = 0.012 * x * x * x;
let point = Point::new(center.x + x, center.y - y);
if step == 0 {
builder.move_to(point);
} else {
builder.line_to(point);
}
}
});
frame.stroke(
&curve,
canvas::Stroke::default().with_color(color).with_width(1.45),
);
frame.fill(&canvas::Path::circle(center, 1.35), color);
}
fn draw_tangent_constraint_glyph(
frame: &mut canvas::Frame,
center: Point,
@@ -60,6 +84,16 @@ fn draw_tangent_constraint_glyph(
frame.stroke(&canvas::Path::line(contact, tangent_end), stroke);
}
fn draw_concentric_constraint_glyph(
frame: &mut canvas::Frame,
center: Point,
color: Color,
) {
let stroke = canvas::Stroke::default().with_color(color).with_width(1.25);
frame.stroke(&canvas::Path::circle(center, 4.7), stroke.clone());
frame.stroke(&canvas::Path::circle(center, 2.15), stroke);
}
fn constraint_glyph_box(
anchor: Point,
outward: [f32; 2],
@@ -831,6 +865,7 @@ pub fn selection_overlay<'a>(
selection_visual: SelectionVisualOptions,
constraint_glyphs: Vec<(Point, [f32; 2], String, bool, bool, Vec<Point>)>,
constraint_glyph_tooltip: Option<String>,
constraint_cursor_badge: Option<String>,
) -> Element<'a, Message> {
canvas(SelectionCanvas {
selection,
@@ -856,6 +891,7 @@ pub fn selection_overlay<'a>(
selection_visual,
constraint_glyphs,
constraint_glyph_tooltip,
constraint_cursor_badge,
})
.width(Length::Fill)
.height(Length::Fill)
@@ -920,6 +956,9 @@ struct SelectionCanvas {
constraint_glyphs: Vec<(Point, [f32; 2], String, bool, bool, Vec<Point>)>,
/// Localized kind name made visible after the app-level hover dwell.
constraint_glyph_tooltip: Option<String>,
/// Symbol shown beside the cursor while it targets an entity that already
/// participates in an enabled geometric constraint.
constraint_cursor_badge: Option<String>,
}
fn draw_grip_marker(
@@ -1818,6 +1857,28 @@ impl canvas::Program<Message> for SelectionCanvas {
let hole = canvas::Path::circle(Point::new(bx + 6.0, by + 10.5), 1.4);
frame.fill(&hole, dark);
}
if let Some(label) = &self.constraint_cursor_badge {
let center = Point::new(cp.x + sq + if self.hover_locked { 30.0 } else { 12.0 }, cp.y - sq - 7.0);
let blue = Color::from_rgb8(35, 145, 230);
let badge = canvas::Path::circle(center, 8.5);
frame.fill(&badge, blue);
if label == "◎" {
draw_concentric_constraint_glyph(&mut frame, center, Color::WHITE);
} else if label == "T" {
draw_tangent_constraint_glyph(&mut frame, center, Color::WHITE);
} else {
frame.fill_text(canvas::Text {
content: label.clone(),
position: center,
color: Color::WHITE,
size: iced::Pixels(11.0),
align_x: iced::alignment::Horizontal::Center.into(),
align_y: iced::alignment::Vertical::Center,
shaping: iced::advanced::text::Shaping::Advanced,
..Default::default()
});
}
}
}
} // end !over_viewcube
@@ -1905,8 +1966,8 @@ impl canvas::Program<Message> for SelectionCanvas {
let hovered = cursor
.position_in(bounds)
.and_then(|point| constraint_glyph_hit_test(&glyphs_for_offsets, point));
let normal_bg = theme.palette().primary.base.color;
let normal_fg = theme.palette().primary.base.text;
let normal_bg = Color::from_rgb8(103, 109, 118);
let normal_fg = Color::WHITE;
// A redundant or conflicting constraint gets the danger palette
// instead of the
// ordinary primary one — same information a resolver panel
@@ -1955,6 +2016,10 @@ impl canvas::Program<Message> for SelectionCanvas {
);
if label == "T" {
draw_tangent_constraint_glyph(&mut frame, glyph_center, fg);
} else if label == "G²" {
draw_smooth_constraint_glyph(&mut frame, glyph_center, fg);
} else if label == "◎" {
draw_concentric_constraint_glyph(&mut frame, glyph_center, fg);
} else {
frame.fill_text(canvas::Text {
content: label.clone(),
+29
View File
@@ -0,0 +1,29 @@
Page-setup fixtures saved by a commercial CAD application (2016 release, DXF
AC1027 and the matching DWG). Provided by Panos for the plotting parity track;
the drawing holds one 10 m line (`$INSUNITS` = 6, metres) and three paper
layouts, each with a viewport of that line and its dimension:
| Layout | Device | Media (`4`) | `44`×`45` | `73` | `72` | `142`/`143` | `147` | `75` |
|---|---|---|---|---|---|---|---|---|
| `A4 1-100` | `DWG To PDF.pc3` | `ISO_A4_(297.00_x_210.00_MM)` | 297 × 210 | 0 | mm | 1 / 1 | 25.4 | 16 |
| `A3 - plotter` | system printer `HPB602DE (HP OfficeJet Pro 7740 series)` | `A3` | 297.01 × 419.99 | 1 | mm | 1 / 1 | 25.4 | 16 |
| `ARCH D - PLOTTER` | the application's second PDF plotter configuration (`… PDF (High Quality Print).pc3`) | `ARCH_D_(36.00_x_24.00_Inches)` | 914.4 × 609.6 | 0 | in | 1 / 25.4 | 0.03937 | 16 |
What the file establishes (see `src/app/update/file.rs`, `plot_settings_from_dialog`):
- A landscape sheet is written either as the driver's own landscape medium
with rotation 0 (the PDF driver lists both orientations) or as a portrait
medium with rotation 90 (system printers) — rotation is relative to the
medium's orientation, and the medium's exact driver dimensions are kept.
- Margins (`40`–`43`, mm) belong to the medium's own edges: the PDF driver's
A4 has 5.79375 left/right and 17.79375 bottom/top. Layout limits (`10`/`20`)
put the sheet at minus the *displayed* margins: at rotation 90 the medium's
top margin (20.02) becomes the layout's left one, its left margin (5.00) the
layout's bottom one.
- Plot flags `70` = 672 on every layout: draw viewports first, print
lineweights, plot with plot styles — the "use standard scale" bit stays clear
even with a standard code in `75`; the model tab (fit to paper) sets it.
- `147` is `142/143` × 25.4 on millimetre page setups and `142/143` itself on
inch ones.
- An inch page setup over a millimetre paper space stores "1:1" as
`1 in = 25.4 units` (`75` = 16 kept).
Binary file not shown.
File diff suppressed because it is too large. Load diff