From e284f21ec08e86dd2aeec9271a82cd6fe971d82f Mon Sep 17 00:00:00 2001 From: Skryx Dev Date: Sat, 14 Nov 2026 17:12:17 +0100 Subject: [PATCH] DWG 2013 and 2018: solids and regions keep their geometry (data store section) From AutoCAD 2013 a 3DSOLID, REGION or BODY keeps its modeler description in the file's data store section (AcDb:AcDsPrototype_1b), not in the entity. DraftCraft now reads and writes that section, so these entities survive a DWG 2013/2018 save and open. - crates/dwg/src/datastore.rs: the section read to records (checked reader, capped counts and sizes, blob pages followed) and written as AutoCAD lays out a new store: segment index, data index, data segments, blob pages for records over 0x40000 bytes, schema index and data, search index. AutoCAD's empty sections come out byte for byte. - The writer puts the section after AcDb:XrefManifest when the drawing has solids, and writes the 2013+ modeler entity as AutoCAD does (wireframe block, group 290, GUID, history), with the "data store" bit of its common entity data set: without that bit AutoCAD reports "ASM body missing" for every solid. - The reader decodes the 2013+ entity and turns the section's records into the DXF's ACDSDATA groups, so a DWG read keeps what the DXF of the same drawing keeps. Checked in AutoCAD 2027: solids-2018 (four bodies, one of 2.9 MB in blob pages, with and without solid history) written as DWG 2013 and 2018 opens with every body drawn, AUDIT 0. Co-Authored-By: Claude Opus 5.5 --- crates/dwg/src/compose/file.rs | 17 +- crates/dwg/src/compose/object.rs | 6 +- crates/dwg/src/compose/tests.rs | 1 + crates/dwg/src/datastore.rs | 748 ++++++++++++++++++++++++++ crates/dwg/src/datastore/tests.rs | 136 +++++ crates/dwg/src/file.rs | 11 + crates/dwg/src/lib.rs | 1 + crates/dwg/src/read/object.rs | 8 +- crates/dwg/src/read/probe.rs | 54 ++ crates/io/src/dwg/data_store.rs | 82 +++ crates/io/src/dwg/entities.rs | 82 ++- crates/io/src/dwg/mod.rs | 13 + crates/io/src/dwg/write/common.rs | 1 + crates/io/src/dwg/write/mod.rs | 15 +- crates/io/src/dwg/write/solid.rs | 63 ++- crates/io/src/dwg/write/tests.rs | 17 +- crates/io/tests/it/acis_data_store.rs | 47 +- docs/dwg-handoff.md | 23 +- docs/dwg-writer-handoff.md | 13 +- docs/dwg.md | 2 +- 20 files changed, 1310 insertions(+), 30 deletions(-) create mode 100644 crates/dwg/src/datastore.rs create mode 100644 crates/dwg/src/datastore/tests.rs create mode 100644 crates/io/src/dwg/data_store.rs diff --git a/crates/dwg/src/compose/file.rs b/crates/dwg/src/compose/file.rs index 2a93a8f0..f434f519 100644 --- a/crates/dwg/src/compose/file.rs +++ b/crates/dwg/src/compose/file.rs @@ -61,6 +61,9 @@ pub struct Parts<'a> { pub app_version: &'a str, /// The font file of each text style, with the style's handle. pub fonts: &'a [(String, u64)], + /// The data store section (2013 and later: the modeler descriptions of solids, regions and + /// bodies, laid out by [`crate::datastore::write`]), when the drawing has any. + pub data_store: Option<&'a [u8]>, } /// The maintenance release each version's file records, as AutoCAD writes it today. @@ -354,12 +357,20 @@ fn paged(p: &Parts<'_>) -> Result> { let history = app_info_history(p); let history_page = round_up(history.len(), 0x80); let compressed = |name, data| Section { name, data, compressed: true, page_size: MAX_PAGE }; - let stream = vec![ + let mut stream = vec![ Section { name: "AcDb:SummaryInfo", data: summary, compressed: false, page_size: summary_page }, Section { name: "AcDb:Preview", data: preview, compressed: false, page_size: preview_page }, Section { name: "AcDb:AppInfo", data: app_info, compressed: false, page_size: app_info_page }, Section { name: "AcDb:AppInfoHistory", data: history, compressed: false, page_size: history_page }, compressed("AcDb:XrefManifest", xref_manifest(p)), + ]; + // AutoCAD files the data store after the xref manifest, in the stream and in the map. + let mut map_order: Vec<&str> = MAP_ORDER.to_vec(); + if let Some(ds) = p.data_store.filter(|_| ver >= V::R2013) { + stream.push(compressed("AcDb:AcDsPrototype_1b", ds.to_vec())); + map_order.insert(1, "AcDb:AcDsPrototype_1b"); + } + stream.extend([ compressed("AcDb:RevHistory", shared::rev_history()), compressed("AcDb:AcDbObjects", objects), compressed("AcDb:ObjFreeSpace", obj_free_space(p)), @@ -368,7 +379,7 @@ fn paged(p: &Parts<'_>) -> Result> { compressed("AcDb:Classes", classes_section(ver, p.codepage, p.text, p.classes)), compressed("AcDb:AuxHeader", aux_header(p)), compressed("AcDb:Header", header(p)), - ]; + ]); let mut code = [0u8; 6]; code.copy_from_slice(ver.magic().as_bytes().get(..6).unwrap_or(b"AC1032")); let info = FileInfo { @@ -379,7 +390,7 @@ fn paged(p: &Parts<'_>) -> Result> { codepage: p.codepage, acad_maintenance: if ver >= V::R2018 { shared::ACAD_MAINTENANCE } else { 0 }, }; - container::pack(&info, &stream, &MAP_ORDER) + container::pack(&info, &stream, &map_order) } /// AutoCAD 2007: named sections in pages of Reed-Solomon codewords. diff --git a/crates/dwg/src/compose/object.rs b/crates/dwg/src/compose/object.rs index 2812e30e..76696fbb 100644 --- a/crates/dwg/src/compose/object.rs +++ b/crates/dwg/src/compose/object.rs @@ -70,6 +70,9 @@ pub struct EntityStart<'a> { /// entity names its neighbours): `None` when they are the objects with the handles just /// below and above this one's. pub links: Option<(u64, u64)>, + /// The entity keeps data in the file's data store section (AutoCAD 2013 on): a solid's, + /// region's or body's modeler description. AutoCAD looks for a record only when this is set. + pub data_store: bool, } impl Default for EntityStart<'_> { @@ -92,6 +95,7 @@ impl Default for EntityStart<'_> { invisible: false, lineweight: 29, links: None, + data_store: false, } } } @@ -248,7 +252,7 @@ impl ObjectWriter { self.dat.b(e.xdictionary == 0); } if ver >= V::R2013 { - self.dat.b(false); + self.dat.b(e.data_store); } if ver <= V::R2000 { self.dat.b(e.links.is_none()); diff --git a/crates/dwg/src/compose/tests.rs b/crates/dwg/src/compose/tests.rs index e4560ddc..69fb389b 100644 --- a/crates/dwg/src/compose/tests.rs +++ b/crates/dwg/src/compose/tests.rs @@ -255,6 +255,7 @@ fn autocads_files_compose_again() { app_name: "DraftCraft", app_version: "3.0.0", fonts: &[("txt".into(), 0xF)], + data_store: None, }; let out = compose(&parts).unwrap_or_else(|e| panic!("{name}: {e}")); let again = crate::file::DwgFile::open(&out).unwrap_or_else(|e| panic!("{name}: {e}")); diff --git a/crates/dwg/src/datastore.rs b/crates/dwg/src/datastore.rs new file mode 100644 index 00000000..02507875 --- /dev/null +++ b/crates/dwg/src/datastore.rs @@ -0,0 +1,748 @@ +//! The data store section of AutoCAD 2013 and later files (`AcDb:AcDsPrototype_1b`, spec +//! chapter 24): where 3D solids, regions and bodies keep their modeler description (binary +//! ACIS), one record per entity, and where AutoCAD 2027 keeps the drawing's thumbnail. +//! +//! A byte stream, not a bit stream: a file header, then file segments (each a header, its data +//! and padding to a multiple of 0x80 bytes). The segment index lists where each segment is; the +//! data index lists each record (its data segment, where its header is, its schema); a data +//! segment holds the records' headers (handle and where the data is) and their data, a record +//! larger than 0x40000 bytes in pages of blob segments; the schema index and schema data name +//! what each record is; the search segment lists each schema's records by handle (AutoCAD +//! ignores a record that is not listed there). +//! +//! [`read`] takes a section apart; [`write`] lays one out the way AutoCAD lays out a new file +//! (revision 1, each segment once, in index order), and [`solids`] is the store of a drawing's +//! modeler records: the schema AutoCAD gives them and its four standard schemas. + +use std::collections::BTreeMap; + +/// A record's data, by the entity it belongs to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Record { + pub handle: u64, + /// The record's schema: an index into [`Store::schemas`]. + pub schema: u32, + pub data: Vec, +} + +/// One property of a schema: a name and a typed value list. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Property { + pub flags: u32, + pub name: String, + /// The value type (0 to 15), `None` when flag 2 says it has none. + pub kind: Option, + /// The size of a value of the custom type (14). + pub custom_size: u32, + /// The number that follows flag 1 or flag 8. + pub extra: u32, + pub values: Vec>, +} + +/// A schema: what a kind of record holds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Schema { + pub name: String, + pub indexes: Vec, + pub properties: Vec, +} + +/// A data store: its schemas, the unknown properties (size and flags, with the id the schema +/// index gives each) and its records. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Store { + pub schemas: Vec, + pub unknown: Vec<(u32, u32, u32)>, + pub records: Vec, +} + +impl Store { + /// The records of the schema named `name`. + pub fn records_of<'a>(&'a self, name: &'a str) -> impl Iterator + 'a { + let index = self.schemas.iter().position(|s| s.name == name).and_then(|i| u32::try_from(i).ok()); + self.records.iter().filter(move |r| Some(r.schema) == index) + } +} + +/// The schema of a solid's, region's or body's modeler description. +pub const ASM_SCHEMA: &str = "AcDb3DSolid_ASM_Data"; + +/// Why a data store could not be read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "data store: {}", self.0) + } +} + +impl std::error::Error for Error {} + +type Result = std::result::Result; + +fn err(what: &str) -> Result { + Err(Error(what.to_string())) +} + +const SIGNATURE: &[u8; 4] = b"jard"; +const SEGMENT_SIGNATURE: u16 = 0xD5AC; +const SEGMENT_HEADER: usize = 0x30; +/// The size of a record header in a data segment. +const RECORD_HEADER: usize = 20; +/// The first four bytes of a record whose data is in blob pages. +const BLOB_REFERENCE: u32 = 0xBB10_6BB1; +/// The largest record kept in a data segment; a larger one goes in blob pages. +const MAX_INLINE: usize = 0x40000; +/// The most data one blob page holds. +const BLOB_PAGE: usize = 0xF_FFB0; +/// A data segment is closed once its records pass this many bytes. +const DATA_SEGMENT: usize = 0x10_0000; +/// The size of a value of each type (spec 24.2.2.6.1.1). +const TYPE_SIZES: [u32; 16] = [0, 0, 2, 1, 2, 4, 8, 1, 2, 4, 8, 4, 8, 0, 0, 0]; +/// Most segments, records, schemas, properties, names and values read (a damaged file's counts +/// can be anything). +const MAX_COUNT: usize = 1 << 20; +/// Most bytes of record data read in all. +const MAX_DATA: usize = 1 << 30; + +/// A little-endian reader over a section, every read checked. +struct Bytes<'a> { + b: &'a [u8], + at: usize, +} + +impl<'a> Bytes<'a> { + fn new(b: &'a [u8], at: usize) -> Bytes<'a> { + Bytes { b, at } + } + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self.at.checked_add(n).ok_or_else(|| Error("offset overflow".into()))?; + let s = self.b.get(self.at..end).ok_or_else(|| Error(format!("reads past the end at {:#x}", self.at)))?; + self.at = end; + Ok(s) + } + fn u16(&mut self) -> Result { + let s = self.take(2)?; + Ok(u16::from_le_bytes([s.first().copied().unwrap_or(0), s.get(1).copied().unwrap_or(0)])) + } + fn u32(&mut self) -> Result { + let mut a = [0u8; 4]; + a.copy_from_slice(self.take(4)?); + Ok(u32::from_le_bytes(a)) + } + fn u64(&mut self) -> Result { + let mut a = [0u8; 8]; + a.copy_from_slice(self.take(8)?); + Ok(u64::from_le_bytes(a)) + } + fn count(&mut self) -> Result { + let n = usize::try_from(self.u32()?).map_err(|_| Error("count overflow".into()))?; + if n > MAX_COUNT { err("implausible count") } else { Ok(n) } + } + /// A zero-terminated name. + fn name(&mut self) -> Result { + let rest = self.b.get(self.at..).unwrap_or(&[]); + let n = rest.iter().position(|&c| c == 0).ok_or_else(|| Error("a name runs past the end".into()))?; + let s = String::from_utf8_lossy(self.take(n)?).into_owned(); + self.at += 1; + Ok(s) + } +} + +/// A segment's header fields: index, unknown, size, unknown, revision, unknown, system data +/// offset (in 16 bytes), object data offset (in 16 bytes). +struct SegmentHeader { + system_offset: usize, + object_offset: usize, +} + +fn segment_header(b: &[u8], at: usize) -> Result { + let mut r = Bytes::new(b, at); + if r.u16()? != SEGMENT_SIGNATURE { + return err("a segment without its signature"); + } + let _name = r.take(6)?; + let _index = r.u32()?; + let _unknown = r.u32()?; + let _size = r.u32()?; + let _unknown2 = r.u32()?; + let _revision = r.u32()?; + let _unknown3 = r.u32()?; + let system_offset = (r.u32()? as usize).checked_mul(16).ok_or_else(|| Error("offset overflow".into()))?; + let object_offset = (r.u32()? as usize).checked_mul(16).ok_or_else(|| Error("offset overflow".into()))?; + Ok(SegmentHeader { system_offset, object_offset }) +} + +/// Read a data store section. +pub fn read(b: &[u8]) -> Result { + let mut h = Bytes::new(b, 0); + if h.take(4)? != SIGNATURE { + return err("not a data store"); + } + let _header_size = h.u32()?; + let _unknown = h.u32()?; + let _version = h.u32()?; + let _unknown2 = h.u32()?; + let _revision = h.u32()?; + let segment_index_at = h.u32()? as usize; + let _unknown3 = h.u32()?; + let segment_count = h.count()?; + let schema_index = h.u32()? as usize; + let data_index = h.u32()? as usize; + let _search = h.u32()?; + + // Where each segment starts. + let mut s = Bytes::new(b, segment_index_at.checked_add(SEGMENT_HEADER).ok_or_else(|| Error("offset overflow".into()))?); + let mut segments = Vec::with_capacity(segment_count.min(4096)); + for _ in 0..segment_count { + let at = usize::try_from(s.u64()?).map_err(|_| Error("offset overflow".into()))?; + let size = s.u32()? as usize; + segments.push((at, size)); + } + let segment = |i: usize| -> Result { + match segments.get(i) { + Some(&(at, size)) if size > 0 => Ok(at), + _ => err("a reference to a missing segment"), + } + }; + + // The schemas and the names of their properties. + let index_at = segment(schema_index)?; + let index_header = segment_header(b, index_at)?; + let mut x = Bytes::new(b, index_at + SEGMENT_HEADER); + let schema_count = x.count()?; + let _unknown = x.u32()?; + let mut schema_refs = Vec::with_capacity(schema_count.min(4096)); + for _ in 0..schema_count { + let index = x.u32()?; + let seg = x.u32()? as usize; + let local = x.u32()? as usize; + schema_refs.push((index, seg, local)); + } + let _marker = x.u64()?; + let unknown_count = x.count()?; + let _unknown2 = x.u32()?; + let mut unknown_refs = Vec::with_capacity(unknown_count.min(4096)); + for _ in 0..unknown_count { + let seg = x.u32()? as usize; + let local = x.u32()? as usize; + let id = x.u32()?; + unknown_refs.push((seg, local, id)); + } + let mut n = Bytes::new(b, index_at + index_header.system_offset); + let name_count = n.count()?; + let mut schema_names = Vec::with_capacity(name_count.min(4096)); + for _ in 0..name_count { + schema_names.push(n.name()?); + } + + // Each schema data segment's property names. + let mut property_names: BTreeMap> = BTreeMap::new(); + let mut names_of = |seg: usize| -> Result> { + if let Some(v) = property_names.get(&seg) { + return Ok(v.clone()); + } + let at = segment(seg)?; + let hd = segment_header(b, at)?; + let mut n = Bytes::new(b, at + hd.system_offset); + let count = n.count()?; + let mut v = Vec::with_capacity(count.min(4096)); + for _ in 0..count { + v.push(n.name()?); + } + property_names.insert(seg, v.clone()); + Ok(v) + }; + let mut unknown = Vec::with_capacity(unknown_refs.len()); + for &(seg, local, id) in &unknown_refs { + let mut u = Bytes::new(b, segment(seg)? + SEGMENT_HEADER + local); + unknown.push((id, u.u32()?, u.u32()?)); + } + let mut schemas: Vec<(u32, Schema)> = Vec::with_capacity(schema_refs.len()); + for (k, &(index, seg, local)) in schema_refs.iter().enumerate() { + let names = names_of(seg)?; + let mut r = Bytes::new(b, segment(seg)? + SEGMENT_HEADER + local); + let mut schema = schema(&mut r, &names)?; + schema.name = schema_names.get(k).cloned().unwrap_or_default(); + schemas.push((index, schema)); + } + schemas.sort_by_key(|(i, _)| *i); + + // The records. + let mut d = Bytes::new(b, segment(data_index)? + SEGMENT_HEADER); + let record_count = d.count()?; + let _unknown = d.u32()?; + let mut records = Vec::with_capacity(record_count.min(4096)); + let mut total = 0usize; + for _ in 0..record_count { + let seg = d.u32()? as usize; + let local = d.u32()? as usize; + let schema = d.u32()?; + if seg == 0 { + continue; + } + let at = segment(seg)?; + let hd = segment_header(b, at)?; + let mut rh = Bytes::new(b, at + SEGMENT_HEADER + local); + let _entry_size = rh.u32()?; + let _unknown = rh.u32()?; + let handle = rh.u64()?; + let offset = rh.u32()? as usize; + let start = at.checked_add(hd.object_offset).and_then(|v| v.checked_add(offset)).ok_or_else(|| Error("offset overflow".into()))?; + let mut rd = Bytes::new(b, start); + let size = rd.u32()?; + let data = if size == BLOB_REFERENCE { blob(b, &mut rd, &segment)? } else { rd.take(size as usize)?.to_vec() }; + total = total.saturating_add(data.len()); + if total > MAX_DATA { + return err("implausibly much data"); + } + records.push(Record { handle, schema, data }); + } + Ok(Store { schemas: schemas.into_iter().map(|(_, s)| s).collect(), unknown, records }) +} + +/// A record's data from its blob pages. +fn blob(b: &[u8], r: &mut Bytes<'_>, segment: &dyn Fn(usize) -> Result) -> Result> { + let total = usize::try_from(r.u64()?).map_err(|_| Error("size overflow".into()))?; + if total > MAX_DATA { + return err("an implausibly large record"); + } + let pages = r.count()?; + let _record_size = r.u32()?; + let _page_size = r.u32()?; + let _last_page = r.u32()?; + let _unknown = r.u32()?; + let _unknown2 = r.u32()?; + let mut out = Vec::with_capacity(total); + for _ in 0..pages { + let seg = r.u32()? as usize; + let _size = r.u32()?; + let mut p = Bytes::new(b, segment(seg)? + SEGMENT_HEADER); + let _total = p.u64()?; + let _start = p.u64()?; + let _index = p.u32()?; + let _count = p.u32()?; + let n = usize::try_from(p.u64()?).map_err(|_| Error("size overflow".into()))?; + if out.len().saturating_add(n) > total { + return err("blob pages hold more than the record"); + } + out.extend_from_slice(p.take(n)?); + } + Ok(out) +} + +fn schema(r: &mut Bytes<'_>, names: &[String]) -> Result { + let n = r.u16()?; + let mut indexes = Vec::with_capacity(usize::from(n)); + for _ in 0..n { + indexes.push(r.u64()?); + } + let n = r.u16()?; + let mut properties = Vec::with_capacity(usize::from(n)); + for _ in 0..n { + let flags = r.u32()?; + let name_index = r.u32()?; + let name = names.get(name_index as usize).cloned().unwrap_or_default(); + let (mut kind, mut custom_size, mut size) = (None, 0, 0); + if flags & 2 == 0 { + let k = r.u32()?; + if k == 0xE { + custom_size = r.u32()?; + size = custom_size; + } else { + size = TYPE_SIZES.get(k as usize).copied().unwrap_or(0); + } + kind = Some(k); + } + let extra = if flags == 1 || flags == 8 { r.u32()? } else { 0 }; + let count = r.u16()?; + let mut values = Vec::with_capacity(usize::from(count)); + if size > 0 { + for _ in 0..count { + values.push(r.take(size as usize)?.to_vec()); + } + } + properties.push(Property { flags, name, kind, custom_size, extra, values }); + } + Ok(Schema { name: String::new(), indexes, properties }) +} + +/// The store of a drawing's modeler records, as AutoCAD (and the Open Design Alliance) lay out +/// a new one: the modeler schema first, then the four standard schemas. +pub fn solids(records: &[(u64, &[u8])]) -> Store { + let flag = |name: &str| Schema { + name: format!("{name}Schema"), + indexes: Vec::new(), + properties: vec![Property { flags: 0, name: name.to_string(), kind: Some(1), custom_size: 0, extra: 0, values: Vec::new() }], + }; + let mut indexable = flag("AcDs:Indexable"); + indexable.name = "AcDbDs::IndexedPropertySchema".into(); + let schemas = vec![ + Schema { + name: ASM_SCHEMA.into(), + indexes: vec![0, 1], + properties: vec![ + Property { + flags: 0, + name: "AcDbDs::ID".into(), + kind: Some(10), + custom_size: 0, + extra: 0, + values: vec![2u64.to_le_bytes().to_vec(), 3u64.to_le_bytes().to_vec()], + }, + Property { flags: 0, name: "ASM_Data".into(), kind: Some(15), custom_size: 0, extra: 0, values: Vec::new() }, + ], + }, + flag("AcDbDs::TreatedAsObjectData"), + flag("AcDbDs::Legacy"), + indexable, + Schema { + name: "AcDbDs::HandleAttributeSchema".into(), + indexes: Vec::new(), + properties: vec![Property { + flags: 8, + name: "AcDbDs::HandleAttribute".into(), + kind: Some(7), + custom_size: 0, + extra: 1, + values: vec![vec![0]], + }], + }, + ]; + Store { + schemas, + unknown: vec![(1, 8, 1), (2, 8, 1), (3, 8, 1), (4, 8, 0)], + records: records.iter().map(|(h, d)| Record { handle: *h, schema: 0, data: d.to_vec() }).collect(), + } +} + +/// One segment being laid out: its name, its data and the two offsets its header records. +struct Seg { + name: &'static [u8; 6], + unknown: u32, + data: Vec, + /// Where the data stops and the 0x70 padding starts, before the segment is rounded up. + system_offset: u32, + object_offset: u32, +} + +fn pad_to(v: &mut Vec, multiple: usize, byte: u8) { + while !v.len().is_multiple_of(multiple) { + v.push(byte); + } +} + +/// Pad a segment's data so what follows starts on a 16-byte boundary of the segment. +fn pad_to_boundary(v: &mut Vec, byte: u8) { + while !(SEGMENT_HEADER + v.len()).is_multiple_of(16) { + v.push(byte); + } +} + +fn put32(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn put64(v: &mut Vec, x: u64) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn len32(n: usize) -> u32 { + u32::try_from(n).unwrap_or(u32::MAX) +} + +/// Lay out a data store section. +pub fn write(store: &Store) -> Vec { + // Segment numbers: 0 unused, 1 the segment index, 2 the data index, then the data segments, + // the schema index, the schema data, the search segment, and the blob pages last. + let groups = data_groups(store); + let first_data = 3usize; + let schema_index = first_data + groups.len(); + let schema_data = schema_index + 1; + let search = schema_data + 1; + let data = data_segments(store, &groups, first_data, search + 1); + let (sdata, names_offset, schema_at, unknown_at) = schema_data_segment(store); + let (sindex, schema_names_offset) = schema_index_segment(store, &schema_at, &unknown_at, len32(schema_data)); + + // The segments in order, then the segment index that lists them. + let mut ordered: Vec = vec![Seg { name: b"datidx", unknown: 0, data: data.index, system_offset: 0, object_offset: 0 }]; + ordered.extend(data.segments); + ordered.push(Seg { name: b"schidx", unknown: 0, data: sindex, system_offset: schema_names_offset, object_offset: 0 }); + ordered.push(Seg { name: b"schdat", unknown: 0, data: sdata, system_offset: names_offset, object_offset: 0 }); + ordered.push(Seg { name: b"search", unknown: 0, data: search_segment(store), system_offset: 0, object_offset: 0 }); + ordered.extend(data.blobs); + lay_out(&ordered, schema_index, search) +} + +/// The records split into data segments of at most [`DATA_SEGMENT`] bytes: (record number, +/// record) lists. +fn data_groups(store: &Store) -> Vec> { + let mut groups: Vec> = vec![Vec::new()]; + let mut size = 0usize; + for (k, r) in store.records.iter().enumerate() { + let stored = if r.data.len() > MAX_INLINE { 52 } else { r.data.len() + 4 }; + if size > 0 && size + stored > DATA_SEGMENT { + groups.push(Vec::new()); + size = 0; + } + size += stored; + if let Some(last) = groups.last_mut() { + last.push((k, r)); + } + } + groups +} + +/// The data segments, the data index that finds each record, and the blob pages of the large +/// records. +struct DataSegments { + segments: Vec, + index: Vec, + blobs: Vec, +} + +fn data_segments(store: &Store, groups: &[Vec<(usize, &Record)>], first_data: usize, first_blob: usize) -> DataSegments { + let mut segments: Vec = Vec::new(); + let mut index_entries: Vec<(u32, u32, u32)> = vec![(0, 0, 0); store.records.len()]; + let mut blobs: Vec = Vec::new(); + for (n, list) in groups.iter().enumerate() { + let seg_no = len32(first_data + n); + let mut heads = Vec::new(); + let mut body = Vec::new(); + for (j, (k, r)) in list.iter().enumerate() { + if let Some(e) = index_entries.get_mut(*k) { + *e = (seg_no, len32(j * RECORD_HEADER), r.schema); + } + put32(&mut heads, len32(RECORD_HEADER)); + put32(&mut heads, 1); + put64(&mut heads, r.handle); + put32(&mut heads, len32(body.len())); + if r.data.len() <= MAX_INLINE { + put32(&mut body, len32(r.data.len())); + body.extend_from_slice(&r.data); + } else { + blob_reference(&mut body, &r.data, first_blob + blobs.len(), &mut blobs); + } + } + // The data starts on a 16-byte boundary of the segment, after the headers. + let mut data = heads; + pad_to_boundary(&mut data, 0x62); + let object_offset = len32((SEGMENT_HEADER + data.len()) / 16); + data.extend_from_slice(&body); + segments.push(Seg { name: b"_data_", unknown: 0, data, system_offset: 0, object_offset }); + } + let mut index = Vec::new(); + put32(&mut index, len32(index_entries.len())); + put32(&mut index, 0); + for (s, l, sc) in &index_entries { + put32(&mut index, *s); + put32(&mut index, *l); + put32(&mut index, *sc); + } + DataSegments { segments, index, blobs } +} + +/// A large record: a reference to its blob pages in `body`, the pages (segments numbered from +/// `first`) added to `blobs`. +fn blob_reference(body: &mut Vec, data: &[u8], first: usize, blobs: &mut Vec) { + let pages: Vec<&[u8]> = data.chunks(BLOB_PAGE).collect(); + put32(body, BLOB_REFERENCE); + put64(body, data.len() as u64); + put32(body, len32(pages.len())); + put32(body, len32(32 + 8 * pages.len())); + put32(body, len32(BLOB_PAGE.min(data.len()))); + put32(body, len32(pages.last().map_or(0, |p| p.len()))); + put32(body, 0); + put32(body, 0); + let mut start = 0u64; + for (i, p) in pages.iter().enumerate() { + put32(body, len32(first + i)); + put32(body, len32(p.len())); + let mut page = Vec::with_capacity(p.len() + 32); + put64(&mut page, data.len() as u64); + put64(&mut page, start); + put32(&mut page, len32(i)); + put32(&mut page, len32(pages.len())); + put64(&mut page, p.len() as u64); + page.extend_from_slice(p); + start += p.len() as u64; + blobs.push(Seg { name: b"blob01", unknown: 1, data: page, system_offset: 0, object_offset: 0 }); + } +} + +/// The schema data: the unknown properties, the schemas, then the property names. With the +/// names' place (in 16 bytes), each schema's place, and each unknown property's (place, id). +fn schema_data_segment(store: &Store) -> (Vec, u32, Vec, Vec<(u32, u32)>) { + let mut names: Vec = Vec::new(); + let mut name_index = |n: &str| -> u32 { + match names.iter().position(|x| x == n) { + Some(i) => len32(i), + None => { + names.push(n.to_string()); + len32(names.len() - 1) + } + } + }; + let mut sdata = Vec::new(); + let mut unknown_at = Vec::new(); + for (id, size, flags) in &store.unknown { + unknown_at.push((len32(sdata.len()), *id)); + put32(&mut sdata, *size); + put32(&mut sdata, *flags); + } + let mut schema_at = Vec::new(); + for s in &store.schemas { + schema_at.push(len32(sdata.len())); + sdata.extend_from_slice(&u16::try_from(s.indexes.len()).unwrap_or(0).to_le_bytes()); + for i in &s.indexes { + put64(&mut sdata, *i); + } + sdata.extend_from_slice(&u16::try_from(s.properties.len()).unwrap_or(0).to_le_bytes()); + for p in &s.properties { + put32(&mut sdata, p.flags); + put32(&mut sdata, name_index(&p.name)); + if let Some(k) = p.kind { + put32(&mut sdata, k); + if k == 0xE { + put32(&mut sdata, p.custom_size); + } + } + if p.flags == 1 || p.flags == 8 { + put32(&mut sdata, p.extra); + } + sdata.extend_from_slice(&u16::try_from(p.values.len()).unwrap_or(0).to_le_bytes()); + for v in &p.values { + sdata.extend_from_slice(v); + } + } + } + pad_to_boundary(&mut sdata, 0x73); + let names_offset = len32((SEGMENT_HEADER + sdata.len()) / 16); + put32(&mut sdata, len32(names.len())); + for n in &names { + sdata.extend_from_slice(n.as_bytes()); + sdata.push(0); + } + (sdata, names_offset, schema_at, unknown_at) +} + +/// The schema index: each schema's place, the unknown properties' places, then the schema names +/// (their place, in 16 bytes, returned with it). +fn schema_index_segment(store: &Store, schema_at: &[u32], unknown_at: &[(u32, u32)], schema_data_no: u32) -> (Vec, u32) { + let mut sindex = Vec::new(); + put32(&mut sindex, len32(store.schemas.len())); + put32(&mut sindex, 0); + for (i, at) in schema_at.iter().enumerate() { + put32(&mut sindex, len32(i)); + put32(&mut sindex, schema_data_no); + put32(&mut sindex, *at); + } + put64(&mut sindex, 0x000A_F10C); + put32(&mut sindex, len32(unknown_at.len())); + put32(&mut sindex, 0); + for (at, id) in unknown_at { + put32(&mut sindex, schema_data_no); + put32(&mut sindex, *at); + put32(&mut sindex, *id); + } + pad_to_boundary(&mut sindex, 0x73); + let schema_names_offset = len32((SEGMENT_HEADER + sindex.len()) / 16); + put32(&mut sindex, len32(store.schemas.len())); + for s in &store.schemas { + sindex.extend_from_slice(s.name.as_bytes()); + sindex.push(0); + } + (sindex, schema_names_offset) +} + +/// The search segment: for each schema with records, the numbers of its records' data index +/// entries in order, then the records by handle with that number, as AutoCAD writes it. +fn search_segment(store: &Store) -> Vec { + let mut found = Vec::new(); + let with_records: Vec<(usize, Vec<(u64, usize)>)> = store + .schemas + .iter() + .enumerate() + .filter_map(|(i, _)| { + let mut list: Vec<(u64, usize)> = + store.records.iter().enumerate().filter(|(_, r)| r.schema as usize == i).map(|(k, r)| (r.handle, k)).collect(); + list.sort(); + (!list.is_empty()).then_some((i, list)) + }) + .collect(); + put32(&mut found, len32(with_records.len())); + for (i, list) in &with_records { + put32(&mut found, len32(*i)); + put64(&mut found, list.len() as u64); + let mut numbers: Vec = list.iter().map(|(_, k)| *k).collect(); + numbers.sort_unstable(); + for k in numbers { + put64(&mut found, k as u64); + } + put32(&mut found, 1); + put32(&mut found, 0); + put32(&mut found, len32(list.len())); + for (h, k) in list { + put64(&mut found, *h); + put64(&mut found, 1); + put64(&mut found, *k as u64); + } + } + found +} + +/// The file header, the segment index and the segments in order (numbered from 2). +fn lay_out(ordered: &[Seg], schema_index: usize, search: usize) -> Vec { + let count = ordered.len() + 2; + let index_size = round(SEGMENT_HEADER + round(12 * count, 16), 0x80); + let mut places: Vec<(u64, u32)> = vec![(0, 0), (0x80, len32(index_size))]; + let mut at = 0x80 + index_size; + for s in ordered { + let size = round(SEGMENT_HEADER + s.data.len(), 0x80); + places.push((at as u64, len32(size))); + at += size; + } + let total = at; + + let mut out = Vec::with_capacity(total); + out.extend_from_slice(SIGNATURE); + for v in [0x80, 8, 2, 0, 1, 0x80, 0, len32(count), len32(schema_index), 2, len32(search), 0, len32(total)] { + put32(&mut out, v); + } + out.resize(0x80, 0); + let mut index_data = Vec::new(); + for (a, s) in &places { + put64(&mut index_data, *a); + put32(&mut index_data, *s); + } + pad_to(&mut index_data, 16, 0); + segment(&mut out, &Seg { name: b"segidx", unknown: 0, data: index_data, system_offset: 0, object_offset: 0 }, 1); + for (i, s) in ordered.iter().enumerate() { + segment(&mut out, s, len32(i + 2)); + } + out +} + +fn round(n: usize, to: usize) -> usize { + n.div_ceil(to) * to +} + +/// One segment: header, data, 0x70 padding to a multiple of 0x80 bytes. +fn segment(out: &mut Vec, s: &Seg, index: u32) { + let start = out.len(); + out.extend_from_slice(&SEGMENT_SIGNATURE.to_le_bytes()); + out.extend_from_slice(s.name); + let size = round(SEGMENT_HEADER + s.data.len(), 0x80); + for v in [index, s.unknown, len32(size), 0, 1, 0, s.system_offset, s.object_offset] { + put32(out, v); + } + out.extend_from_slice(&[0x55; 8]); + out.extend_from_slice(&s.data); + while out.len() - start < size { + out.push(0x70); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/dwg/src/datastore/tests.rs b/crates/dwg/src/datastore/tests.rs new file mode 100644 index 00000000..9b2ababf --- /dev/null +++ b/crates/dwg/src/datastore/tests.rs @@ -0,0 +1,136 @@ +use super::*; + +fn u32_at(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) +} + +/// A stand-in modeler description of `n` bytes. +fn sab(n: usize, seed: u8) -> Vec { + let mut v = b"ASM BinaryFile4".to_vec(); + v.extend((0..n.saturating_sub(15)).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))); + v.truncate(n); + v +} + +#[test] +fn a_store_reads_back_as_written() { + let a = sab(838, 1); + let b = sab(7780, 2); + let store = solids(&[(0x2EB, &a), (0x2E2, &b)]); + let bytes = write(&store); + assert_eq!(&bytes[..4], b"jard"); + assert_eq!(bytes.len() % 0x80, 0); + assert_eq!(u32_at(&bytes, 0x34) as usize, bytes.len(), "the header records the size"); + let back = read(&bytes).unwrap(); + assert_eq!(back, store); + let got: Vec<(u64, usize)> = back.records_of(ASM_SCHEMA).map(|r| (r.handle, r.data.len())).collect(); + assert_eq!(got, vec![(0x2EB, 838), (0x2E2, 7780)]); +} + +/// The layout AutoCAD gives a new store: the file header, the segment index first, every +/// segment signed and named, its data padded with 0x70 to a multiple of 0x80 bytes. +#[test] +fn the_layout_is_autocads() { + let a = sab(100, 3); + let bytes = write(&solids(&[(0x2E2, &a)])); + // jard, header size, 8, version 2, 0, revision 1, segment index at 0x80, 0, 7 segments, + // schema index 4, data index 2, search 6, no previous save. + let header: Vec = (0..13).map(|i| u32_at(&bytes, 4 + 4 * i)).collect(); + assert_eq!(&header[..12], &[0x80, 8, 2, 0, 1, 0x80, 0, 7, 4, 2, 6, 0]); + let names: Vec<&[u8]> = (0..7) + .skip(1) + .map(|i| { + let at = u32_at(&bytes, 0x80 + 0x30 + 12 * i) as usize; + assert_eq!(&bytes[at..at + 2], &[0xAC, 0xD5]); + assert_eq!(u32_at(&bytes, at + 8) as usize, i, "the segment's own index"); + assert_eq!(&bytes[at + 0x28..at + 0x30], &[0x55; 8]); + &bytes[at + 2..at + 8] + }) + .collect(); + assert_eq!(names, [&b"segidx"[..], b"datidx", b"_data_", b"schidx", b"schdat", b"search"]); + // The data segment: one record header (size 20, 1, handle, offset 0), its data on the next + // 16-byte boundary (0x50), padded with 0x62 up to there. + let data = u32_at(&bytes, 0x80 + 0x30 + 12 * 3) as usize; + assert_eq!(u32_at(&bytes, data + 0x24), 5, "the data starts at 0x50"); + assert_eq!(u32_at(&bytes, data + 0x30), 20); + assert_eq!(u32_at(&bytes, data + 0x34), 1); + assert_eq!(u32_at(&bytes, data + 0x38), 0x2E2); + assert_eq!(&bytes[data + 0x44..data + 0x50], &[0x62; 12]); + assert_eq!(u32_at(&bytes, data + 0x50), 100); + assert_eq!(&bytes[data + 0x54..data + 0x54 + 15], b"ASM BinaryFile4"); +} + +/// A record larger than 0x40000 bytes is stored in blob pages of at most 0xFFFB0 bytes. +#[test] +fn a_large_record_goes_in_blob_pages() { + let big = sab(2_971_153, 4); + let small = sab(692, 5); + let bytes = write(&solids(&[(0x928, &big), (0x2E6, &small)])); + let back = read(&bytes).unwrap(); + assert_eq!(back.records.len(), 2); + assert_eq!(back.records[0].data, big); + assert_eq!(back.records[1].data, small); + let count = u32_at(&bytes, 0x20) as usize; + let blobs = (1..count).filter(|&i| { + let at = u32_at(&bytes, 0x80 + 0x30 + 12 * i) as usize; + &bytes[at + 2..at + 8] == b"blob01" + }); + assert_eq!(blobs.count(), 3, "2,971,153 bytes in pages of 1,048,496"); +} + +/// Many records fill more than one data segment. +#[test] +fn many_records_fill_several_data_segments() { + let datas: Vec> = (0..12).map(|i| sab(200_000, i as u8)).collect(); + let records: Vec<(u64, &[u8])> = datas.iter().enumerate().map(|(i, d)| (0x100 + i as u64, d.as_slice())).collect(); + let store = solids(&records); + let back = read(&write(&store)).unwrap(); + assert_eq!(back, store); +} + +/// A damaged section is an error, never a panic. +#[test] +fn hostile_bytes_do_not_panic() { + let a = sab(500, 6); + let good = write(&solids(&[(0x2E2, &a)])); + assert!(read(&[]).is_err()); + assert!(read(b"jard").is_err()); + for cut in [8, 0x40, 0x80, 0x100, good.len() / 2, good.len() - 1] { + let _ = read(&good[..cut]); + } + for at in (0..good.len()).step_by(7) { + let mut b = good.clone(); + b[at] ^= 0xFF; + let _ = read(&b); + b[at] = 0xFF; + let _ = read(&b); + } +} + +/// AutoCAD's own sections, read and written again: `DWG_DS_FILES` names sections written by +/// `probe_dump_section` (`:` between them). The records come back; a section AutoCAD laid out +/// fresh (revision 1, as an empty drawing's) is written byte for byte as AutoCAD wrote it. +#[test] +#[ignore] +fn probe_autocads_sections() { + for f in std::env::var("DWG_DS_FILES").unwrap_or_default().split(':').filter(|f| !f.is_empty()) { + let bytes = std::fs::read(f).unwrap(); + let store = read(&bytes).unwrap(); + println!("{f}: {} schemas {:?}", store.schemas.len(), store.schemas.iter().map(|s| &s.name).collect::>()); + for r in &store.records { + println!( + " record {:X} schema {} {} bytes {:?}", + r.handle, + r.schema, + r.data.len(), + String::from_utf8_lossy(&r.data[..r.data.len().min(15)]) + ); + } + let again = write(&store); + if u32_at(&bytes, 0x14) == 1 { + let first = again.iter().zip(&bytes).position(|(a, b)| a != b); + println!(" fresh layout: same bytes {} (first difference {first:?})", again == bytes); + } + assert_eq!(read(&again).unwrap(), store); + } +} diff --git a/crates/dwg/src/file.rs b/crates/dwg/src/file.rs index 15cb1486..4cb7f08e 100644 --- a/crates/dwg/src/file.rs +++ b/crates/dwg/src/file.rs @@ -226,6 +226,11 @@ impl ObjectReader<'_> { pub fn version(&self) -> read::DwgVersion { self.o.s.ver } + /// True when the object keeps data in the file's data store section (AutoCAD 2013 on): a + /// solid's, region's or body's modeler description. + pub fn has_data_store_record(&self) -> bool { + self.o.has_ds_data + } /// True when the file keeps text apart from the other fields (AutoCAD 2007 and later). pub fn has_string_stream(&self) -> bool { self.o.s.ver.has_string_stream() @@ -508,6 +513,12 @@ impl DwgFile { }) } + /// A named section of a 2004-or-later file, decompressed (`AcDb:AcDsPrototype_1b`, + /// `AcDb:Preview`…). `None` when the file has no such section, or is older. + pub fn section(&self, name: &str) -> Option<&[u8]> { + self.others.iter().find(|(n, _)| n == name).map(|(_, s)| s.as_slice()) + } + /// True for the versions before AutoCAD 2000 (R13 and R14). pub fn before_2000(&self) -> bool { self.version < read::DwgVersion::R2000 diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index d572ab33..e550b324 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -18,6 +18,7 @@ pub mod bits; pub mod compose; pub mod crc; +pub mod datastore; pub mod file; pub mod lz77; pub mod read; diff --git a/crates/dwg/src/read/object.rs b/crates/dwg/src/read/object.rs index ee5c8d81..8130089c 100644 --- a/crates/dwg/src/read/object.rs +++ b/crates/dwg/src/read/object.rs @@ -201,6 +201,8 @@ pub(crate) struct Opened<'a> { flags: EntityFlags, pub num_reactors: u32, pub xdic_missing: bool, + /// The object keeps data in the data store section (AutoCAD 2013 on). + pub has_ds_data: bool, pub xdata: Vec, /// The entity that follows this one in its block's chain (up to AutoCAD 2000), when the /// entity stores it; `None` when the next object of the file follows. @@ -242,6 +244,7 @@ pub(crate) fn open<'a>(ctx: &DecodeCtx, data: &'a [u8], offset: usize) -> Result let mut common: Option = None; let num_reactors; let xdic_missing; + let mut has_ds_data = false; if is_entity { if dat.b()? { let gsize = if ver >= V::R2010 { dat.bll()? } else { dat.rl()? as u64 }; @@ -257,7 +260,7 @@ pub(crate) fn open<'a>(ctx: &DecodeCtx, data: &'a [u8], offset: usize) -> Result flags.xdic_missing = dat.b()?; } if ver >= V::R2013 { - let _has_ds_data = dat.b()?; + has_ds_data = dat.b()?; } if ver <= V::R14 { flags.bylayer_ltype = dat.b()?; @@ -319,7 +322,7 @@ pub(crate) fn open<'a>(ctx: &DecodeCtx, data: &'a [u8], offset: usize) -> Result num_reactors = dat.bl()?; xdic_missing = if ver >= V::R2004 { dat.b()? } else { false }; if ver >= V::R2013 { - let _has_ds_data = dat.b()?; + has_ds_data = dat.b()?; } } @@ -353,6 +356,7 @@ pub(crate) fn open<'a>(ctx: &DecodeCtx, data: &'a [u8], offset: usize) -> Result flags, num_reactors, xdic_missing, + has_ds_data, xdata, next_entity: None, s: Streams { ver, codepage: ctx.codepage, dat, strs, hdl: Some(hdl), text: ctx.text }, diff --git a/crates/dwg/src/read/probe.rs b/crates/dwg/src/read/probe.rs index 8735aafa..87bf310f 100644 --- a/crates/dwg/src/read/probe.rs +++ b/crates/dwg/src/read/probe.rs @@ -311,3 +311,57 @@ fn probe_header_tails() { println!(" tail {} bits {tail}", tail.len()); } } + +/// Writes the named section of each file in `DWG_SECTION_FILES` (separated by `:`) next to it, +/// as `.
.bin`: `DWG_SECTION=AcDb:AcDsPrototype_1b`. +#[test] +#[ignore] +fn probe_dump_section() { + let name = std::env::var("DWG_SECTION").unwrap_or_else(|_| "AcDb:AcDsPrototype_1b".into()); + for f in std::env::var("DWG_SECTION_FILES").unwrap_or_default().split(':').filter(|f| !f.is_empty()) { + let bytes = std::fs::read(f).unwrap(); + if std::env::var_os("DWG_DESCRIBE").is_some() { + println!("{}", r2004::describe(&bytes)); + } + let file = crate::file::DwgFile::open(&bytes).unwrap(); + match file.section(&name) { + Some(s) => { + let out = format!("{f}.{}.bin", name.replace(':', "_")); + std::fs::write(&out, s).unwrap(); + println!("{f}: {} bytes -> {out}", s.len()); + } + None => println!("{f}: no {name}"), + } + } +} + +/// The data bits of each object of `DWG_OBJ_HANDLES` (hex, `,`) in `DWG_OBJ_FILE`, after the +/// common entity data, then its references. +#[test] +#[ignore] +fn probe_object_bits() { + let Ok(f) = std::env::var("DWG_OBJ_FILE") else { return }; + let bytes = std::fs::read(f).unwrap(); + let file = crate::file::DwgFile::open(&bytes).unwrap(); + let want: Vec = std::env::var("DWG_OBJ_HANDLES").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h, 16).ok()).collect(); + for o in file.objects().filter(|o| want.contains(&o.handle)) { + let mut r = file.read_object(&o).unwrap(); + let mut bits = String::new(); + let n = r.remaining_bits(); + for _ in 0..n.min(20000) { + bits.push(if r.b().unwrap() { '1' } else { '0' }); + } + println!("{:X}: {n} data bits\n{bits}", o.handle); + let mut r = file.read_object(&o).unwrap(); + let refs = r.entity_refs(); + println!(" refs {refs:?}"); + let mut more = Vec::new(); + while let Ok(h) = r.reference() { + more.push(format!("{h:X}")); + if more.len() > 8 { + break; + } + } + println!(" then {more:?}"); + } +} diff --git a/crates/io/src/dwg/data_store.rs b/crates/io/src/dwg/data_store.rs new file mode 100644 index 00000000..1e4ffaf0 --- /dev/null +++ b/crates/io/src/dwg/data_store.rs @@ -0,0 +1,82 @@ +//! The data store section of a DWG file from AutoCAD 2013 on (`AcDb:AcDsPrototype_1b`): the ACIS +//! geometry of 3D solids, regions and bodies, which those entities no longer carry themselves. +//! DraftCraft keeps it as the DXF reader does (`Foreign::data_store`): the groups of a DXF +//! ACDSDATA section, laid out as AutoCAD writes one. + +use draftcraft_doc::RawTag; +use draftcraft_dwg::datastore::{self, ASM_SCHEMA}; + +/// Bytes of modeler data on one group 310, as AutoCAD's DXF has them. +const BYTES_PER_LINE: usize = 127; + +/// The groups of an ACDSDATA section holding the store's modeler records, or none when it has +/// none. Records of other schemas (a thumbnail) aren't kept: DraftCraft writes them nowhere. +pub(crate) fn groups(store: &datastore::Store) -> Vec { + let records: Vec<&datastore::Record> = store.records_of(ASM_SCHEMA).filter(|r| r.handle != 0 && !r.data.is_empty()).collect(); + if records.is_empty() { + return Vec::new(); + } + let tag = |code: i32, value: &str| RawTag { code, value: value.to_string() }; + let mut t = vec![tag(70, "2"), tag(71, "4")]; + // The modeler schema (index 0): its two properties, and the four properties every schema + // has, as sub-records. + t.extend([ + tag(0, "ACDSSCHEMA"), + tag(90, "0"), + tag(1, ASM_SCHEMA), + tag(2, "AcDbDs::ID"), + tag(280, "10"), + tag(91, "8"), + tag(2, "ASM_Data"), + tag(280, "15"), + tag(91, "0"), + ]); + for (id, name) in [(1, "AcDbDs::TreatedAsObjectData"), (2, "AcDbDs::Legacy")] { + t.extend([tag(101, "ACDSRECORD"), tag(95, "0"), tag(90, &id.to_string()), tag(2, name), tag(280, "1"), tag(291, "1")]); + } + t.extend([tag(101, "ACDSRECORD"), tag(1, "AcDbDs::ID"), tag(90, "3"), tag(2, "AcDs:Indexable"), tag(280, "1"), tag(291, "1")]); + t.extend([tag(101, "ACDSRECORD"), tag(1, "AcDbDs::ID"), tag(90, "4"), tag(2, "AcDbDs::HandleAttribute"), tag(280, "7"), tag(282, "1")]); + // The schemas of those four properties. + for (i, (schema, property)) in [ + ("AcDbDs::TreatedAsObjectDataSchema", "AcDbDs::TreatedAsObjectData"), + ("AcDbDs::LegacySchema", "AcDbDs::Legacy"), + ("AcDbDs::IndexedPropertySchema", "AcDs:Indexable"), + ] + .iter() + .enumerate() + { + t.extend([tag(0, "ACDSSCHEMA"), tag(90, &(i + 1).to_string()), tag(1, schema), tag(2, property), tag(280, "1"), tag(91, "0")]); + } + t.extend([ + tag(0, "ACDSSCHEMA"), + tag(90, "4"), + tag(1, "AcDbDs::HandleAttributeSchema"), + tag(2, "AcDbDs::HandleAttribute"), + tag(280, "7"), + tag(91, "1"), + tag(284, "1"), + ]); + for r in records { + t.extend([ + tag(0, "ACDSRECORD"), + tag(90, "0"), + tag(2, "AcDbDs::ID"), + tag(280, "10"), + tag(320, &format!("{:X}", r.handle)), + tag(2, "ASM_Data"), + tag(280, "15"), + tag(94, &r.data.len().to_string()), + ]); + t.extend(r.data.chunks(BYTES_PER_LINE).map(|c| RawTag { code: 310, value: hex(c) })); + } + t +} + +fn hex(bytes: &[u8]) -> String { + use std::fmt::Write; + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + let _ = write!(s, "{b:02X}"); + } + s +} diff --git a/crates/io/src/dwg/entities.rs b/crates/io/src/dwg/entities.rs index 55f41c45..11383750 100644 --- a/crates/io/src/dwg/entities.rs +++ b/crates/io/src/dwg/entities.rs @@ -2471,11 +2471,12 @@ const MAX_ACIS_TEXT: usize = 256 << 20; /// text up to AutoCAD 2010. The drawing keeps the entity as the groups a DXF file has: each line /// of the text a group 1, a line longer than 255 characters continued in groups 3. The text is /// stored scrambled in both formats, the same way, and is kept as stored. -/// `None` for the forms not read yet: the binary description, and the files from AutoCAD 2013 -/// on, which keep the description in a section of its own. +/// From AutoCAD 2013 the description is in the data store section (read with the drawing, see +/// `super::read`), and the entity keeps group 290 and its GUID (group 2). +/// `None` for the form not read yet: the binary description of 2004 to 2010. fn modeler(r: &mut ObjectReader, dxf_type: &'static str) -> DwgResult> { if r.version() >= V::R2013 { - return Ok(None); + return modern_modeler(r, dxf_type).map(Some); } let tag = |code: i32, value: String| RawTag { code, value }; let mut t = vec![tag(100, "AcDbModelerGeometry".into())]; @@ -2510,6 +2511,81 @@ fn modeler(r: &mut ObjectReader, dxf_type: &'static str) -> DwgResult DwgResult { + let _described_elsewhere = r.b()?; + let wireframe = r.b()?; + if wireframe { + let _point = r.bd3()?; + let _isolines = r.bl()?; + if r.b()? { + let wires = r.bl()?; + skip_wires(r, wires)?; + } + let silhouettes = r.bl()?; + for _ in 0..r.count(silhouettes.min(MAX_WIRES), 8, "silhouette")? { + let _viewport = r.bl()?; + let _target = r.bd3()?; + let _direction = r.bd3()?; + let _up = r.bd3()?; + let _perspective = r.b()?; + let wires = r.bl()?; + skip_wires(r, wires)?; + } + } + let _end = r.b()?; + let _count = r.bl()?; + let flag = r.b()?; + let a = r.bl()?; + let b = r.bs()?; + let c = r.bs()?; + let mut tail = [0u8; 8]; + for t in &mut tail { + *t = r.rc()?; + } + let tag = |code: i32, value: String| RawTag { code, value }; + let guid = format!( + "{{{a:08x}-{b:04x}-{c:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}}}", + tail[0], tail[1], tail[2], tail[3], tail[4], tail[5], tail[6], tail[7] + ); + let mut t = vec![tag(100, "AcDbModelerGeometry".into()), tag(290, u8::from(flag).to_string()), tag(2, guid)]; + if dxf_type == "3DSOLID" { + t.extend([tag(100, "AcDb3dSolid".into()), tag(350, "0".into())]); + } + Ok(Shape { body: Body::Unknown(dxf_type, t), thickness: 0.0, normal: UP }) +} + +/// Step over `n` wires of a wireframe block: type, selection marker, colour, ACIS index, points, +/// and a transform when one is present. +fn skip_wires(r: &mut ObjectReader, n: u32) -> DwgResult<()> { + for _ in 0..r.count(n.min(MAX_WIRES), 8, "wire")? { + let _kind = r.rc()?; + let _marker = r.bl()?; + let _color = r.bs()?; + let _index = r.bl()?; + let points = r.bl()?; + for _ in 0..r.count(points.min(MAX_WIRES), 6, "wire point")? { + let _p = r.bd3()?; + } + if r.b()? { + for _ in 0..4 { + let _axis = r.bd3()?; + } + let _scale = r.bd()?; + let _rotation = r.b()?; + let _reflection = r.b()?; + let _shear = r.b()?; + } + } + Ok(()) +} + /// OLE2FRAME (§20.4.74): an embedded or linked object. Its type, its space and its data, with /// (from AutoCAD 2000) whether it keeps its proportions. The drawing keeps it as the groups a /// DXF file has: the frame's corners come from the data's wrapper, and the data is the DXF diff --git a/crates/io/src/dwg/mod.rs b/crates/io/src/dwg/mod.rs index f0b81e63..c948727b 100644 --- a/crates/io/src/dwg/mod.rs +++ b/crates/io/src/dwg/mod.rs @@ -11,6 +11,7 @@ mod blocks; mod carry; +mod data_store; mod dynblock; mod entities; mod header; @@ -175,6 +176,18 @@ pub fn read(bytes: &[u8]) -> Result<(Drawing, Unread)> { &mut d, &mut unread, ); + // The ACIS geometry of solids, regions and bodies, from AutoCAD 2013 on in a section of its own. + if let Some(section) = file.section("AcDb:AcDsPrototype_1b") { + match draftcraft_dwg::datastore::read(section) { + Ok(store) => { + let groups = data_store::groups(&store); + if !groups.is_empty() { + std::sync::Arc::make_mut(&mut d.foreign).data_store = groups; + } + } + Err(_) => unread.count("data store"), + } + } // A block reference's clip, from the kept filter objects, as the DXF reader takes it. crate::dxf_clip::read(&mut d); for o in &objects { diff --git a/crates/io/src/dwg/write/common.rs b/crates/io/src/dwg/write/common.rs index 5f77c9f4..76445c10 100644 --- a/crates/io/src/dwg/write/common.rs +++ b/crates/io/src/dwg/write/common.rs @@ -171,6 +171,7 @@ pub(super) fn entity_start<'r>(cx: &Cx<'_>, r: &'r Rec<'_>) -> EntityStart<'r> { invisible: g.i(60) & 1 != 0, lineweight: lineweight(g.i_or(370, -1)), links: cx.links.get(&r.handle).copied(), + data_store: false, } } diff --git a/crates/io/src/dwg/write/mod.rs b/crates/io/src/dwg/write/mod.rs index 98d0071e..b672add2 100644 --- a/crates/io/src/dwg/write/mod.rs +++ b/crates/io/src/dwg/write/mod.rs @@ -505,7 +505,19 @@ pub fn write(tags: &[Tag], ver: V, info: &FileInfo<'_>) -> Result<(Vec, Unwr let encoded = encode_pruned(doc, ver, counted, &mut again); let doc = &encoded.cx.doc; let cx = &encoded.cx; - let mut objects: Vec<(u64, Vec)> = encoded.objects.into_iter().map(|o| (o.handle, o.bytes)).collect(); + // From 2013 the modeler entities written keep their description in the data store section. + let solids: Vec<(u64, &[u8])> = if ver >= V::R2013 { + encoded + .objects + .iter() + .filter(|o| matches!(o.kind.as_str(), "3DSOLID" | "REGION" | "BODY")) + .filter_map(|o| Some((o.handle, doc.data_store.get(&o.handle)?.as_slice()))) + .collect() + } else { + Vec::new() + }; + let data_store = (!solids.is_empty()).then(|| draftcraft_dwg::datastore::write(&draftcraft_dwg::datastore::solids(&solids))); + let mut objects: Vec<(u64, Vec)> = encoded.objects.iter().map(|o| (o.handle, o.bytes.clone())).collect(); // Two objects under one handle: a file AutoCAD would open with one of them lost. It happens // only when the drawing has used up its handles (the records then repeat the last one). let mut seen = std::collections::HashSet::with_capacity(objects.len()); @@ -560,6 +572,7 @@ pub fn write(tags: &[Tag], ver: V, info: &FileInfo<'_>) -> Result<(Vec, Unwr app_name: info.app_name, app_version: info.app_version, fonts: &fonts, + data_store: data_store.as_deref(), }; let bytes = compose::compose(&parts).map_err(|e| IoError::Format(format!("DWG: {e}")))?; Ok((bytes, encoded.unwritten)) diff --git a/crates/io/src/dwg/write/solid.rs b/crates/io/src/dwg/write/solid.rs index 891bec76..916e7e0c 100644 --- a/crates/io/src/dwg/write/solid.rs +++ b/crates/io/src/dwg/write/solid.rs @@ -4,7 +4,8 @@ //! in its groups 1 and 3, scrambled the same way in both formats (`super::super::entities` //! reads it back as stored); or, from AutoCAD 2004, as the binary form (format 2) a data store //! record holds. A wireframe block follows, empty: AutoCAD draws the shape from the description. -//! From AutoCAD 2013 the description lives in the file's data store section, not here. +//! From AutoCAD 2013 the description lives in the file's data store section (written by +//! `draftcraft_dwg::datastore`), and the entity holds the wireframe block and its GUID (group 2). use draftcraft_dwg::DwgVersion as V; use draftcraft_dwg::compose::{ObjectWriter, Ref}; @@ -25,8 +26,9 @@ pub(super) fn modeler(cx: &Cx<'_>, r: &Rec<'_>, code: u16) -> Option= V::R2013 { - // The data store section is not written yet: the shape would be lost. - return None; + // The description goes in the data store: without a record there, the shape would be + // lost (SAT text has no place in these files). + return sab.map(|_| modern(cx, r, code, &g)); } let mut w = begin(cx, code, r); match (&sat, sab) { @@ -71,6 +73,61 @@ pub(super) fn modeler(cx: &Cx<'_>, r: &Rec<'_>, code: u16) -> Option, r: &Rec<'_>, code: u16, g: &Groups<'_>) -> ObjectWriter { + // The entity tells AutoCAD its description is in the data store. + let mut w = cx.writer(code, r); + let mut start = super::common::entity_start(cx, r); + start.data_store = true; + w.entity(&start); + // The description is elsewhere; a wireframe block follows. + w.b(true); + w.b(true); + w.bd3([0.0; 3]); + w.bl(4); + w.b(true); + // No wires, no silhouettes. + w.bl(0); + w.bl(0); + w.b(true); + w.bl(0); + w.b(g.0.iter().find(|t| t.code == 290).is_none_or(|_| g.i(290) != 0)); + let (a, b, c, d) = guid(g.s(2)); + w.bl(a); + w.bs(b); + w.bs(c); + for x in d { + w.rc(x); + } + w.bl(0); + if r.kind == "3DSOLID" { + w.reference(Ref::SoftPointer, cx.known(r.sub("AcDb3dSolid").h(350))); + } + w +} + +/// A GUID as `{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}` in its four stored parts; zero when the +/// text is not one. +pub(crate) fn guid(text: &str) -> (u32, u16, u16, [u8; 8]) { + let hex: String = text.chars().filter(char::is_ascii_hexdigit).collect(); + let part = |from: usize, len: usize| hex.get(from..from + len).and_then(|h| u64::from_str_radix(h, 16).ok()); + if hex.len() != 32 { + return (0, 0, 0, [0; 8]); + } + let mut tail = [0u8; 8]; + for (i, t) in tail.iter_mut().enumerate() { + *t = part(16 + 2 * i, 2).and_then(|v| u8::try_from(v).ok()).unwrap_or(0); + } + ( + part(0, 8).and_then(|v| u32::try_from(v).ok()).unwrap_or(0), + part(8, 4).and_then(|v| u16::try_from(v).ok()).unwrap_or(0), + part(12, 4).and_then(|v| u16::try_from(v).ok()).unwrap_or(0), + tail, + ) +} + /// The SAT text of the modeler groups (format 1): each group 1 a line, continued by groups 3, /// with DXF's caret escape undone, each line ended by CR LF as AutoCAD stores it, and without /// the end-of-data line DWG's sized blocks have no use for. `None` when the groups hold none. diff --git a/crates/io/src/dwg/write/tests.rs b/crates/io/src/dwg/write/tests.rs index 0e84df15..efa71295 100644 --- a/crates/io/src/dwg/write/tests.rs +++ b/crates/io/src/dwg/write/tests.rs @@ -4,6 +4,7 @@ use super::*; use draftcraft_dwg::file::DwgFile; +/// A file of the mi201 corpus, or any file by its absolute path. fn mi201(name: &str) -> Vec { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/mi201").join(name); std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) @@ -131,7 +132,21 @@ fn hex_of(b: &[u8]) -> String { fn probe() { let only = std::env::var("DWG_PROBE").unwrap_or_default(); let only_ver = std::env::var("DWG_PROBE_VER").unwrap_or_default(); - for (dxf, dwg, ver) in PAIRS { + // `DWG_PROBE_PAIR=/abs/file.dxf:/abs/file.dwg:r2018` compares another pair AutoCAD saved. + let pair = std::env::var("DWG_PROBE_PAIR").unwrap_or_default(); + let mut pairs: Vec<(&str, &str, V)> = PAIRS.to_vec(); + if let [dxf, dwg, ver] = pair.split(':').collect::>()[..] { + let ver = match ver { + "r2013" => V::R2013, + "r2010" => V::R2010, + "r2007" => V::R2007, + "r2004" => V::R2004, + "r2000" => V::R2000, + _ => V::R2018, + }; + pairs = vec![(dxf, dwg, ver)]; + } + for (dxf, dwg, ver) in pairs { if !only_ver.is_empty() && !dwg.contains(&only_ver) { continue; } diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index 14c697ca..4d29204b 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -89,7 +89,6 @@ fn dxf_keeps_the_data_store_and_drops_records_of_deleted_entities() { } #[test] -#[ignore = "DraftCraft's DWG writer doesn't write the data store section (AcDsPrototype_1b) yet: it waits for an AutoCAD file to check it against (docs/dwg-writer-handoff.md)"] fn dwg_keeps_the_solids_geometry() { let d = draftcraft_io::read_dxf(dxf().as_bytes()).unwrap(); let dwg = draftcraft_io::write(&d, "x.dwg").unwrap(); @@ -103,6 +102,27 @@ fn dwg_keeps_the_solids_geometry() { assert_eq!(again.foreign.data_store_entities().len(), 2); } +/// In DWG 2013 and 2018 a solid tells AutoCAD its description is in the data store: the "has +/// data store data" bit of its common entity data. Without it AutoCAD opens the file with every +/// solid's body missing (AUDIT: "ASM body missing"), though the section holds them. +#[test] +fn dwg_solids_point_at_their_data_store_records() { + let d = draftcraft_io::read_dxf(dxf().as_bytes()).unwrap(); + for v in [draftcraft_io::Version::R2013, draftcraft_io::Version::R2018] { + let dwg = draftcraft_io::write_with(&d, "x.dwg", &draftcraft_io::SaveOptions { version: Some(v), binary: false }).unwrap(); + let file = draftcraft_dwg::file::DwgFile::open(&dwg).unwrap(); + assert!(file.section("AcDb:AcDsPrototype_1b").is_some(), "{v:?} has the section"); + let mut marked: Vec<(String, u64)> = Vec::new(); + for o in file.objects() { + let r = file.read_object(&o).unwrap(); + if r.has_data_store_record() { + marked.push((o.type_name.clone(), o.handle)); + } + } + assert_eq!(marked, vec![("3DSOLID".to_string(), 0x2A), ("3DSOLID".to_string(), 0x2B)], "{v:?}"); + } +} + /// A solid with SAT-text ACIS data (an R2000-style file) can't be written to a DXF of 2013 or /// later, whose files keep that data in the data store: it is left out there and counted, while /// 2010 and earlier keep it, and solids with a data store record are kept everywhere (#2334). @@ -222,3 +242,28 @@ fn a_dwg_keeps_a_sat_text_region_only_before_2013() { assert!(holds_sat(draftcraft_io::Version::R2010), "2010 keeps the SAT text"); assert!(!holds_sat(draftcraft_io::Version::R2018), "2018 comes back without it"); } + +/// A drawing with solids written as DWG 2013 and 2018, to open in AutoCAD: `DWG_DS_IN` names the +/// drawing (DXF or DWG), `DWG_DS_OUT` the folder. It also checks that the files read back with +/// the same geometry, and that a DWG read keeps what the DXF of the same drawing keeps. +#[test] +#[ignore] +fn write_solids_for_autocad() { + let (Ok(input), Ok(out)) = (std::env::var("DWG_DS_IN"), std::env::var("DWG_DS_OUT")) else { return }; + let d = draftcraft_io::read(&std::fs::read(&input).unwrap(), &input).unwrap(); + let mut want = asm_data(&String::from_utf8(draftcraft_io::write(&d, "x.dxf").unwrap()).unwrap()); + want.sort(); + let sizes: Vec<(String, usize)> = want.iter().map(|(h, x)| (h.clone(), x.len() / 2)).collect(); + println!("{input}: records {sizes:?}"); + for (v, name) in [(draftcraft_io::Version::R2013, "2013"), (draftcraft_io::Version::R2018, "2018")] { + let dwg = draftcraft_io::write_with(&d, "x.dwg", &draftcraft_io::SaveOptions { version: Some(v), binary: false }).unwrap(); + let path = std::path::Path::new(&out).join(format!("solids-dc-{name}.dwg")); + std::fs::write(&path, &dwg).unwrap(); + let mut got = asm_data(&crate::dwg_as_dxf(&dwg)); + got.sort(); + let sizes = |v: &[(String, String)]| v.iter().map(|(h, x)| (h.clone(), x.len() / 2)).collect::>(); + assert_eq!(sizes(&got), sizes(&want), "{name}"); + assert!(got == want, "{name}: the same handles and sizes, different bytes"); + println!("{}: {} bytes", path.display(), dwg.len()); + } +} diff --git a/docs/dwg-handoff.md b/docs/dwg-handoff.md index 4b497ea4..80ad752a 100644 --- a/docs/dwg-handoff.md +++ b/docs/dwg-handoff.md @@ -72,14 +72,11 @@ open the file again. ## What fails today -Four tests of `cargo test -p draftcraft-io --test it`; everything else in the workspace passes. - -| Test | Needs | -|---|---| -| `acis_data_store::dwg_keeps_the_solids_geometry` | The data store section of 2013-and-later files (`AcDb:AcDsPrototype_1b`, DXF's ACDSDATA), where solids keep their geometry | -| `acis_data_store::sat_text_solids_stay_in_dwg_2018_and_xref_contents_are_not_counted` | 3DSOLID, REGION and BODY as 2013-and-later files store them (in AutoCAD's 2018 region the DXF's identifier, group 2, is the 16 bytes at bit 157 of its data; what is before it is not worked out) | -| `dynblock_read::a_saved_drawing_keeps_the_dynamic_block_as_read` | The dynamic-block objects: ACAD_EVALUATION_GRAPH and the BLOCK…PARAMETER, …ACTION and …GRIP types, as their DXF groups | -| `dynblock_read::a_scale_action_survives_a_dwg_save` | Same | +Nothing in `cargo test -p draftcraft-io --test it` (the three macOS-only failures of AGENTS.md +aside). The four tests this list used to name pass: the data store section of 2013-and-later +files (`AcDb:AcDsPrototype_1b`, DXF's ACDSDATA) is read and written by +`crates/dwg/src/datastore.rs` (`acis_data_store::dwg_keeps_the_solids_geometry`), 3DSOLID, +REGION and BODY are read as those files store them, and the dynamic-block objects are kept. ## What a file can still lose on opening @@ -88,8 +85,11 @@ and the note says saving over the file would lose it. **Geometry that is not drawn** -- 3DSOLID, REGION and BODY whose description is binary (AutoCAD 2004 and later files) or in the - data store (2013 and later). Text ones (AutoCAD 2000 files, DraftCraft's own) are kept. +- 3DSOLID, REGION and BODY whose description is binary (AutoCAD 2004 to 2010 files). Text ones + (AutoCAD 2000 files, DraftCraft's own) and those in the data store (2013 and later) are kept. +- The history objects of 3D solids (ACSH_HISTORY_CLASS, ACSH_BOX_CLASS and the other ACSH_ + types, ACDBASSOCPERSSUBENTMANAGER, ACDBPERSSUBENTMANAGER): the solids themselves are kept, and + AutoCAD opens them without their history. - MESH (subdivision meshes) and SHAPE (a shape from an SHX file: its name needs the file). **Behaviour that is not kept** @@ -129,8 +129,7 @@ order, an OLE object's wrapper. A drawing from AutoCAD with each would settle it ## What is left, in order -1. The four failing tests: the data store, then the dynamic-block objects (step 12c). -2. The other types in the read note (step 12c). +1. The other types in the read note (step 12c). 3. ~~DraftCraft's own DWG writer and the other save versions (15–17); acadrust removed (18).~~ Done: see [`dwg-writer-handoff.md`](dwg-writer-handoff.md). diff --git a/docs/dwg-writer-handoff.md b/docs/dwg-writer-handoff.md index 6906cac5..38983f05 100644 --- a/docs/dwg-writer-handoff.md +++ b/docs/dwg-writer-handoff.md @@ -44,7 +44,8 @@ holds what the DXF of the same drawing holds, and what a command adds to one is | `crates/io/src/dwg/write/annotation.rs` | MTEXT, DIMENSION, SPLINE, HATCH, LEADER, TOLERANCE, VIEWPORT, MLINE, IMAGE, WIPEOUT | | `crates/io/src/dwg/write/objects.rs` | DICTIONARY, ACDBDICTIONARYWDFLT, XRECORD, ACDBPLACEHOLDER, DICTIONARYVAR, SCALE, GROUP, LAYOUT, MLINESTYLE, WIPEOUTVARIABLES, TABLESTYLE, MLEADERSTYLE, MATERIAL, VISUALSTYLE, CELLSTYLEMAP, section and detail view styles, DIMASSOC, IMAGEDEF, IMAGEDEF_REACTOR, RASTERVARIABLES, SPATIAL_FILTER, PDFDEFINITION, in every version | | `crates/io/src/dwg/write/header.rs` | header variables from their DXF form to DWG's | -| `crates/io/src/dwg/write/mleader.rs`, `table.rs`, `solid.rs`, `dynblock.rs` | multileaders, tables, ACIS solids up to 2010, dynamic block objects | +| `crates/io/src/dwg/write/mleader.rs`, `table.rs`, `solid.rs`, `dynblock.rs` | multileaders, tables, ACIS solids (from 2013 with their description in the data store), dynamic block objects | +| `crates/dwg/src/datastore.rs`, `crates/io/src/dwg/data_store.rs` | the data store section of 2013 and later (`AcDb:AcDsPrototype_1b`), where solids, regions and bodies keep their modeler description: read to records and written as AutoCAD lays out a new one; the records as the DXF's ACDSDATA groups | | `crates/io/src/dwg/write/variables.rs` | AutoCAD's variable dictionary, added when the drawing has none | | `crates/io/src/dwg/write/preview.rs` | the picture file browsers and the open dialog show | @@ -97,7 +98,15 @@ set; an AutoCAD 2018 MTEXT ends with a null reference. length and jogged radius dimensions, which AutoCAD lists as its own types), hatches 2007 and 2018 (patterns, gradients, solid fill with a hole), mlines 2013, regions 2007, viewports 2007 and 2018 (the layout viewports show the model). AutoCAD's own save of our mi201 2018 file - reads in DraftCraft the same as ours. The image files were not checked. + reads in DraftCraft the same as ours. The image files were not checked. Solids and regions + in 2013 and 2018 (four bodies, one of 2.9 MB in blob pages, with and without history) open + with every body drawn and AUDIT 0. What that needed, found this way: an entity whose + description is in the data store has the "data store" bit of its common entity data set + (`EntityStart::data_store`); without it AutoCAD reports "ASM body missing" for every solid, + though the section holds them. AutoCAD's own 2018 files store the description as + `ASM BinaryFile4` (version 22300) where its DXF and 2013 files have `ACIS BinaryFile` (21800); + AutoCAD reads the DXF form in a 2018 file, so the writer keeps it as the drawing has it. The + solids' history objects (ACSH_ types) are not written: AutoCAD opens the solids without it. 2. Dynamic-block parameters and actions made in the Block Editor are written to DWG: the Block Editor keeps the evaluation graph's node list (`rebuild_graph` in `crates/doc/src/dynblock/author.rs`), and `crates/engine/tests/dynblock_authoring.rs` saves diff --git a/docs/dwg.md b/docs/dwg.md index 883d0683..7f88b64e 100644 --- a/docs/dwg.md +++ b/docs/dwg.md @@ -98,7 +98,7 @@ DraftCraft writes every version itself, and acadrust is gone. What remains: | Step | What | Shows today as | |---|---|---| -| 12c | What a real file still leaves in the read note: the solid modeler's binary description (2004 and later) and the 2013-and-later data store (ACDSDATA) of 3DSOLID, REGION and BODY; dynamic-block objects (the evaluation graph, parameters, actions and grips); MESH and SHAPE; draw order (SORTENTSTABLE); MATERIAL, VISUALSTYLE and the section and detail view styles before 2013; CELLSTYLEMAP, TABLECONTENT and TABLEGEOMETRY; an entity's plot style | Named in the read note of the file, by type; four io tests fail on them (`acis_data_store` × 2, `dynblock_read` × 2) | +| 12c | What a real file still leaves in the read note: the solid modeler's binary description (2004 to 2010) of 3DSOLID, REGION and BODY, and the solids' history objects (ACSH_ types; the 2013-and-later data store, ACDSDATA, is read and written: `crates/dwg/src/datastore.rs`); dynamic-block objects (the evaluation graph, parameters, actions and grips); MESH and SHAPE; draw order (SORTENTSTABLE); MATERIAL, VISUALSTYLE and the section and detail view styles before 2013; CELLSTYLEMAP, TABLECONTENT and TABLEGEOMETRY; an entity's plot style | Named in the read note of the file, by type; four io tests fail on them (`acis_data_store` × 2, `dynblock_read` × 2) | | 14 | The switch-over: the direct reader as the default, the old paths removed | done | | 15–16 | DraftCraft's own DWG writer (objects, sections and container, a read-back check on every save) | done | | 17 | The other save versions: 2000, 2004, 2007, 2010, 2013 | done |