Match DIVIDE marker placement behavior

This commit is contained in:
ramox81 committed 2026-09-11 10:26:08 +03:00
1 parent 7d0c059b30
commit 18569687a1
4 files changed
+135 -74

No files matched your search

+6 -4
View File
@@ -3149,23 +3149,25 @@ impl OpenCADStudio {
self.tabs[i].scene.clear_preview_wire(); self.tabs[i].scene.clear_preview_wire();
self.restore_pre_cmd_tangent(); self.restore_pre_cmd_tangent();
} }
CmdResult::DivideEntity { handle, n } => { CmdResult::DivideEntity { handle, n, marker } => {
use crate::modules::draw::inquiry::divide::divide_entity; use crate::modules::draw::inquiry::divide::divide_entity;
let pts = self.tabs[i] let pts = self.tabs[i]
.scene .scene
.document .document
.get_entity(handle) .get_entity(handle)
.map(|e| divide_entity(e, n)) .map(|e| divide_entity(e, n, marker.as_ref()))
.unwrap_or_default(); .unwrap_or_default();
let count = pts.len(); let count = pts.len();
if count > 0 { if count > 0 {
self.push_undo_snapshot(i, "DIVIDE"); self.push_undo_snapshot(i, "DIVIDE");
for p in pts { let layer = self.tabs[i].active_layer.clone();
for mut p in pts {
p.as_entity_mut().set_layer(layer.clone());
self.tabs[i].scene.add_entity(p); self.tabs[i].scene.add_entity(p);
} }
self.tabs[i].dirty = true; self.tabs[i].dirty = true;
self.command_line self.command_line
.push_output(crate::tf!("DIVIDE: {count} point(s) placed.").as_ref()); .push_output(crate::tf!("DIVIDE: {count} marker(s) placed.").as_ref());
} else { } else {
self.command_line self.command_line
.push_error(crate::t!("DIVIDE: entity type not supported or N < 2.").as_ref()); .push_error(crate::t!("DIVIDE: entity type not supported or N < 2.").as_ref());
+1 -1
View File
@@ -975,7 +975,7 @@ impl OpenCADStudio {
"DIVIDE" => { "DIVIDE" => {
use crate::modules::draw::inquiry::divide::DivideCommand; use crate::modules::draw::inquiry::divide::DivideCommand;
let cmd = DivideCommand::new(); let cmd = DivideCommand::new().with_blocks(self.tabs[i].scene.custom_block_names());
self.command_line.push_info(&cmd.prompt()); self.command_line.push_info(&cmd.prompt());
self.tabs[i].active_cmd = Some(Box::new(cmd)); self.tabs[i].active_cmd = Some(Box::new(cmd));
} }
+9 -1
View File
@@ -1481,7 +1481,7 @@ pub enum CmdResult {
op: crate::modules::draw::modify::pedit::PeditOp, op: crate::modules::draw::modify::pedit::PeditOp,
}, },
/// Place Point entities at N equal intervals along the entity. /// Place Point entities at N equal intervals along the entity.
DivideEntity { handle: Handle, n: usize }, DivideEntity { handle: Handle, n: usize, marker: Option<CurveMarker> },
/// Place Point entities at `segment_length` intervals along the entity. /// Place Point entities at `segment_length` intervals along the entity.
MeasureEntity { handle: Handle, segment_length: f64 }, MeasureEntity { handle: Handle, segment_length: f64 },
/// Extend/trim a Line or Arc by the given mode; end command. /// Extend/trim a Line or Arc by the given mode; end command.
@@ -1939,6 +1939,14 @@ impl InputKind {
} }
} }
#[derive(Clone, Debug)]
pub struct CurveMarker {
pub block: String,
pub align: bool,
pub plane: WorkingPlane,
}
pub trait CadCommand: Send { pub trait CadCommand: Send {
/// Keep the layer already carried by entities committed by this command /// Keep the layer already carried by entities committed by this command
/// instead of replacing it with the current drawing layer. /// instead of replacing it with the current drawing layer.
+119 -68
View File
@@ -1,86 +1,125 @@
// DIVIDE command — place Point entities at N equal intervals along an entity. // DIVIDE and MEASURE place points or block references along a curve.
// MEASURE command — place Point entities at fixed-distance intervals along an entity. use acadrust::entities::{Insert, Point as PointEnt};
use acadrust::entities::Point as PointEnt;
use cadkernel::space::PlanarCurve;
use acadrust::types::Vector3; use acadrust::types::Vector3;
use acadrust::{EntityType, Handle}; use acadrust::{Entity, EntityType, Handle};
use cadkernel::space::PlanarCurve;
use glam::DVec3; use glam::DVec3;
use crate::command::{CadCommand, CmdOption, CmdResult, CurveMarker, WorkingPlane};
use crate::entities::curve::entity_curve; use crate::entities::curve::entity_curve;
use crate::t; use crate::t;
const MEASURE: bool = false;
use crate::command::{CadCommand, CmdResult}; #[derive(Clone, Copy, PartialEq)]
enum Step { Pick, Amount, BlockName, Align }
// ── DIVIDE ───────────────────────────────────────────────────────────────── pub struct DivisionMarkerCommand {
pub struct DivideCommand {
target: Option<Handle>, target: Option<Handle>,
waiting_for_n: bool, pick_point: DVec3,
step: Step,
blocks: Vec<String>,
block: Option<String>,
align: bool,
plane: WorkingPlane,
valid_pick: bool,
} }
impl DivideCommand { pub type DivideCommand = DivisionMarkerCommand;
impl DivisionMarkerCommand {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self { target: None, pick_point: DVec3::ZERO, step: Step::Pick,
target: None, blocks: Vec::new(), block: None, align: true,
waiting_for_n: false, plane: WorkingPlane::default(), valid_pick: false }
} }
pub fn with_blocks(mut self, blocks: Vec<String>) -> Self {
self.blocks = blocks;
self
}
fn marker(&self) -> Option<CurveMarker> {
self.block.as_ref().map(|name| CurveMarker {
block: name.clone(), align: self.align, plane: self.plane,
})
} }
} }
impl CadCommand for DivideCommand { impl CadCommand for DivisionMarkerCommand {
fn name(&self) -> &'static str { fn name(&self) -> &'static str { if MEASURE { "MEASURE" } else { "DIVIDE" } }
"DIVIDE"
}
fn prompt(&self) -> String { fn prompt(&self) -> String {
if self.target.is_none() { let prompt = match self.step {
t!("DIVIDE Select object to divide:").into_owned() Step::Pick if MEASURE => "Select object to measure:",
} else { Step::Pick => "Select object to divide:",
t!("DIVIDE Enter number of segments:").into_owned() Step::BlockName => "Enter name of block to insert:",
Step::Align => "Align block with object? [Yes/No] <Yes>:",
Step::Amount if MEASURE && self.block.is_none() => "Specify length of segment or [Block]:",
Step::Amount if MEASURE => "Specify length of segment:",
Step::Amount if self.block.is_none() => "Enter number of segments or [Block]:",
Step::Amount => "Enter number of segments:",
};
format!("{} {}", self.name(), prompt)
}
fn options(&self) -> Vec<CmdOption> {
match self.step {
Step::Amount if self.block.is_none() => vec![CmdOption::new("Block", "B")],
Step::Align => vec![CmdOption::new("Yes", "Y"), CmdOption::new("No", "N")],
_ => vec![],
} }
} }
fn set_working_plane(&mut self, plane: WorkingPlane) { self.plane = plane; }
fn needs_entity_pick(&self) -> bool { fn needs_entity_pick(&self) -> bool { self.step == Step::Pick }
self.target.is_none() fn inject_before_entity_pick(&self) -> bool { true }
fn inject_picked_entity(&mut self, entity: EntityType) {
self.valid_pick = measurable(&entity).is_some();
} }
fn on_entity_pick(&mut self, handle: Handle, pt: DVec3) -> CmdResult {
fn on_entity_pick(&mut self, handle: Handle, _pt: DVec3) -> CmdResult { if handle.is_null() || !self.valid_pick { return CmdResult::NeedPoint; }
if handle.is_null() {
return CmdResult::NeedPoint;
}
self.target = Some(handle); self.target = Some(handle);
self.waiting_for_n = true; self.pick_point = pt;
self.step = Step::Amount;
CmdResult::NeedPoint CmdResult::NeedPoint
} }
fn wants_text_input(&self) -> bool { self.step != Step::Pick }
fn wants_text_input(&self) -> bool {
self.waiting_for_n
}
fn dyn_field(&self) -> crate::command::DynField { fn dyn_field(&self) -> crate::command::DynField {
if self.waiting_for_n { if self.step == Step::Amount { crate::command::DynField::Scalar }
crate::command::DynField::Scalar else { crate::command::DynField::Point }
} else {
crate::command::DynField::Point
}
} }
fn dyn_commit_as_text(&self) -> bool { self.step == Step::Amount }
fn on_text_input(&mut self, text: &str) -> Option<CmdResult> { fn on_text_input(&mut self, text: &str) -> Option<CmdResult> {
let n: usize = text.trim().parse().ok().filter(|&n| n >= 2)?; let text = text.trim();
let handle = self.target?; match self.step {
self.waiting_for_n = false; Step::BlockName => {
Some(CmdResult::DivideEntity { handle, n }) self.block = Some(self.blocks.iter().find(|name| name.eq_ignore_ascii_case(text))?.clone());
} self.step = Step::Align;
}
fn on_point(&mut self, _pt: DVec3) -> CmdResult { Step::Align => {
CmdResult::NeedPoint self.align = match text.to_ascii_uppercase().as_str() {
"Y" | "YES" => true,
"N" | "NO" => false,
_ => return None,
};
self.step = Step::Amount;
}
Step::Amount => {
if self.block.is_none() && matches!(text.to_ascii_uppercase().as_str(), "B" | "BLOCK") {
self.step = Step::BlockName;
} else {
let n = text.parse::<usize>().ok().filter(|n| (2..=32767).contains(n))?;
return Some(CmdResult::DivideEntity { handle: self.target?, n, marker: self.marker() });
}
}
Step::Pick => return None,
}
Some(CmdResult::NeedPoint)
} }
fn on_point(&mut self, _pt: DVec3) -> CmdResult { CmdResult::NeedPoint }
fn on_enter(&mut self) -> CmdResult { fn on_enter(&mut self) -> CmdResult {
CmdResult::Cancel if self.step == Step::Align {
self.align = true;
self.step = Step::Amount;
CmdResult::NeedPoint
} else { CmdResult::Cancel }
} }
} }
// ── MEASURE ────────────────────────────────────────────────────────────────
pub struct MeasureCommand { pub struct MeasureCommand {
target: Option<Handle>, target: Option<Handle>,
@@ -157,23 +196,21 @@ impl CadCommand for MeasureCommand {
} }
} }
// ── Geometry ───────────────────────────────────────────────────────────────
/// Compute N-1 equally spaced points along the entity (DIVIDE). pub fn divide_entity(entity: &EntityType, n: usize, marker: Option<&CurveMarker>) -> Vec<EntityType> {
pub fn divide_entity(entity: &EntityType, n: usize) -> Vec<EntityType> { if !(2..=32767).contains(&n) {
if n < 2 {
return vec![]; return vec![];
} }
let Some((curve, total)) = measurable(entity) else { let Some((curve, total)) = measurable(entity) else {
return vec![]; return vec![];
}; };
let step = total / n as f64; let step = total / n as f64;
(1..n) let last = if curve.is_closed() { n } else { n - 1 };
.map(|k| make_point(curve.point_at_distance(step * k as f64))) (1..=last)
.map(|k| make_marker(&curve, step * k as f64, marker))
.collect() .collect()
} }
/// Compute points at fixed `segment_length` intervals along the entity (MEASURE).
pub fn measure_entity(entity: &EntityType, segment_length: f64) -> Vec<EntityType> { pub fn measure_entity(entity: &EntityType, segment_length: f64) -> Vec<EntityType> {
if segment_length <= 0.0 { if segment_length <= 0.0 {
return vec![]; return vec![];
@@ -190,21 +227,35 @@ pub fn measure_entity(entity: &EntityType, segment_length: f64) -> Vec<EntityTyp
pts pts
} }
fn make_marker(curve: &PlanarCurve, distance: f64, marker: Option<&CurveMarker>) -> EntityType {
let pos = curve.point_at_distance(distance);
let Some(marker) = marker else {
let mut point = PointEnt::new();
point.location = Vector3::new(pos[0], pos[1], pos[2]);
return EntityType::Point(point);
};
let local = marker.plane.to_local(DVec3::from_array(pos));
let mut insert = Insert::new(marker.block.clone(), Vector3::new(local.x, local.y, local.z));
if marker.align {
let tangent = DVec3::from_array(curve.tangent_at(curve.parameter_at_distance(distance)));
let tangent = marker.plane.vector_to_local(tangent);
insert.rotation = tangent.y.atan2(tangent.x);
}
insert.apply_transform(&marker.plane.to_world_transform());
EntityType::Insert(insert)
}
fn make_point(pos: [f64; 3]) -> EntityType { fn make_point(pos: [f64; 3]) -> EntityType {
let mut p = PointEnt::new(); let mut p = PointEnt::new();
p.location = Vector3::new(pos[0], pos[1], pos[2]); p.location = Vector3::new(pos[0], pos[1], pos[2]);
EntityType::Point(p) EntityType::Point(p)
} }
/// The entity's curve and its length, or `None` for anything that cannot be
/// walked along — a hatch, a block, an unbounded ray.
fn measurable(entity: &EntityType) -> Option<(PlanarCurve, f64)> { fn measurable(entity: &EntityType) -> Option<(PlanarCurve, f64)> {
let curve = entity_curve(entity)?; let curve = entity_curve(entity)?;
let total = curve.curve.length(); let total = curve.curve.length();
(total.is_finite() && total > 1e-10).then_some((curve, total)) (total.is_finite() && total > 1e-10).then_some((curve, total))
} }
inventory::submit!(crate::command::CommandRegistration { names: &["DIVIDE"] });
// ── Autocomplete registry ───────────────────────────────── inventory::submit!(crate::command::CommandRegistration { names: &["MEASURE"] });
inventory::submit!(crate::command::CommandRegistration { names: &["DIVIDE"] }); // DivideCommand
inventory::submit!(crate::command::CommandRegistration { names: &["MEASURE"] }); // MeasureCommand