dxf#
DXF import (ASCII): tables, blocks and entities of model space, without a GPU -- crate root lib/dxf/src/lib.rs
dxf -- DXF import (G6e2; docs/RENDER2D.md "DXF"): the ASCII format of AutoCAD R12 to 2018 read into a data model
that needs no GPU: the header's variables, the tables of layers, linetypes, text styles, block records and
dimension styles, blocks with their entities, and the entities of the drawing. lib/render2d puts it into a scene
(render2d::dxf); a converter or a test reads the same without a device.
dxf::load(bytes, &Limits) -> Result<Document> the whole file in memory, every entity kept
dxf::read(&mut source, &Limits, &mut sink) -> Result<Stats> streaming: the source hands out the file in pieces,
the sink gets the header, the tables, each block when it is complete and each entity of ENTITIES as it is
read (nothing of ENTITIES is kept: a file of a gigabyte loads in bounded memory)
mtext::parse(text, height) -> Mtext MTEXT's inline format codes as paragraphs of runs
specials(text) -> Vec<Special> TEXT's %% codes (degree, diameter, under- and overline)
aci_rgb(index), font_substitute(name) AutoCAD's colour index, which repository font stands in
Binary DXF is refused (Error::Binary). Files are untrusted input: every count, length and size is bounded
(Limits), a malformed value is skipped with a note, a group code that is no number ends the file with an error;
nothing nests deeper than POLYLINE / VERTEX and INSERT / ATTRIB, so there is no recursion. Strings before AutoCAD
2007 are in the header's code page ($DWGCODEPAGE, formats::encoding's character sets and multi-byte encodings), from
AC1021 on UTF-8; \U+XXXX and \M+NXXXX are decoded everywhere, %% codes and MTEXT's codes where the text is drawn
(specials, mtext).
dxf crate root#
enum Errorwhat went wrong; the text says whereBinary-- a binary DXF ("AutoCAD Binary DXF"): not read (decision 31: the ASCII format)Invalid(String)-- not a DXF: a group code that is no number, a pair cut off (the line in the text)Limit(String)-- a Limits value exceeded
type Result<T> = core::result::Result<T, Error>struct Limitsthe bounds a file must stay in (Limits::DEFAULT; raise them for large files you trust more)line_bytes: usize-- bytes of one line (a group code or a value)entity_pairs: usize-- group pairs of one entity (with its vertices and attributes) and the bytes of their valuesentity_bytes: usizeentity_points: usize-- points of one entity: vertices, control points, knots, a hatch's edges and its pattern's dasheskept_entities: u64-- entities kept: all of a Document's, or the blocks' while streamingkept_points: u64-- points kept (as entity_points, summed over what is kept)blocks: usize-- blocks, distinct names (layers, linetypes, styles, blocks), entries of all tablesnames: usizetable_entries: usize
impl Limits
const DEFAULT: Limits = Limits { line_bytes: 1 << 20, entity_pairs: 1 << 24, enti ...type P3 = [f64; 3]a point (x, y, z)struct Name(pub u32)a name of the file (a layer, linetype, text style, block, an entity's kind): an index into Names; names that differ only in the case of ASCII letters are one (AutoCAD's rule)struct Namesthe names of a file, in the order they were first seen (Name(0) is the layer "0")
impl Names
fn get(&self, n: Name) -> &strthe name's text as the file first spelled itfn find(&self, s: &str) -> Option<Name>a name that is already knownfn len(&self) -> usizefn is_empty(&self) -> boolenum Coloran entity's colour (62, 420): by layer, by block, an index of AutoCAD's palette (1 to 255; aci_rgb) or a true colour 0xRRGGBB (420 wins over 62)ByLayerByBlockAci(u8)Rgb(u32)
enum Linetypean entity's linetype (6): by layer (also when absent), by block, or a linetype of the table ("CONTINUOUS" is one)ByLayerByBlockNamed(Name)
enum Lineweighta lineweight (370): by layer, by block, the drawing's default ($LWDEFAULT), or hundredths of a millimetreByLayerByBlockDefaultMm100(u16)
enum Transparencya transparency (440): by layer, by block, or an alpha (255: opaque, 0: invisible)ByLayerByBlockAlpha(u8)
struct Commonwhat every entity haskind: Name-- the entity's kind as the file names it (LINE, LWPOLYLINE, ...)handle: u64-- 5 (0: none)layer: Name-- 8 (the layer "0" when absent)linetype: Linetypecolor: Colorlineweight: Lineweightltscale: f64-- 48 (1 when absent)transparency: Transparencyextrusion: P3-- 210 (0, 0, 1 when absent): the normal of the entity's object coordinate system (OCS)thickness: f64-- 39invisible: bool-- 60 = 1paper: bool-- 67 = 1: in paper space
struct Entityan entity: what all have, and its kind's geometrycommon: Commonkind: Kind
struct Vertexa vertex of a polyline: its point (OCS for 2D polylines, WCS for 3D), the bulge of the segment that starts here (the tangent of a quarter of its arc's angle, positive: counter-clockwise), the widths at its start and endat: P3bulge: f64start_width: f64end_width: f64
struct PolylineLWPOLYLINE, and POLYLINE with its VERTEXes (2D and 3D; meshes are Kind::Mesh)vertices: Vec<Vertex>closed: bool-- 70 bit 1plinegen: bool-- 70 bit 128: the linetype's pattern runs on across the vertices (else it starts anew at each)three_d: bool-- a 3D polyline (POLYLINE 70 bit 8): points in WCS, no bulges, no widthsconst_width: f64-- 43 (LWPOLYLINE) or 40 / 41 of POLYLINE: the width where a vertex has none of its ownelevation: f64-- 38 (LWPOLYLINE) or 30 of POLYLINE's point: the OCS z
struct MeshPOLYLINE as a polyface mesh (70 bit 64: faces of up to four vertices, an edge invisible where its index is negative) or a polygon mesh (70 bit 16: m by n vertices, closed in m or n)vertices: Vec<P3>faces: Vec<[i32; 4]>-- polyface: per face its vertex indices from 1 (negative: the edge from it is invisible; 0: none)m: u32-- polygon mesh: its size and whether it closesn: u32closed_m: boolclosed_n: bool
struct SplineSPLINE (and the spline of a HELIX): degree, knots, control points with weights, fit pointsdegree: u32flags: u32-- 70: 1 closed, 2 periodic, 4 rational, 8 planar, 16 linearknots: Vec<f64>control: Vec<P3>weights: Vec<f64>-- one per control point, or empty (all 1)fit: Vec<P3>start_tangent: Option<P3>end_tangent: Option<P3>
struct TextTEXT, ATTRIB and ATTDEFtext: String-- 1, decoded (\U+XXXX; the %% codes stay: specials())style: Option<Name>-- 7 (Standard when absent)at: P3-- 10, 11 (OCS)at2: Option<P3>height: f64-- 40rotation: f64-- 50 (degrees)width: Option<f64>-- 41, 51 (degrees): None when absent (the style's)oblique: Option<f64>generation: Option<u32>-- 71: 2 backward, 4 upside down (None: the style's)halign: u32-- 72 (0 left, 1 center, 2 right, 3 aligned, 4 middle, 5 fit), 73 (0 baseline, 1 bottom, 2 middle, 3 top)valign: u32tag: Option<String>-- ATTRIB and ATTDEF: the tag (2) and the flags (70: 1 invisible, 2 constant, 4 verify, 8 preset)attr_flags: u32mtext: Option<alloc::boxed::Box<MText>>-- ATTRIB / ATTDEF of several lines (R2018: an MTEXT inside them)
struct MTextMTEXTtext: String-- 3 ... and 1, joined, decoded (\U+XXXX); the format codes stay (mtext::parse)style: Option<Name>at: P3-- 10 (WCS)height: f64-- 40, 41 (the reference rectangle's width: 0, no wrapping), 46 (its height, for columns)width: f64rect_height: f64attach: u32-- 71 (1 top left to 9 bottom right), 72 (1 left to right, 3 top to bottom, 5 by style)direction: u32x_dir: Option<P3>-- 11 (WCS): the x axis' direction; else 50 (radians, in the OCS)rotation: f64spacing_style: u32-- 73 (1 at least, 2 exactly), 44 (the factor of the single spacing)spacing: f64bg_flags: u32-- 90 (1 a background fill, 2 in the background colour, 16 a text frame), 63 / 421 its colour, 45 how far beyond the text (a factor of the height)bg_color: Colorbg_scale: f64column_type: u32-- R2018's columns (75 type: 0 none, 1 static, 2 dynamic; 76 count; 48 width; 49 gutter; 50 heights)column_count: u32column_width: f64column_gutter: f64column_heights: Vec<f64>
struct InsertINSERT (also MINSERT's array) with its ATTRIBsblock: Name-- 2at: P3-- 10 (OCS), 41 42 43, 50 (degrees)scale: P3rotation: f64columns: u32-- 70, 71 (0 read as 1), 44, 45rows: u32spacing: [f64; 2]attribs: Vec<Entity>-- the ATTRIBs after it (each an Entity of Kind::Text)
enum Edgean edge of a hatch's boundary path (angles in degrees, as the file has them)Line { a: [f64; 2], b: [f64; 2] }Arc { center: [f64; 2], radius: f64, start: f64, end: f64, ccw: bool }Ellipse { center: [f64; 2], major: [f64; 2], ratio: f64, start: f64, end: f64, ccw: bool }-- major: the end of the major axis relative to the centre; ratio: minor over majorSpline { degree: u32, rational: bool, periodic: bool, knots: Vec<f64>, control: Vec<[f64; 2]>, weights: Vec<f64>, fit: Vec<[f64; 2]> }Poly { vertices: Vec<[f64; 3]>, closed: bool }-- a polyline path: its vertices (x, y, bulge), closed
struct Patha hatch's boundary path: its flags (92: 1 external, 2 polyline, 4 derived, 8 textbox, 16 outermost) and edgesflags: u32edges: Vec<Edge>
struct PatternLinea line family of a hatch pattern as the file stores it, already scaled and turned: angle (53, degrees), a base point (43, 44), the offset to the next line (45, 46) and dashes (49: positive on, negative off, 0 a dot)angle: f64base: [f64; 2]offset: [f64; 2]dashes: Vec<f64>
struct HatchHATCHpattern: String-- 2, 70 (solid fill), 75 (0 normal, 1 outer, 2 ignore islands), 52, 41, 77solid: boolstyle: u32angle: f64scale: f64double: boolelevation: f64-- 30: the OCS z of the boundarypaths: Vec<Path>lines: Vec<PatternLine>gradient: bool-- 450 = 1: a gradient (its two colours, 63/421 after 453)gradient_colors: Vec<Color>
struct QuadSOLID, TRACE (the outline 10, 11, 13, 12 in OCS) and 3DFACE (10, 11, 12, 13 in WCS; 70: invisible edges)points: [P3; 4]face: boolinvisible_edges: u32
struct BlockRefwhat draws through an anonymous block: DIMENSION (and its kinds ARC_DIMENSION, LARGE_RADIAL_DIMENSION) and ACAD_TABLE (2: the block; 10 its insertion point for a table)block: Option<Name>at: P3x_dir: Option<P3>-- ACAD_TABLE's 11: its horizontal direction (WCS)
struct LeaderLEADER: its vertices (WCS), an arrowhead (71), a spline path (72), the dimension style (3)vertices: Vec<P3>arrow: boolspline: booldimstyle: Option<Name>
struct WipeoutWIPEOUT (and IMAGE's frame, read alike): insertion point, the u and v vectors of a pixel, the size in pixels, the clip boundary in pixel coordinates (71: 1 a rectangle of two corners, 2 a polygon)at: P3u: P3v: P3size: [f64; 2]clip_type: u32clip: Vec<[f64; 2]>
enum Kindan entity's geometryLine { a: P3, b: P3 }Point { at: P3, angle: f64 }-- POINT: WCS, 50 the angle of its symbol (degrees)Circle { center: P3, radius: f64 }-- CIRCLE and ARC (OCS centre; angles in degrees, counter-clockwise from start to end)Arc { center: P3, radius: f64, start: f64, end: f64 }Ellipse { center: P3, major: P3, ratio: f64, start: f64, end: f64 }-- ELLIPSE: WCS centre, the major axis' end relative to it, minor / major, the parameters (radians)Spline(Spline)Polyline(Polyline)Mesh(Mesh)Text(Text)MText(MText)Insert(Insert)Hatch(Hatch)Quad(Quad)BlockRef(BlockRef)Leader(Leader)Wipeout(Wipeout)Ray { at: P3, dir: P3, both: bool }-- RAY (fromat) and XLINE (both ways)Other-- what this reader does not read (its kind in Common::kind): counted, not drawn
struct Layera layer of the tablename: Namecolor: Color-- 62 (its magnitude) or 420on: bool-- 62 negative: off; 70 bit 1: frozen, bit 4: locked; 290: plottedfrozen: boollocked: boolplot: boollinetype: Option<Name>-- 6 (None: CONTINUOUS)lineweight: Lineweight-- 370 (Default when absent)transparency: Option<u8>-- the XDATA AcCmTransparency (1071): an alpha
struct Dashan element of a linetype: a dash (positive), a gap (negative) or a dot (0); a shape or text of a complex linetype is kept as a flag (74) and its textlength: f64complex: u32text: Option<String>
struct LinetypeDefa linetype of the tablename: Namedescription: Stringdashes: Vec<Dash>total: f64-- 40
struct StyleDefa text style of the tablename: Namefont: String-- 3: the font file (txt, simplex.shx, arial.ttf, ...), 4 the big font filebigfont: Stringfamily: Option<String>-- the TrueType family the XDATA "ACAD" names (1000), if anyheight: f64-- 40 (0: none fixed), 41, 50 (degrees)width: f64oblique: f64flags: u32-- 70: 1 a shape file (not a text font), 4 vertical; 71: 2 backward, 4 upside downgeneration: u32
struct BlockRecorda block record of the tablename: Namehandle: u64units: i32-- 70: the insertion units
struct DimStylea dimension style (what a LEADER's arrow needs)name: Namearrow_size: f64-- 41 DIMASZ, 40 DIMSCALEscale: f64
struct Tablesthe tableslayers: Vec<Layer>linetypes: Vec<LinetypeDef>styles: Vec<StyleDef>block_records: Vec<BlockRecord>dimstyles: Vec<DimStyle>
impl Tables
fn layer(&self, n: Name) -> Option<&Layer>fn linetype(&self, n: Name) -> Option<&LinetypeDef>fn style(&self, n: Name) -> Option<&StyleDef>fn dimstyle(&self, n: Name) -> Option<&DimStyle>struct Headerthe header's variables this reader usesversion: String-- $ACADVER (AC1009 R12 ... AC1032 2018; empty without a header), $DWGCODEPAGEcodepage: Stringinsunits: i32-- $INSUNITS (0 unitless, 1 inch, 4 mm, 6 m, ...)ltscale: f64-- $LTSCALE, $CELTSCALElwdisplay: Option<bool>-- $LWDISPLAY (None: not in the file), $LWDEFAULT (hundredths of a mm)lwdefault: u16pdmode: i32-- $PDMODE, $PDSIZEpdsize: f64extmin: Option<P3>-- $EXTMIN, $EXTMAXextmax: Option<P3>dimscale: f64-- $DIMSCALE, $DIMASZ, $TEXTSIZE, $MIRRTEXTdimasz: f64textsize: f64mirrtext: boolpresent: bool-- whether the file had a HEADER section
struct Blocka block: its name, base point, flags (70: 1 anonymous, 2 attributes, 4 xref, 8 xref overlay, 16 external, 32 resolved, 64 referenced), entitiesname: Namebase: P3flags: u32xref: String-- 1: the file an xref namesentities: Vec<Entity>paper: bool-- *Paper_Space...: a layout's
enum Wherewhere an entity marker wasEntitiesBlocks
struct Statswhat was readkinds: BTreeMap<(Where, String), u64>-- entity markers per section and kind as the reader took them (VERTEX, ATTRIB, SEQEND, BLOCK, ENDBLK count too)paper: u64-- entities of ENTITIES in paper space (67 = 1)bytes: u64-- bytes and lines read, group pairslines: u64pairs: u64sections: Vec<String>-- sections seennotes: Vec<String>-- what was skipped or guessed, each once (at most 64)
impl Stats
fn count(&self, w: Where, kind: &str) -> u64the count of a kind in a sectiontrait Sinkwhat a streaming read hands out, in the file's order: the header (also an empty one, before anything else), the tables (once, when the TABLES section ends, or empty before the first block or entity), each block when its ENDBLK is read, each entity of ENTITIES (paper space too: Common::paper)fn header(&mut self, _h: &Header, _names: &Names)fn tables(&mut self, _t: &Tables, _names: &Names)fn block(&mut self, _b: Block, _names: &Names)fn entity(&mut self, _e: Entity, _names: &Names)
struct Documenta whole fileheader: Headertables: Tablesblocks: Vec<Block>entities: Vec<Entity>names: Namesstats: Stats
impl Document
fn name(&self, n: Name) -> &stra name's textfn block(&self, n: Name) -> Option<&Block>a block by its namefn load(bytes: &[u8], limits: &Limits) -> Result<Document>a whole file in memory into a Document (every entity kept: Limits::kept_entities and kept_points bound them)fn read(source: &mut dyn FnMut(&mut [u8]) -> usize, limits: &Limits, sink: &mut dyn Sink) -> Result<(Stats, Names)>a file read piece by piece:sourcefills a buffer and says how many bytes it put there (0: the end); the sink gets what was read in the file's order. Only the tables and the blocks are kept (Limits bound them); the entities of ENTITIES go to the sink one by onefn is_binary(bytes: &[u8]) -> boolwhether bytes begin like a binary DXFfn aci_rgb(i: u8) -> u32AutoCAD's colour index (ACI) as 0xRRGGBB: 1 red, 2 yellow, 3 green, 4 cyan, 5 blue, 6 magenta, 7 white (black on a light background: the caller decides), 8 and 9 greys, 10 to 249 24 hues of 15 degrees, each in five brightnesses (255, 204, 153, 127, 76) and each of those mixed half with white of that brightness, 250 to 255 greys; 0 and 256 (by block, by layer) are white
dxf/src/fonts.rs#
Source: lib/dxf/src/fonts.rs
fonts -- which font of the repository stands in for a text style's font (decision 31: SHX fonts belong to Autodesk,
and there are no Microsoft fonts in the repository). A substitute names a family (the caller has the bytes) and how
wide the original runs: the advance of the sample "a..z A..Z 0..9" over its cap height, from the original's metrics
(Helvetica / Arial, Times, Courier: their published advance widths; SHX fonts: estimates from their glyph grids,
docs/RENDER2D.md "DXF"). render2d::dxf turns that into a width factor against the substitute's own advance.
enum Familya family of the fonts in the repositorySans-- Inter (styles/netlab/assets): sans-serif, for Arial, Helvetica, Calibri, Verdana, Tahoma and every SHX fontSansBold-- Inter SemiBold: bold sans-serif (Arial Black, "... Bold")Serif-- DejaVu Serif (lib/doc_view/assets): Times, Georgia, Cambria, Garamond, Book AntiquaSerifBoldMono-- DejaVu Sans Mono: Courier, Consolas, Lucida Console, Source Code Pro, monotxt.shxMonoBoldUi-- Selawik (styles/winui/assets): Segoe UI
struct Substitutea font's stand-infamily: Familysample_advance: f64-- the original's advance of the sample "a..z A..Z 0..9" (62 characters) in cap heights; 0: keep the substitute's widthshx: bool-- an SHX font (single strokes) or a shape file
/// the sample whose advance sets the width factor of a substitute
SAMPLE: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123 ...
fn font_substitute(file: &str, family: Option<&str>) -> Substitutethe stand-in of a style's font file (3) or TrueType family (its XDATA), compared without case and path: TrueType names by their family, everything else (".shx", no extension, unknown) as an SHX font
dxf/src/mtext.rs#
Source: lib/dxf/src/mtext.rs
mtext -- MTEXT's inline format codes (G6e2): a text as paragraphs of runs, each run with its format.
\P paragraph \N column break \X (dimension text: a line break) \~ no-break space \\ \{ \} the characters
{ } a group: the format inside ends with it
\L \l underline on, off \O \o overline \K \k strike-through
\f<family>|b<0|1>|i<0|1>|c<charset>|p<pitch>; a TrueType family \F<file>; a font file (SHX)
\H<v>; \H<v>x; height (absolute, or times the current) \W<v>; \W<v>x; width factor
\Q<deg>; oblique \T<v>; \T<v>x; tracking (spacing of characters) \A<0|1|2>; bottom, centre, top
\C<aci>; colour of the palette (0 by block, 256 by layer) \c<bgr>; a true colour (blue in the high byte)
\S<top><sep><bottom>; stacked: / with a bar, # diagonal, ^ without a bar (tolerances)
\p...; paragraph: i<first line indent>, l<left indent>, r<right>, q<l|c|r|j|d> alignment, t<tabs> (x: ignored)
\U+XXXX a character \M+NXXXX a double byte of an East Asian page ^I tab, ^J line break, ^<c> control
%%c %%d %%p %%% %%nnn as in TEXT (strings::specials)
Unknown codes are dropped with their letter (a code with a ';' to its end); nothing recurses (the groups are a stack
of at most GROUP_DEPTH formats; deeper ones share the deepest).
/// the deepest nesting of { } groups that keeps formats of its own
GROUP_DEPTH: usize = 64
struct Formathow a run looksfont: Option<String>-- \f's family or \F's file (None: the entity's style), \f's bold and italic flagsshx: boolbold: boolitalic: boolheight: f64-- the cap height (drawing units)width: Option<f64>-- width factor, oblique angle (degrees; None: the style's), tracking factoroblique: Option<f64>tracking: f64color: Option<Color>-- None: the entity's colourunderline: booloverline: boolstrike: boolvalign: u8-- \A: 0 bottom, 1 centre, 2 top (where a smaller run sits on the line)
enum StackKinda stacked text's separatorBar-- '/': above and below a horizontal barDiagonal-- '#': a diagonal fractionTolerance-- '^': above and below, no bar (tolerances)
enum Itema piece of a paragraphText(String, Format)Stack { top: String, bottom: String, kind: StackKind, format: Format }Tab(Format)
enum Aligna paragraph's alignment (\pq; Default: the attachment point's)DefaultLeftCenterRightJustifyDistribute
struct Paragrapha paragraph: its alignment, indents (drawing units), tab stops, items; whether a column break came before italign: Alignindent_first: f64indent_left: f64indent_right: f64tabs: Vec<f64>column_break: boolitems: Vec<Item>
struct Mtextan MTEXT's contentparagraphs: Vec<Paragraph>
impl Mtext
fn plain(&self, height: f64) -> Option<String>the text, paragraphs joined by '\n', when it has nothing but text in the entity's own format, left aligned (what render2d's MText draws as it is); None otherwisefn text(&self) -> Stringall text without formats (for counts and tests): paragraphs by '\n', stacks as top/bottom, tabs as '\t'fn parse(text: &str, height: f64) -> MtextMTEXT's text (3 and 1 joined) as paragraphs of runs;heightis the entity's cap height
dxf/src/strings.rs#
Source: lib/dxf/src/strings.rs
strings -- a DXF's bytes as text: UTF-8 from AutoCAD 2007 (AC1021) on, before that the header's code page
($DWGCODEPAGE: formats::encoding's character sets and multi-byte encodings), \U+XXXX and \M+NXXXX in any
version; TEXT's %% codes (specials).
fn decode_unicode_escapes(s: &str) -> String\U+XXXX (four or five hex digits) as the character it names; \M+NXXXX as the double byte XXXX of the East Asian page N (mbcs). Everything else stays (also "\\": TEXT has no escapes; MTEXT is parsed by mtext::parse)struct Speciala run of a TEXT after its %% codes: the text and how it is decoratedtext: Stringunderline: booloverline: boolstrike: bool
fn specials(s: &str) -> Vec<Special>TEXT's %% codes: %%c the diameter sign (U+2205), %%d the degree sign, %%p plus-minus, %%nnn the character of that code (Windows-1252 above 127), %%% a percent sign; %%u, %%o and %%k switch underline, overline and strike-through on and off (the runs they start). Unknown codes stay as they are