diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index e0ebb81a4..84ca2031b 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -75,6 +75,20 @@ pub struct Foreign { /// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD` /// names its entity with a 320 handle (see [`Foreign::data_store_entities`]). pub data_store: Vec, + /// Block references with kept annotation scale contexts, as they were read: what a context + /// is brought up to date from (see [`KeptPlacement`]), by handle. + pub placements: BTreeMap, +} + +/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its +/// attributes' insertion and alignment points, in order. Its kept contexts were written for it +/// then; what it did since moves them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct KeptPlacement { + pub insert: crate::geom::Vec3, + pub rotation: f64, + pub scale: crate::geom::Vec3, + pub attribs: Vec<(crate::geom::Vec3, crate::geom::Vec3)>, } impl Foreign { @@ -87,6 +101,7 @@ impl Foreign { && self.targets.is_empty() && self.class_order.is_empty() && self.data_store.is_empty() + && self.placements.is_empty() } /// The entities the data store has records for (their 320 handles). diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index f52cd9d07..d25aac64e 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -430,6 +430,17 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.records.entry(key).or_insert(x); } } + // Block references whose extension dictionaries are kept (their annotation scale contexts), + // as read. + for e in all_entities(d) { + if let EntityKind::Insert(ins) = &e.kind + && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) + { + let attribs = ins.attribs.iter().map(|a| (a.text.insert, a.text.align_pt.unwrap_or(a.text.insert))).collect(); + f.placements + .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); + } + } // The classes of kept objects and of entities of types CADCraft doesn't model. let mut types: HashSet = f.objects.iter().map(|o| up(&o.kind)).collect(); types.extend(all_entities(d).filter_map(|e| match &e.kind { @@ -714,22 +725,36 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> let mut out = HashMap::new(); for list in by_parent.values() { let Some(first) = list.first() else { continue }; - let Some(EntityKind::Insert(ins)) = owner_entity(&first.handle.hex()).and_then(|h| d.entity(h)).map(|e| &e.kind) else { continue }; - let def = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).unwrap_or(first); - let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; - let turn = (ins.rotation.to_degrees() - num(def, 50).unwrap_or(0.0)).to_radians(); - let at0 = cadcraft_doc::geom::Vec2::new(x0, y0); - let ratio = |code: i32, now: f64| num(def, code).filter(|s| s.abs() > 1e-12).map_or(1.0, |s| now / s); - let ratios = [(41, ratio(41, ins.scale.x)), (42, ratio(42, ins.scale.y)), (43, ratio(43, ins.scale.z))]; + let Some(h) = owner_entity(&first.handle.hex()) else { continue }; + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { continue }; + // The reference as read: kept when it was read, else (data made before that was kept) + // its default context. + let (at0, rot0, scale0) = match f.placements.get(&h) { + Some(p) => (p.insert.xy(), p.rotation, [p.scale.x, p.scale.y, p.scale.z]), + None => { + let def = list.iter().find(|o| is_default(o)).unwrap_or(first); + let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; + let s = |code: i32, now: f64| num(def, code).unwrap_or(now); + let rot = num(def, 50).unwrap_or(0.0).to_radians(); + (cadcraft_doc::geom::Vec2::new(x0, y0), rot, [s(41, ins.scale.x), s(42, ins.scale.y), s(43, ins.scale.z)]) + } + }; + let turn = ins.rotation - rot0; + let ratio = |then: f64, now: f64| if then.abs() > 1e-12 { now / then } else { 1.0 }; + let ratios = [(41, ratio(scale0[0], ins.scale.x)), (42, ratio(scale0[1], ins.scale.y)), (43, ratio(scale0[2], ins.scale.z))]; let unchanged = (ins.insert.xy() - at0).len() < 1e-9 && turn.abs() < 1e-12 && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); if unchanged || !ratios.iter().all(|(_, r)| r.is_finite()) || !turn.is_finite() { continue; } for c in list { let mut o = (*c).clone(); - // Its offset from the default context turns with the reference. + // Its offset from where the reference was moves as the reference did: back into the + // reference's frame then, scaled (a mirror flips it), turned to its frame now. let at = match (num(c, 10), num(c, 20)) { - (Some(x), Some(y)) => ins.insert.xy() + (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(turn), + (Some(x), Some(y)) => { + let off = (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(-rot0); + ins.insert.xy() + cadcraft_doc::geom::Vec2::new(off.x * ratios[0].1, off.y * ratios[1].1).rotate(ins.rotation) + } _ => ins.insert.xy(), }; for t in &mut o.tags { @@ -817,19 +842,25 @@ fn attribute_contexts( for (xd, list) in &by_attrib { let Some((r, tag, nth)) = attribs.get(xd) else { continue }; let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; - let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; + let Some((index, a)) = ins.attribs.iter().enumerate().filter(|(_, a)| up(&a.tag) == *tag).nth(*nth) else { continue }; let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); let Some(to_block_now) = ins.transform(base).inverse() else { continue }; - let Some(def) = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).or(list.first()) else { continue }; + let Some(def) = list.iter().find(|o| is_default(o)).or(list.first()) else { continue }; let at = |o: &ForeignObject, x: i32| Some(Vec2::new(num(o, x)?, num(o, x + 10)?)); // What the attribute did in the block since: its default context then, the attribute now. let Some(def_place) = text(def, 340).and_then(|s| read.get(&(*r, s))).copied() else { continue }; let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; let now_ins = to_block_now.apply(a.text.insert.xy()); let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); - let (Some(then_ins), Some(then_align)) = (at(def, 10).map(|p| to_block_then.apply(p)), at(def, 11).map(|p| to_block_then.apply(p))) else { - continue; - }; + // The attribute as read, in its reference as read, when that was kept; else its default + // context in the reference's. + let kept = f.placements.get(r).and_then(|p| { + let (ins_then, align_then) = p.attribs.get(index)?; + let then = matrix(ins, base, (p.insert.xy(), p.rotation.to_degrees(), (p.scale.x, p.scale.y))).inverse()?; + Some((then.apply(ins_then.xy()), then.apply(align_then.xy()))) + }); + let then = kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?)))); + let Some((then_ins, then_align)) = then else { continue }; let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - (num(def, 50).unwrap_or(0.0) - def_place.1); for c in list { let Some(s) = text(c, 340) else { continue }; @@ -864,6 +895,12 @@ fn attribute_contexts( out } +/// Whether a kept context is its object's default one: its first 290 group (of +/// AcDbObjectContextData) is 1. An attribute context has a later 290 group of its own. +fn is_default(o: &ForeignObject) -> bool { + o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1") +} + fn is_blkref_context(kind: &str) -> bool { kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") } @@ -924,7 +961,6 @@ fn reconcile( let k = f.targets.get(&handle(&norm(&v.value))?)?; (k.0 == "SCALE" && roles.contains_key(k)).then(|| k.1.clone()) }; - let is_default = |o: &ForeignObject| o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1"); let set_default = |o: &mut ForeignObject, on: bool| { if let Some(t) = o.tags.iter_mut().find(|t| t.code == 290) { t.value = if on { "1" } else { "0" }.into(); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index f3c740d97..0a9746735 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -587,3 +587,84 @@ fn new_contexts_come_from_one_whose_scale_remains() { assert!((actx[1].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); assert_eq!(listed_contexts(&text), 4); } + +/// The written context of the block reference at scale `name`: (insertion, rotation). +fn context_at(text: &str, name: &str) -> (Vec2, f64) { + contexts(text).into_iter().find(|c| c.0 == name).map(|c| (c.2, c.3)).unwrap() +} + +#[test] +fn an_unchanged_reference_keeps_its_contexts_when_its_default_one_is_elsewhere() { + // The reference sits at (11, 20) while its default context says (10, 20): saved unchanged, + // every context is written as read (what moves them is what the reference did since). + let d = read_dxf(dxf(&FIXTURE.replace("2 SIGN\n10 10\n20 20\n30 0\n41 5", "2 SIGN\n10 11\n20 20\n30 0\n41 5")).as_bytes()).unwrap(); + let text = write_dxf(&d); + for scale in ["1:1", "1:5"] { + assert_eq!(context_at(&text, scale).0, Vec2::new(10.0, 20.0), "{scale}"); + } + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); +} + +#[test] +fn a_context_s_own_offset_scales_turns_and_mirrors_with_the_reference() { + // The 1:1 context sits 2 to the right of the reference. Scaled 2 and turned 90°, it is 4 + // above; mirrored (x scale -5), 2 to the left. + let src = FIXTURE.replace("340 51\n50 0\n10 10", "340 51\n50 0\n10 12"); + let edit = |f: &dyn Fn(&mut cadcraft_doc::Insert)| { + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + f(i); + } + }) + .unwrap(); + write_dxf(&d) + }; + let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + let text = edit(&|i| { + i.scale = i.scale * 2.0; + i.rotation = 90f64.to_radians(); + }); + let (at, rot) = context_at(&text, "1:1"); + assert!(near(at, 10.0, 24.0) && (rot - 90.0).abs() < 1e-9, "{at:?} {rot}"); + let text = edit(&|i| i.scale.x = -i.scale.x); + let (at, _) = context_at(&text, "1:1"); + assert!(near(at, 8.0, 20.0), "{at:?}"); +} + +#[test] +fn the_default_context_is_the_one_whose_first_290_is_1() { + // The 1:1 attribute context comes first, turned 10° in its reference, with its own later + // 290 set: the 1:5 one is still the default, so an unchanged save keeps the 10°. + let at = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 76").unwrap(); + let end = FIXTURE.find("0 ENDSEC\n0 EOF").unwrap(); + let second = FIXTURE[at..end].replace("50 0\n10 11", "50 10\n10 11").replace("21 22\n290 0", "21 22\n290 1"); + let first = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 75").unwrap(); + let src = format!("{}{second}{}{}", &FIXTURE[..first], &FIXTURE[first..at], &FIXTURE[end..]); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + // Moved, so the attribute contexts are brought up to date. + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + for a in &mut i.attribs { + a.text.insert = a.text.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + a.text.align_pt = Some(a.text.insert); + } + } + }) + .unwrap(); + let text = write_dxf(&d); + let recs = records(&text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let rot = recs + .iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .find(|(_, t)| get(t, 340).and_then(|h| scales.get(h)) == Some(&"1:1")) + .and_then(|(_, t)| get(t, 50)) + .and_then(|v| v.parse::().ok()) + .unwrap(); + assert!((rot - 10.0).abs() < 1e-9, "{rot}"); +}