Generating AutoCAD R12 (AC1009) ASCII .DXF Files in Pure TypeScript: 8 AIA Layers, $INSUNITS Inches, and Screen-to-CAD Arc Math

2026-11-28来源 dev.toEnglish

If you have ever exported a floor plan from a consumer browser tool only to open it in AutoCAD, BricsCAD, QCAD, or LibreCAD and see every wall, door swing, cabinet, and dimension flattened onto Layer 0 at arbitrary pixel coordinates, you know why contractors and drafters reject SVG-to-DXF converters. Real drafting software expects true 1:1 US inch coordinates, clean right-handed Cartesian geometry, separated AIA-style layers with distinct AutoCAD Color Index (ACI) colors, and valid DXF header and table records that never trigger a file-recovery prompt.

When we built the zero-dependency CAD export engine inside PlanCaliber, we targeted AutoCAD R12 (AC1009) ASCII .DXF directly from pure TypeScript. R12 ASCII is the universal lowest-common-denominator interchange standard in CAD: it requires no object-handle graph, no CLASSES or OBJECTS boilerplate, and opens cleanly at true scale across AutoCAD, Revit import, SketchUp Pro, DraftSight, LibreCAD, and QCAD.

Below are the five exact engineering details that make a pure-TypeScript .DXF writer production-safe.

1. Group-Code Pairs and the Minimal Valid R12 Header

An ASCII DXF file is an alternating sequence of integer group codes and values (code\nvalue\n). Every CAD viewer reads $ACADVER, $INSUNITS, $LUNITS, $EXTMIN, and $EXTMAX first so zoom-to-extents frames the building cleanly on open:

function fmt(n: number): string { return Number(n.toFixed(4)).toString(); } const lines: string[] = []; const push = (code: number, val: string | number): void => { lines.push(String(code), String(val)); }; push(0, 'SECTION'); push(2, 'HEADER'); push(9, '$ACADVER'); push(1, 'AC1009'); // AutoCAD R12 ASCII push(9, '$INSUNITS'); push(70, 1); // 1 = US Inches push(9, '$LUNITS'); push(70, 4); // 4 = Feet-and-inches fractional display push(9, '$LUPREC'); push(70, 4); // 1/16" display precision push(9, '$EXTMIN'); push(10, fmt(bounds.minX - 60)); push(20, fmt(-60)); push(30, '0'); push(9, '$EXTMAX'); push(10, fmt(bounds.maxX + 60)); push(20, fmt(bounds.depthIn + 60)); push(30, fmt(ceilingHeightIn)); push(0, 'ENDSEC'); 

Setting $INSUNITS = 1 (inches) and $LUNITS = 4 (feet-and-inches) ensures a 24'-0" garage wall measures exactly 288.0000 units when a contractor snaps a DIST measurement in AutoCAD, with zero manual rescaling.

2. Defining LTYPE and 8 AIA-Style CAD Layers (TABLES)

Before any LINE, ARC, CIRCLE, or TEXT entity references a linetype (such as DASHED for overhead beams or swing clearance arcs) or a layer name, both must be declared in the TABLES section. Otherwise strict CAD importers reject the drawing with an undefined table entry error.

PlanCaliber emits CONTINUOUS and DASHED linetypes (3.5" dash, 2.5" gap) followed by 8 standard residential drafting layers with distinct AutoCAD Color Index (62) values:

const layerDefs: { name: string; color: number }[] = [ { name: 'A-WALL', color: 7 }, // Structural & partition wall faces (white/black) { name: 'A-DOOR', color: 30 }, // Door slabs, jambs & swing arcs (amber/orange) { name: 'A-GLAZ', color: 4 }, // Window glass & sills (cyan) { name: 'A-CABN', color: 8 }, // Kitchen & bath cabinetry + appliances (dark gray) { name: 'A-FURN', color: 9 }, // Furniture & clearances (light gray) { name: 'E-POWR', color: 2 }, // NEC 210.52 outlets, switches & lights (yellow) { name: 'A-ROOM', color: 3 }, // Room names & ANSI Z765 areas (green) { name: 'A-DIMS', color: 6 } // Exterior & interior dimension strings (magenta) ]; push(0, 'TABLE'); push(2, 'LAYER'); push(70, layerDefs.length); for (const lyr of layerDefs) { push(0, 'LAYER'); push(2, lyr.name); push(70, 0); push(62, lyr.color); push(6, 'CONTINUOUS'); } push(0, 'ENDTAB'); 

Separating entities into these 8 layers lets an electrician toggle off A-FURN and A-CABN in one click while leaving A-WALL and E-POWR crystal clear.

3. Flipping Screen Y-Down Canvas Space to Cartesian CAD Y-Up

Browser canvases (<canvas> and <svg>) place (0, 0) at the top-left with +Y pointing downward. CAD software uses mathematical Cartesian coordinates with +Y pointing upward. Writing raw screen coordinates directly into a DXF file mirrors the entire house vertically and reverses every left-hand / right-hand door swing!

The fix is a single linear reflection flipY(y) = maxY - y applied consistently to every coordinate emitted:

const maxY = bounds.maxY; const flipY = (y: number): number => maxY - y; 

4. Door Swing ARC Angles Under Y-Reflection

The trickiest subtle bug in browser-to-DXF exporters is door swing arcs. In DXF, every ARC entity sweeps counter-clockwise (CCW) from start angle (group 50, degrees) to end angle (group 51, degrees). When you reflect Y, a 90-degree clockwise screen arc flips direction, and naively passing raw angles draws the 270-degree reflex arc swinging backward through the wall!

Instead of tracking handedness flags, compute both endpoint vectors in flipped DXF space and always choose the ordering whose CCW sweep is <= 180 degrees:

const addArcFromVectors = ( layer: string, hx: number, hy: number, radius: number, v1: { x: number; y: number }, v2: { x: number; y: number } ): void => { const a1 = (Math.atan2(flipY(hy + v1.y) - flipY(hy), v1.x) * 180) / Math.PI; const a2 = (Math.atan2(flipY(hy + v2.y) - flipY(hy), v2.x) * 180) / Math.PI; const normDeg = (d: number): number => ((d % 360) + 360) % 360; const n1 = normDeg(a1); const n2 = normDeg(a2); const ccwSpan = normDeg(n2 - n1); const startDeg = ccwSpan <= 180 ? n1 : n2; const endDeg = ccwSpan <= 180 ? n2 : n1; push(0, 'ARC'); push(8, layer); push(10, fmt(hx)); push(20, fmt(flipY(hy))); push(30, '0'); push(40, fmt(radius)); push(50, fmt(startDeg)); push(51, fmt(endDeg)); }; 

Because interior and exterior residential door swings are 90 degrees (<= 180), this invariant guarantees every single door arc sweeps strictly between the closed jamb vector and open leaf vector regardless of wall orientation or hinge side.

5. Centered TEXT Entities Without AutoCAD Origin-Jump

One classic R12 gotcha catches almost every first-time DXF author: if you set horizontal justification (72 = 1, center) or vertical justification (73 = 2, middle) on a TEXT entity, AutoCAD ignores primary coordinates (10, 20, 30) and reads the secondary alignment point (11, 21, 31) instead. If you omit (11, 21, 31), every room label silently piles up on top of (0, 0)!

Always write BOTH (10, 20, 30) and (11, 21, 31) when emitting centered room or dimension text:

push(0, 'TEXT'); push(8, layer); push(10, fmt(x)); push(20, fmt(flipY(y))); push(30, '0'); push(40, fmt(heightIn)); push(1, cleanText); push(72, 1); // Horizontal center push(73, 2); // Vertical middle push(11, fmt(x)); push(21, fmt(flipY(y))); push(31, '0'); 

Finally, always emit an empty BLOCKS section before ENTITIES and close the file cleanly with 0\nENDSEC\n0\nEOF\n.

Try True 1:1 Layered AutoCAD R12 .DXF Export in Your Browser

  • See how PlanCaliber compares to heavyweight desktop seats on our AutoCAD Floor Plan Alternative breakdown.
  • Trace a hand sketch or existing PDF straight into editable 2D/3D walls with our Sketch & PDF to CAD Tool, or customize a ready-made 40x60 Barndominium & Shop Template.
  • Check exact deliverables on PlanCaliber Pricing: draft free in 2D/3D, unlock unwatermarked 2-sheet vector PDFs for $9 one-time, or export the full 5-sheet 1/4"=1'-0" vector PDF + 8-layer AutoCAD R12 .DXF + 3D .OBJ + Framing & Drywall .CSV pack for $19 one-time (no subscription, 14-day instant refund).

Preliminary space-planning and CAD drafting software. Always verify structural dimensions, setbacks, and local US building codes on site before construction.

原文:https://www.a8q9.cn/en/article/generating-autocad-r12-ac1009-ascii-dxf-files-in-pure-typescript-8-aia-layers-in-745117.html

相关文章