Dynamic block references: rotation and flip parameters and their rotate and flip actions

Angle1 (degrees, as Properties shows them) turns the rotate action's objects
about its base point; Flip state1 mirrors the flip action's objects across
the current reflection line (text stays readable). Parameters in the
selection are carried along, attributes follow, the flip grip's record and
the history are written as AutoCAD writes them. Checked against AutoCAD's own
output for the same changes: value records, history and geometry match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cody Vogt
2026-10-29 22:27:13 -06:00
co-authored by Claude Opus 5.5
parent f8b09e92e5
commit ee0697955c
3 changed files with 268 additions and 31 deletions
+70 -11
View File
@@ -52,6 +52,10 @@ pub struct DynamicBlock {
/// the grips shown in them by object).
#[serde(skip)]
pub grip_objects: Vec<(i32, Handle)>,
/// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its
/// reflection line).
#[serde(skip)]
pub grip_points: Vec<(i32, Vec3)>,
}
/// One parameter: a property a reference to the block can change.
@@ -91,12 +95,14 @@ pub enum ParameterKind {
Polar { base: Vec3, end: Vec3 },
/// Horizontal and vertical distances from a base point.
Xy { base: Vec3, end: Vec3 },
/// An angle about a base point.
Rotation { base: Vec3, end: Vec3 },
/// An angle about a base point (Angle1): the end point turns about the base. The angle is
/// measured from the direction the dynamic block has from base to end.
Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet },
/// Aligns the reference with nearby geometry.
Alignment { base: Vec3, end: Vec3 },
/// Mirrors the objects about a reflection line.
Flip { base: Vec3, end: Vec3 },
/// Mirrors the objects about the reflection line from base to end (Flip state1); the names
/// of its two states, not flipped and flipped.
Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] },
/// A position (Position1).
Point { at: Vec3, label: String, description: String },
/// Named sets of visible objects.
@@ -122,6 +128,8 @@ impl ParameterKind {
match self {
ParameterKind::Linear { label, .. }
| ParameterKind::Point { label, .. }
| ParameterKind::Rotation { label, .. }
| ParameterKind::Flip { label, .. }
| ParameterKind::Visibility { label, .. }
| ParameterKind::Lookup { label, .. } => Some(label),
_ => None,
@@ -213,7 +221,11 @@ pub enum ActionKind {
angle_offset: f64,
},
Scale,
Rotate,
/// Turns the objects about its base point by the change of a rotation parameter's angle.
Rotate {
base: ActionBase,
},
/// Mirrors the objects across a flip parameter's reflection line when its state changes.
Flip,
Array,
PolarStretch,
@@ -223,6 +235,16 @@ pub enum ActionKind {
},
}
/// Where an action that turns or scales its objects has its base point.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionBase {
/// It follows the parameter's base point, at `offset` from it; else it stays at `at`.
pub dependent: bool,
pub offset: Vec3,
pub at: Vec3,
}
/// A lookup table column: the parameter value it reads or sets.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -361,6 +383,7 @@ pub fn dynamic_block(d: &Drawing, name: &str) -> Option<DynamicBlock> {
} else {
if kind.ends_with("GRIP") {
out.grip_objects.push((node, o.handle));
out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010)));
}
out.other.push(o.kind.clone());
}
@@ -409,14 +432,28 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
}
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
// the value set.
"BLOCKROTATIONPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter"));
let (label, description) = (c.string(305), c.string(306));
ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) }
}
// Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped).
"BLOCKFLIPPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter"));
let (label, description) = (c.string(305), c.string(306));
let states = [c.string(307), c.string(308)];
ParameterKind::Flip { base, end, label, description, states }
}
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKALIGNMENTPARAMETER" => {
let (base, end) = two();
match kind {
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
_ => ParameterKind::Flip { base, end },
_ => ParameterKind::Alignment { base, end },
}
}
other => ParameterKind::Other { dxf_type: other.to_string() },
@@ -471,8 +508,19 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
}
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
"BLOCKROTATEACTION" => {
let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt"));
let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction"));
connections.push((c.int(94), c.string(303)));
(connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) })
}
// Its four connections: the parameter (92-95) and the values it reads (301-304).
"BLOCKFLIPACTION" => {
let tags = section(secs, "AcDbBlockFlipAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
(connections, ActionKind::Flip)
}
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
@@ -480,6 +528,17 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
Action { node, handle, name, at, selection, connections, kind }
}
/// The base point of an action that has one: after its two connections (92/93, 301/302), the
/// offset from the parameter's base point (1011), whether it follows that point (280), and the
/// point it stays at when it doesn't (1012).
fn action_base(tags: &[RawTag]) -> ActionBase {
let mut c = Cursor::new(tags);
c.next(302);
let offset = c.point(1011);
let dependent = c.int(280) != 0;
ActionBase { dependent, offset, at: c.point(1012) }
}
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
+171 -19
View File
@@ -92,6 +92,26 @@ enum Val {
Point(Vec3),
/// A two-point parameter's base and end points.
Points(Vec3, Vec3),
/// A flip parameter's reflection line (base, end) and whether it is flipped.
Flip(Vec3, Vec3, bool),
/// A flip grip's state: its value record's last group 70.
State(bool),
}
/// A rotation parameter's angle (radians, 0 to 2π): its end's direction from its base, from the
/// direction `home` the dynamic block has (base to end).
fn rotation_angle(b: Vec3, e: Vec3, home: (Vec3, Vec3)) -> f64 {
let (now, zero) = ((e - b).xy(), (home.1 - home.0).xy());
(now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU)
}
/// The end point that gives a rotation parameter with base `b` and end `e` the angle `a` from the
/// direction `home` the dynamic block has.
fn rotation_end(b: Vec3, e: Vec3, home: (Vec3, Vec3), a: f64) -> Vec3 {
let r = (e - b).len();
let zero = (home.1 - home.0).xy();
let dir = Vec2::new(zero.y.atan2(zero.x).cos(), zero.y.atan2(zero.x).sin()).rotate(a);
b + (dir * r).to3(0.0)
}
/// A parameter's current value on the reference: the value it was given, else the block's own.
@@ -102,15 +122,16 @@ fn current(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option
(_, Some(Value::Text { value })) => Val::Text(value.clone()),
(_, Some(Value::Point { at })) => Val::Point(*at),
(_, Some(Value::Points { base, end })) => Val::Points(*base, *end),
(_, Some(Value::Flip { base, end, flipped })) => Val::Flip(*base, *end, *flipped),
(ParameterKind::Flip { base, end, .. }, None) => Val::Flip(*base, *end, false),
(ParameterKind::Visibility { states, .. }, None) => Val::Text(states.first().map(|s| s.name.clone()).unwrap_or_default()),
(ParameterKind::Point { at, .. }, None) => Val::Point(*at),
(
ParameterKind::Linear { base, end, .. }
| ParameterKind::Polar { base, end }
| ParameterKind::Xy { base, end }
| ParameterKind::Rotation { base, end }
| ParameterKind::Alignment { base, end }
| ParameterKind::Flip { base, end },
| ParameterKind::Rotation { base, end, .. }
| ParameterKind::Alignment { base, end },
None,
) => Val::Points(*base, *end),
_ => return None,
@@ -303,6 +324,33 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) ->
let at = if is_x { Vec3::new(block_base.x + v / sx, at.y, at.z) } else { Vec3::new(at.x, block_base.y + v / sy, at.z) };
plan.set.insert(p.node, Val::Point(at));
}
// An angle in degrees, as Properties shows it, snapped to the parameter's values.
(ParameterKind::Rotation { base: hb, end: he, values, label, .. }, None) => {
let typed = number(value)?.to_radians().rem_euclid(std::f64::consts::TAU);
let a = allowed(values, typed);
if !a.is_finite() {
return Err(format!("\"{value}\" is not an angle for {label}."));
}
let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) };
plan.set.insert(p.node, Val::Points(b, rotation_end(b, e, (*hb, *he), a)));
plan.chain(&m, &r.values, p.node, "UpdatedAngle")?;
}
// A state by name (or 0 / 1); its flip grip's record follows.
(ParameterKind::Flip { states, label, .. }, None) => {
let v = value.trim();
let flipped = if v.eq_ignore_ascii_case(&states[1]) || v == "1" {
true
} else if v.eq_ignore_ascii_case(&states[0]) || v == "0" {
false
} else {
return Err(format!("\"{value}\" is not a state of {label}: {}, {}.", states[0], states[1]));
};
let Some(Val::Flip(b, e, _)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no reflection line.")) };
plan.set.insert(p.node, Val::Flip(b, e, flipped));
if let Some(g) = p.grips.first().filter(|g| **g != 0) {
plan.set.insert(*g, Val::State(flipped));
}
}
_ => return Err(format!("CADCraft can't change {name} yet.")),
}
apply(d, insert, &r.definition, &r.values, &plan.set, p.node)
@@ -357,6 +405,17 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa
let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) };
plan.set.insert(node, Val::Point(Vec3::new(q.x, q.y, at.z)));
}
// The angle from the base to the point, snapped to the parameter's values.
(ParameterKind::Rotation { base: hb, end: he, values, label, .. }, GripPart::End) => {
let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) };
let q3 = Vec3::new(q.x, q.y, b.z);
if (q3 - b).len() < 1e-12 {
return Err(format!("{label} needs a point away from its base."));
}
let a = allowed(values, rotation_angle(b, q3, (*hb, *he)));
plan.set.insert(node, Val::Points(b, rotation_end(b, e, (*hb, *he), a)));
plan.chain(&m, &r.values, node, "UpdatedAngle")?;
}
_ => return Err("That grip can't be dragged.".into()),
}
apply(d, insert, &r.definition, &r.values, &plan.set, node)
@@ -445,13 +504,38 @@ fn apply(
let copy_of = |dh: &Handle| def_tags.get(dh).and_then(|t| src_by_tag.get(t)).copied();
// New values, starting from the change; actions add the parameters they carry along.
let mut new: BTreeMap<i32, Val> = set.clone();
let mut moves: HashMap<Handle, Vec<(Option<Vec<i32>>, Vec2)>> = HashMap::new();
let mut moves: HashMap<Handle, Vec<Op>> = HashMap::new();
let param_of: HashMap<Handle, i32> = m.parameters.iter().map(|p| (p.handle, p.node)).collect();
for a in &m.actions {
let changed: Vec<&(i32, String)> = a.connections.iter().filter(|(n, _)| set.contains_key(n)).collect();
if changed.is_empty() {
continue;
}
// Rotate and flip actions turn or mirror their objects, and carry the parameters in their
// selection the same way.
if let Some(t) = turn_or_mirror(&m, values, set, a) {
for h in &a.selection {
if let Some(node) = param_of.get(h) {
if set.contains_key(node) {
continue;
}
let Some(cur) = new.get(node).cloned().or_else(|| current(&m, values, *node)) else { continue };
let p = |q: Vec3| t.apply(q.xy()).to3(q.z);
let moved = match cur {
Val::Point(q) => Val::Point(p(q)),
Val::Points(b, e) => Val::Points(p(b), p(e)),
Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f),
other => other,
};
new.insert(*node, moved);
continue;
}
if let Some(c) = copy_of(h) {
moves.entry(c).or_default().push(Op::Transform(t));
}
}
continue;
}
let (mult, angle, frame, vertices): (f64, f64, &[Vec2], &[(Handle, Vec<i32>)]) = match &a.kind {
ActionKind::Stretch { frame, vertices, multiplier, angle_offset } => (*multiplier, *angle_offset, frame, vertices),
ActionKind::Move { multiplier, angle_offset } => (*multiplier, *angle_offset, &[], &[]),
@@ -496,6 +580,8 @@ fn apply(
(Val::Point(p), _) => Val::Point(shift(p, None)),
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))),
(Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)),
(Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f),
(Val::Flip(b, e, f), _) => Val::Flip(shift(b, None), shift(e, None), f),
(t, _) => t,
};
new.insert(*node, moved);
@@ -503,7 +589,7 @@ fn apply(
}
let Some(c) = copy_of(h) else { continue };
let idx = vtx_by_handle.get(h).map(|i| (*i).clone());
moves.entry(c).or_default().push((idx, v));
moves.entry(c).or_default().push(Op::Move(idx, v));
}
}
// Visibility states.
@@ -530,15 +616,21 @@ fn apply(
for e in src.entities.iter() {
copies.insert(e.handle, d.new_handle());
}
// How far each attribute definition moves (block coordinates): the reference's attribute of
// that tag moves with it, as AutoCAD moves it.
let attrib_moves: HashMap<String, Vec2> = src
// How each attribute definition moves, turns or mirrors (block coordinates): the reference's
// attribute of that tag follows it, as AutoCAD moves it.
let attrib_moves: HashMap<String, Mat3> = src
.entities
.iter()
.filter_map(|e| match &e.kind {
EntityKind::AttDef(ad) => {
let v = moves.get(&e.handle).into_iter().flatten().fold(Vec2::ZERO, |acc, (_, v)| acc + *v);
(v != Vec2::ZERO).then(|| (ad.tag.to_ascii_uppercase(), v))
let ops = moves.get(&e.handle)?;
let t = ops.iter().fold(Mat3::IDENTITY, |acc, op| {
acc.then(match op {
Op::Move(_, v) => Mat3::translate(*v),
Op::Transform(t) => *t,
})
});
Some((ad.tag.to_ascii_uppercase(), t))
}
_ => None,
})
@@ -556,8 +648,11 @@ fn apply(
if let Some(v) = shown_copy.get(&e.handle) {
c.common.visible = *v;
}
for (idx, v) in moves.get(&e.handle).into_iter().flatten() {
move_entity(&mut c, idx.as_deref(), *v);
for op in moves.get(&e.handle).into_iter().flatten() {
match op {
Op::Move(idx, v) => move_entity(&mut c, idx.as_deref(), *v),
Op::Transform(t) => c.kind.transform(t),
}
}
if let EntityKind::Hatch(h) = &mut c.kind {
for l in &mut h.loops {
@@ -594,21 +689,22 @@ fn apply(
let xdata = vec![tag(1001, BTAG), tag(1070, "1"), tag(1005, rec.hex())];
f.records.insert(("BLOCK_RECORD".into(), name.to_ascii_uppercase()), ForeignExtra { xdata, ..Default::default() });
}
// The block-to-drawing transform's linear part turns a block-coordinate move into the move of
// the reference's attribute.
// A block-coordinate change of an attribute definition, seen in the drawing (through the
// block-to-drawing transform), is the change of the reference's attribute.
let to_world = ins.transform(src.base.xy());
let origin = to_world.apply(Vec2::ZERO);
let to_block = to_world.inverse().unwrap_or(Mat3::IDENTITY);
d.modify_entity(insert, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.block = name.clone();
for a in &mut i.attribs {
if let Some(v) = attrib_moves.get(&a.tag.to_ascii_uppercase()) {
let w = to_world.apply(*v) - origin;
if let Some(t) = attrib_moves.get(&a.tag.to_ascii_uppercase()) {
let w = to_block.then(*t).then(to_world);
let mut k = EntityKind::Text(a.text.clone());
k.transform(&Mat3::translate(w));
k.transform(&w);
if let EntityKind::Text(t) = k {
a.text = t;
}
a.transform_multiline(&w);
}
}
}
@@ -891,6 +987,13 @@ fn write_history(tags: &mut Vec<RawTag>, p: &super::Parameter, old: Option<&Val>
(ParameterKind::Visibility { label, .. } | ParameterKind::Lookup { label, .. }, Val::Text(t)) => {
vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(1, t.clone())])]
}
(ParameterKind::Rotation { label, base: hb, end: he, .. }, Val::Points(b, e)) => {
let a = rotation_angle(*b, *e, (*hb, *he));
vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(40, a.to_string())])]
}
(ParameterKind::Flip { label, .. }, Val::Flip(_, _, f)) => {
vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(70, i32::from(*f).to_string())])]
}
(ParameterKind::Linear { label, .. }, Val::Points(b, e)) => {
let mut c: Vec<(i32, Vec<RawTag>)> = p.grips.iter().filter(|g| **g != 0).map(|g| (*g, Vec::new())).collect();
c.push((p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(40, (*e - *b).len().to_string())]));
@@ -928,8 +1031,15 @@ fn write_value(tags: &mut Vec<RawTag>, v: &Val) {
return;
}
Val::Point(p) => vec![*p],
Val::Points(b, e) => vec![*b, *e],
Val::Points(b, e) | Val::Flip(b, e, _) => vec![*b, *e],
Val::State(f) => {
set_state(tags, *f);
return;
}
};
if let Val::Flip(_, _, f) = v {
set_state(tags, *f);
}
for (i, p) in points.iter().enumerate() {
// The i-th point's groups, else new ones before any text.
let find = |tags: &[RawTag], code: i32, n: usize| tags.iter().enumerate().filter(|(_, t)| t.code == code).nth(n).map(|(j, _)| j);
@@ -953,6 +1063,48 @@ fn write_value(tags: &mut Vec<RawTag>, v: &Val) {
}
}
/// Set a record's state, its last group 70 after the header's two (`70 25`, `70 104`), adding
/// it when the record has none.
fn set_state(tags: &mut Vec<RawTag>, on: bool) {
let at: Vec<usize> = tags.iter().enumerate().filter(|(_, t)| t.code == 70).map(|(i, _)| i).collect();
match at.get(2..).and_then(|rest| rest.last()) {
Some(&i) => {
if let Some(t) = tags.get_mut(i) {
t.value = i32::from(on).to_string();
}
}
None => tags.push(tag(70, i32::from(on).to_string())),
}
}
/// The turn or mirror action `a` makes with the changes `set`, if it is one and they change it:
/// a rotate action turns about its base point by the change of its rotation parameter's angle;
/// a flip action mirrors across its flip parameter's reflection line when the state changes.
fn turn_or_mirror(m: &DynamicBlock, values: &BTreeMap<i32, Value>, set: &BTreeMap<i32, Val>, a: &super::Action) -> Option<Mat3> {
match &a.kind {
ActionKind::Rotate { base } => {
let (node, _) = a.connections.iter().find(|(_, c)| c.eq_ignore_ascii_case("AngleDelta"))?;
let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return None };
let turn = (*ne - *nb).xy().angle() - (oe - ob).xy().angle();
let pivot = if base.dependent { *nb + base.offset } else { base.at };
(turn.abs() > 1e-12 && turn.is_finite()).then(|| Mat3::rotate_about(pivot.xy(), turn))
}
ActionKind::Flip => {
let (node, _) = a.connections.first()?;
let (Some(Val::Flip(b, e, now)), Some(Val::Flip(_, _, was))) = (set.get(node), current(m, values, *node)) else { return None };
(now != &was && (*e - *b).len() > 1e-12).then(|| Mat3::mirror(b.xy(), e.xy()))
}
_ => None,
}
}
/// One change to a copied object: a move (of the listed vertices, else all of it) or a turn or
/// mirror.
enum Op {
Move(Option<Vec<i32>>, Vec2),
Transform(Mat3),
}
/// Remove anonymous block `name` when nothing refers to it any more (the block a changed
/// reference used to show), with the data kept for its record.
fn drop_if_unused(d: &mut Drawing, name: &str) {
+27 -1
View File
@@ -29,6 +29,8 @@ pub enum Value {
Point { at: Vec3 },
/// A two-point parameter's points.
Points { base: Vec3, end: Vec3 },
/// A flip parameter's reflection line and whether it is flipped.
Flip { base: Vec3, end: Vec3, flipped: bool },
}
/// A dynamic block reference.
@@ -91,7 +93,8 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
/// parameter's also ends with its state, a group 70 after the header's two (`70 25`, `70 104`).
fn value(o: &ForeignObject) -> Option<Value> {
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone() });
@@ -100,7 +103,9 @@ fn value(o: &ForeignObject) -> Option<Value> {
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
};
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
let states: Vec<&str> = o.tags.iter().filter(|t| t.code == 70).map(|t| t.value.trim()).collect();
match (point(0), point(1)) {
(Some(base), Some(end)) if states.len() > 2 => Some(Value::Flip { base, end, flipped: states.last() == Some(&"1") }),
(Some(base), Some(end)) => Some(Value::Points { base, end }),
(Some(at), None) => Some(Value::Point { at }),
_ => None,
@@ -133,6 +138,12 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
Some(Reference { definition, values })
}
/// An angle (radians) as Properties shows it: degrees with AUPREC decimals.
fn angle_text(d: &Drawing, a: f64) -> String {
let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0);
format!("{:.prec$}", a.to_degrees())
}
/// A number as the drawing shows lengths (LUPREC decimals).
fn number(d: &Drawing, v: f64) -> String {
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
@@ -247,6 +258,21 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let now = (e - b).xy();
let zero = (*he - *hb).xy();
let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
ParameterKind::Flip { label, states, .. } => {
let flipped = matches!(v, Some(Value::Flip { flipped: true, .. }));
let value = states[usize::from(flipped)].clone();
out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), editable: true });
}
ParameterKind::Visibility { label, states, .. } => {
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });