Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions crates/doc/src/dynblock/author.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,36 @@ fn add_member(d: &mut Drawing, g: Handle, kind: &str, mut tags: Vec<RawTag>) ->
if let Some(o) = find_mut(d, g) {
o.tags.push(tag(360, h.hex()));
}
rebuild_graph(d, g);
h
}

/// Write graph `g`'s node list as AutoCAD's files hold it, from the members it lists: the next
/// free id twice (96, 97), then each member as a node, its id (91, its expression's 90), flags
/// 32 (93), the id after it (95), the member (360) and four unused links (92 -1). The DWG writer
/// encodes the nodes from these groups; a bare list of members would be written as an empty
/// graph, and the block would open as a plain block.
fn rebuild_graph(d: &mut Drawing, g: Handle) {
let Some(graph) = find(d, g) else { return };
let members: Vec<Handle> = graph.tags.iter().filter(|t| t.code == 360).filter_map(|t| Handle::parse_hex(&t.value)).collect();
let node_of = |h: Handle| -> Option<i64> {
let o = find(d, h)?;
let mut tags = o.tags.iter().skip_while(|t| !(t.code == 100 && t.value == "AcDbEvalExpr"));
tags.find(|t| t.code == 90).and_then(|t| t.value.trim().parse().ok())
};
let nodes: Vec<(i64, Handle)> = members.into_iter().filter_map(|h| Some((node_of(h)?, h))).collect();
let free = nodes.iter().map(|n| n.0).max().map_or(0, |n| n.saturating_add(1));
let Some(graph) = find_mut(d, g) else { return };
let head = graph.tags.iter().position(|t| t.code == 100 && t.value == "AcDbEvalGraph").map_or(graph.tags.len(), |i| i + 1);
graph.tags.truncate(head);
graph.tags.extend([tag(96, free.to_string()), tag(97, free.to_string())]);
for (i, (id, h)) in nodes.iter().enumerate() {
let after = nodes.get(i + 1).map_or(free, |n| n.0);
graph.tags.extend([tag(91, id.to_string()), tag(93, "32"), tag(95, after.to_string()), tag(360, h.hex())]);
graph.tags.extend(std::iter::repeat_with(|| tag(92, "-1")).take(4));
}
}

fn head(node: i32, element: &str) -> Vec<RawTag> {
vec![tag(100, "AcDbEvalExpr"), tag(90, node.to_string()), tag(100, "AcDbBlockElement"), tag(300, element)]
}
Expand Down Expand Up @@ -319,8 +346,16 @@ pub fn remove(d: &mut Drawing, name: &str, node: i32) -> Result<Vec<String>, Str
let hs: std::collections::HashSet<Handle> = gone.iter().map(|g| g.0).collect();
Arc::make_mut(&mut d.foreign).objects.retain(|o| !hs.contains(&o.handle));
let hexes: std::collections::HashSet<String> = hs.iter().map(|h| h.hex()).collect();
let mut graphs = Vec::new();
for o in Arc::make_mut(&mut d.foreign).objects.iter_mut().filter(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH")) {
let before = o.tags.len();
o.tags.retain(|t| !(t.code == 360 && Handle::parse_hex(&t.value).is_some_and(|h| hexes.contains(&h.hex()))));
if o.tags.len() != before {
graphs.push(o.handle);
}
}
for g in graphs {
rebuild_graph(d, g);
}
Ok(gone.into_iter().map(|g| g.1).filter(|n| !n.is_empty()).collect())
}
Expand Down Expand Up @@ -398,4 +433,40 @@ mod tests {
assert!(m.parameters.is_empty() && m.actions.is_empty() && m.grip_objects.is_empty());
assert!(add_parameter(&mut d, "NOPE", &NewParameter::Point { at: Vec2::ZERO, label: String::new(), description: String::new() }).is_err());
}

/// The graph lists its members as AutoCAD's files do, one node each (id, flags, the next id,
/// the member, four links), and keeps the list right when a member goes.
#[test]
fn the_graph_lists_each_member_as_a_node() {
let (mut d, hs, _) = drawing();
let p =
add_parameter(&mut d, "B", &NewParameter::Point { at: Vec2::new(5.0, 5.0), label: "Top".into(), description: String::new() }).unwrap();
let mv = add_action(&mut d, "B", &NewAction::Move { parameter: p.node, objects: vec![hs[2]] }).unwrap();
let graph = |d: &Drawing| d.foreign.objects.iter().find(|o| o.kind == "ACAD_EVALUATION_GRAPH").unwrap().tags.clone();
let nodes = |tags: &[RawTag]| -> Vec<(String, String, String)> {
let mut out = Vec::new();
for (i, t) in tags.iter().enumerate().filter(|(_, t)| t.code == 91) {
let at = |k: usize| tags.get(i + k).map(|t| (t.code, t.value.clone()));
assert_eq!(at(1), Some((93, "32".into())));
let Some((95, next)) = at(2) else { panic!("95 after 91") };
let Some((360, member)) = at(3) else { panic!("360 after 95") };
assert!((4..8).all(|k| at(k) == Some((92, "-1".into()))));
out.push((t.value.clone(), next, member));
}
out
};
let tags = graph(&d);
let listed = nodes(&tags);
// The point parameter, its grip and the move.
assert_eq!(listed.len(), 3, "{tags:?}");
assert_eq!(listed.last().map(|n| n.2.clone()), Some(mv.handle.hex()));
let free = tags.iter().find(|t| t.code == 96).map(|t| t.value.clone()).unwrap();
assert_eq!(listed.last().map(|n| n.1.clone()), Some(free.clone()), "the last node's next is the next free id");
assert_eq!(tags.iter().filter(|t| t.code == 360).count(), 3);
remove(&mut d, "B", mv.node).unwrap();
let tags = graph(&d);
assert_eq!(nodes(&tags).len(), 2, "{tags:?}");
assert_eq!(tags.iter().filter(|t| t.code == 360).count(), 2);
assert!(dynamic_block(&d, "B").is_some_and(|m| m.actions.is_empty() && m.parameters.len() == 1));
}
}
11 changes: 11 additions & 0 deletions crates/doc/src/entity/dim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,17 @@ pub struct DimMarks {
/// Inspection frame, label and rate (DIMINSPECT).
#[serde(skip_serializing_if = "Option::is_none")]
pub inspect: Option<Inspection>,
/// An arc-length dimension of part of its arc (DIMARC Partial): `p13` and `p14` are the
/// picked points rather than the arc's ends.
#[serde(skip_serializing_if = "is_false")]
pub arc_partial: bool,
/// An arc-length dimension with a leader from its text to the arc (DIMARC Leader).
#[serde(skip_serializing_if = "is_false")]
pub arc_leader: bool,
}

fn is_false(b: &bool) -> bool {
!*b
}

impl DimMarks {
Expand Down
File renamed without changes.
53 changes: 53 additions & 0 deletions crates/dwg/src/compose/fields.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//! The fields of one object as three bit streams (data, text, references), for the encoders that
//! write an object field by field from a layout ([`crate::read::styles`]); [`super::ObjectWriter`]
//! takes the streams over.

use crate::bits::BitWriter;
use crate::read::model::Handle;
use crate::read::version::DwgVersion;

/// The three streams an R2007+ object is written as.
pub(crate) struct ObjW {
pub ver: DwgVersion,
pub dat: BitWriter,
strs: BitWriter,
has_strings: bool,
pub hdl: BitWriter,
}

/// Which handle-reference codes a field takes (spec §2.13): soft
/// hard ownership 3, soft pointer 4, hard pointer 5.
#[derive(Clone, Copy)]
pub(crate) enum FieldRef {
HardOwner = 3,
SoftPtr = 4,
HardPtr = 5,
}

impl ObjW {
pub fn new(ver: DwgVersion) -> Self {
ObjW { ver, dat: BitWriter::new(), strs: BitWriter::new(), has_strings: false, hdl: BitWriter::new() }
}

/// The object's three streams as written so far: fields, text (and whether it has any),
/// references.
pub(crate) fn into_streams(self) -> (BitWriter, BitWriter, bool, BitWriter) {
(self.dat, self.strs, self.has_strings, self.hdl)
}

/// TV: from R2007 in the string stream, as UTF-16.
pub fn tv(&mut self, s: &str) {
if self.ver.has_string_stream() {
self.strs.text16(s);
self.has_strings = true;
} else {
let bytes: Vec<u8> = s.chars().map(|c| if (c as u32) < 0x100 { c as u8 } else { b'?' }).collect();
self.dat.text8(&bytes);
}
}

/// An absolute reference.
pub fn h(&mut self, kind: FieldRef, target: Handle) {
self.hdl.handle(kind as u8, target.0);
}
}
4 changes: 2 additions & 2 deletions crates/dwg/src/compose/file.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
//! The whole file from its parts, laid out as its version stores it.

use super::container::{self, FileInfo, MAX_PAGE, Section};
use super::small as shared;
use crate::bits::BitWriter;
use crate::crc::{crc16, file_header_crc_xor};
use crate::file::HeaderValue;
use crate::read::section::FILE_HEADER_END;
use crate::read::version::DwgVersion as V;
use crate::records::{Error, Result};
use crate::write::container::{self, FileInfo, MAX_PAGE, Section};
use crate::write::sections as shared;

use super::object::TextEncoding;
use super::sections::{Class, classes_section, header_section, object_map};
Expand Down
4 changes: 4 additions & 0 deletions crates/dwg/src/compose/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
//! the objects, the header variables and the classes over; this module lays the file out as the
//! version asked for stores it.

mod container;
mod fields;
mod file;
mod object;
mod r2007;
mod sections;
mod small;

pub(crate) use fields::{FieldRef, ObjW};
pub use file::{Parts, Properties, compose};
pub use object::{EntityStart, ObjectWriter, Ref, TextEncoding, color_of_word, frame, method_word};
pub use sections::{Class, HeaderKind, class_versions, classes_section, header_section, header_variables, object_map};
Expand Down
2 changes: 1 addition & 1 deletion crates/dwg/src/compose/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ impl ObjectWriter {
pub fn grouped(&mut self, kind: &str, items: Vec<(u16, crate::file::XrValue)>, text_styles: &[(String, u64)]) -> crate::records::Result<()> {
use crate::read::model::{Groups, Handle};
let lookup = crate::read::styles::Lookup::from_text_styles(text_styles.iter().map(|(n, h)| (n.clone(), Handle(*h))).collect());
let mut w = crate::write::objects::ObjW::new(self.ver, Handle(self.handle));
let mut w = super::ObjW::new(self.ver);
crate::read::styles::encode_with(&mut w, &Groups { kind: kind.to_string(), items }, &lookup)?;
let (dat, strs, has_strings, hdl) = w.into_streams();
self.dat.append(&dat);
Expand Down
3 changes: 2 additions & 1 deletion crates/dwg/src/compose/sections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ fn parse_floats(t: &str) -> Vec<f64> {

/// A variable's value when the drawing has none: AutoCAD's own default.
fn default_value(name: &str, kind: VarKind) -> HeaderValue {
let dt = crate::write::sections::default_text(name);
let dt = super::small::default_text(name);
match kind {
VarKind::B => HeaderValue::Bool(match dt {
"" => matches!(
Expand Down Expand Up @@ -289,6 +289,7 @@ pub fn class_versions(dxf_name: &str) -> (u32, u32) {
"ACDBDETAILVIEWSTYLE" => (33, 427),
"DIMASSOC" => (23, 12),
"DICTIONARYVAR" => (20, 0),
"ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" => (25, 20),
_ => (0, 0),
}
}
Expand Down
152 changes: 152 additions & 0 deletions crates/dwg/src/compose/small.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//! The small sections every DWG file carries whatever the drawing: the application information
//! (AcDb:AppInfo and AcDb:AppInfoHistory), the revision history, and the header variables' default
//! values, in the forms AutoCAD 2027 writes them.

/// Default values of the header variables for a drawing that has none
/// (AutoCAD's own defaults, as an imperial drawing carries them).
pub(crate) fn default_text(name: &str) -> &'static str {
match name {
"UNKNOWN_BD_412148564080" => "412148564080",
"UNKNOWN_BD_1A" | "UNKNOWN_BD_1B" | "UNKNOWN_BD_1C" => "1",
"UNKNOWN_TV_1" => "\"m\"",
// The spec gives 24; AutoCAD writes 0 in every file of the corpus.
"UNKNOWN_BL_24" => "0",
// Undocumented longs AutoCAD writes with the same values in every
// file of the corpus, 2004 to 2018, whatever the drawing.
"UNKNOWN_BL_R2004_1" | "UNKNOWN_BL_R2004_6" => "808464432",
"UNKNOWN_BL_R2004_2" | "UNKNOWN_BL_R2004_5" => "486539264",
"UNKNOWN_BL_R2004_3" | "UNKNOWN_BL_R2004_4" => "1295003696",
"MENUNAME" => "\".\"",
"DIMASO" | "DIMSHO" | "REGENMODE" | "FILLMODE" | "PSLTSCALE" | "USRTIMER" | "WORLDVIEW" | "TILEMODE" | "VISRETAIN" | "DIMTIH" | "DIMTOH"
| "CAMERADISPLAY" => "",
"PROXYGRAPHICS" | "ATTMODE" | "SHOWHIST" | "LOFTNORMALS" | "LIGHTGLYPHDISPLAY" | "TILEMODELIGHTSYNCH" | "HIDETEXT" | "DIMTOLJ" => "1",
"TREEDEPTH" => "3020",
"LUNITS" | "DIMALTD" | "DIMALTU" | "DIMALTTD" | "DIMLUNIT" | "XCLIPFRAME" | "DIMASSOC" | "DWFFRAME" => "2",
"LUPREC" | "DIMDEC" | "DIMTDEC" => "4",
"SPLINESEGS" | "ISOLINES" => "8",
"SURFU" | "SURFV" | "SURFTYPE" | "SURFTAB1" | "SURFTAB2" | "SPLINETYPE" => "6",
"SHADEDGE" | "DIMATFIT" => "3",
"SHADEDIF" | "TSTACKSIZE" => "70",
"MAXACTVP" => "64",
"TEXTQLTY" => "50",
"LTSCALE" | "CMLSCALE" | "CELTSCALE" | "DIMSCALE" | "DIMLFAC" | "DIMTFAC" | "DIMFXL" | "UNKNOWN_BD_R2007_1" => "1",
"TEXTSIZE" => "0.2",
"TRACEWID" => "0.05",
"SKETCHINC" => "0.1",
"FACETRES" => "0.5",
"PEXTMIN" | "EXTMIN" => "(100000000000000000000, 100000000000000000000, 100000000000000000000)",
"PEXTMAX" | "EXTMAX" => "(-100000000000000000000, -100000000000000000000, -100000000000000000000)",
"PLIMMAX" | "LIMMAX" => "(12, 9)",
"PUCSXDIR" | "UCSXDIR" => "(1, 0, 0)",
"PUCSYDIR" | "UCSYDIR" => "(0, 1, 0)",
"DIMASZ" | "DIMEXE" | "DIMTXT" => "0.18",
"DIMEXO" => "0.0625",
"DIMDLI" => "0.38",
"DIMCEN" | "DIMGAP" => "0.09",
"DIMALTF" => "25.4",
"DIMJOGANG" => "0.7853981633974483",
"DIMDSEP" => "46",
"DIMLWD" | "DIMLWE" => "-2",
"DIMALTMZF" | "DIMMZF" => "100",
"FLAGS" => "10781",
"SORTENTS" => "127",
"OBSCUREDCOLOR" | "INTERSECTIONCOLOR" => "257",
"TSTACKALIGN" => "1",
"UNKNOWN_BL_R2007_2" => "10",
"STEPSPERSEC" | "3DDWFPREC" => "2",
"STEPSIZE" => "6",
"LENSLENGTH" => "50",
"PSOLWIDTH" => "0.25",
"PSOLHEIGHT" => "4",
"LOFTANG1" | "LOFTANG2" => "1.5707963267948966",
"LOFTPARAM" => "7",
"LATITUDE" => "37.795",
"LONGITUDE" => "-122.394",
"TIMEZONE" => "-8000",
"UNKNOWN_B_R2007" => "true",
_ => "",
}
}

/// The maintenance release AutoCAD 2027 writes for AC1032 (file header,
/// auxiliary header, class records), whose object layout the writer
/// follows bit for bit.
pub(crate) const ACAD_MAINTENANCE: u32 = 427;

/// AcDb:RevHistory (chapter 18), as AutoCAD 2027 writes it for a drawing
/// with no revision records.
pub(crate) fn rev_history() -> Vec<u8> {
[0u32, 0, 1, 0].iter().flat_map(|v| v.to_le_bytes()).collect()
}

/// The kinds of entry in an application information list, each written
/// before its text. The spec calls these 16 bytes a checksum that may be
/// zero; in AutoCAD's files they are fixed identifiers, the same in every
/// file of the corpus whatever the text (the property set's is the format
/// id its XML names).
const APPINFO_COMMENT: [u8; 16] = [0xB8, 0xD0, 0xF0, 0x25, 0xA1, 0xD7, 0x93, 0x49, 0xB2, 0xFA, 0x9B, 0xF9, 0x28, 0x6F, 0xA1, 0xFD];

const APPINFO_PROPERTIES: [u8; 16] = [0xE0, 0x85, 0x9F, 0xF2, 0xF9, 0x4F, 0x68, 0x10, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9];

const APPINFO_PRODUCT: [u8; 16] = [0xE8, 0xE0, 0x96, 0x51, 0xC5, 0xCE, 0xB2, 0x44, 0xA8, 0xBF, 0xF6, 0xE8, 0x3B, 0x85, 0x9D, 0x44];

/// The 32 bytes AcDb:AppInfoHistory starts with, the same in every file of
/// the corpus (2004 to 2018, every save).
const APPINFO_HISTORY_START: [u8; 32] = [
0x53, 0xDE, 0x38, 0x1D, 0xEC, 0x43, 0x21, 0xCA, 0x96, 0x19, 0xE1, 0xE2, 0x17, 0x1A, 0x2A, 0x67, 0x3B, 0xD9, 0x7F, 0xF7, 0x3C, 0xBB, 0xCE, 0x08,
0xA0, 0x53, 0xD8, 0xED, 0xD2, 0x8D, 0xC5, 0xC7,
];

/// TU as the R2007+ small sections store it: RS length counting the
/// terminating 0, then UTF-16 units with that 0.
fn tu(out: &mut Vec<u8>, s: &str) {
let units: Vec<u16> = s.encode_utf16().filter(|&u| u != 0).chain([0]).collect();
out.extend_from_slice(&(units.len() as u16).to_le_bytes());
for u in units {
out.extend_from_slice(&u.to_le_bytes());
}
}

fn appinfo_comment(name: &str, version: &str) -> String {
format!("Saved by {name} {version}.")
}

fn appinfo_product(name: &str, version: &str) -> String {
let registry: String = version.split('.').take(2).collect::<Vec<_>>().join(".");
format!(
"<ProductInformation name =\"{name}\" build_version=\"{version}\" registry_version=\"{registry}\" install_id_string=\"{name}\" registry_localeID=\"1033\"/>"
)
}

/// AcDb:AppInfo (chapter 16) in the layout AutoCAD 2027 writes: format 3,
/// "AppInfoDataList", two entries (a comment and the product
/// information), each after the identifier of its kind. It names the
/// program writing the file, never claims to be an Autodesk application.
pub(crate) fn app_info(name: &str, version: &str) -> Vec<u8> {
let mut o = Vec::new();
o.extend_from_slice(&3u32.to_le_bytes());
tu(&mut o, "AppInfoDataList");
o.extend_from_slice(&2u32.to_le_bytes());
o.extend_from_slice(&APPINFO_COMMENT);
tu(&mut o, &appinfo_comment(name, version));
o.extend_from_slice(&APPINFO_PRODUCT);
tu(&mut o, &appinfo_product(name, version));
o
}

/// AcDb:AppInfoHistory (not in the spec) from a ready property set: the fixed 32 bytes, a
/// zero long, then an application information list of three entries (the comment, the property
/// set and the product information).
pub(crate) fn app_info_history_with(props: &str, name: &str, version: &str) -> Vec<u8> {
let mut o = APPINFO_HISTORY_START.to_vec();
o.extend_from_slice(&0u32.to_le_bytes());
tu(&mut o, "AppInfoDataList");
o.extend_from_slice(&3u32.to_le_bytes());
o.extend_from_slice(&APPINFO_COMMENT);
tu(&mut o, &appinfo_comment(name, version));
o.extend_from_slice(&APPINFO_PROPERTIES);
tu(&mut o, props);
o.extend_from_slice(&APPINFO_PRODUCT);
tu(&mut o, &appinfo_product(name, version));
o
}
3 changes: 1 addition & 2 deletions crates/dwg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//!
//! - [`read`]: DWG files from R13 to AutoCAD 2018 and later into the [`records`] of
//! their objects, which `draftcraft-io` maps straight into the drawing.
//! - [`write`] and [`compose`]: DWG files of every version AutoCAD saves (2000 to 2018) from the
//! - [`compose`]: DWG files of every version AutoCAD saves (2000 to 2018) from the
//! drawing's objects.
//! - [`file`]: a DWG file opened to its parts (version, sections, the object list), for a reader
//! that builds the drawing itself.
Expand All @@ -22,7 +22,6 @@ pub mod file;
pub mod lz77;
pub mod read;
pub mod records;
pub mod write;

pub use read::{DwgVersion, read_bytes};

Expand Down
Loading
Loading