From f401e3c07f680ad395e4a58ecfc7835283ccbe9e Mon Sep 17 00:00:00 2001 From: Administrator Date: Wed, 25 Nov 2026 23:18:29 +0700 Subject: [PATCH 1/4] Fix ATTRIB and HATCH parsing defects from issue #4 - ATTRIB: stop at the Xrecord (100 AcDbXrecord) or embedded MTEXT object (101) of a multiline attribute, whose reused group codes overwrote the attribute's position, height, text and layer. R12 attributes, which have no subclass markers, still read to the end. - HATCH edges: a clockwise arc or elliptic edge (73 = 0) stores its angles mirrored, so 0..120 clockwise runs from 0 to -120 degrees; it was drawn the long way round (-240). Elliptic edge angles are geometric and are now turned into ellipse parameters. Full turns stay full turns. Refs #4 Co-Authored-By: Claude Opus 5.5 --- src/dxf/hatch.ts | 72 +++++++++++++++++------------------- src/dxf/parseDxf.ts | 4 ++ test/hatch.test.ts | 79 ++++++++++++++++++++++++++++++++++++++++ test/parse-fixes.test.ts | 39 ++++++++++++++++++++ 4 files changed, 156 insertions(+), 38 deletions(-) diff --git a/src/dxf/hatch.ts b/src/dxf/hatch.ts index d682341..7c7b465 100644 --- a/src/dxf/hatch.ts +++ b/src/dxf/hatch.ts @@ -229,13 +229,8 @@ function parseEdge(edgeType: number, body: Pair[]): Point2D[] { const cy = at(20); const radius = at(40); if (cx === undefined || cy === undefined || radius === undefined) return []; - return sampleArc( - { x: cx, y: cy }, - radius, - ((at(50) ?? 0) * Math.PI) / 180, - ((at(51) ?? 360) * Math.PI) / 180, - at(73) !== 0 - ); + const { start, sweep } = edgeSweep(at(50) ?? 0, at(51) ?? 360, at(73) !== 0); + return sampleArc({ x: cx, y: cy }, radius, start, sweep); } case 3: { // Elliptic arc: centre (10,20), major axis vector (11,21), ratio 40. @@ -245,14 +240,8 @@ function parseEdge(edgeType: number, body: Pair[]): Point2D[] { const my = at(21); const ratio = at(40) ?? 1; if ([cx, cy, mx, my].some((n) => n === undefined)) return []; - return sampleEllipse( - { x: cx!, y: cy! }, - { x: mx!, y: my! }, - ratio, - ((at(50) ?? 0) * Math.PI) / 180, - ((at(51) ?? 360) * Math.PI) / 180, - at(73) !== 0 - ); + const { start, sweep } = edgeSweep(at(50) ?? 0, at(51) ?? 360, at(73) !== 0, ratio); + return sampleEllipse({ x: cx!, y: cy! }, { x: mx!, y: my! }, ratio, start, sweep); } case 4: { // Spline: degree 94, knots 40, control points 10/20. @@ -269,20 +258,41 @@ function parseEdge(edgeType: number, body: Pair[]): Point2D[] { } } -function sampleArc( - center: Point2D, - radius: number, - startAngle: number, - endAngle: number, - counterClockwise: boolean -): Point2D[] { - let sweep = endAngle - startAngle; +/** + * Where a boundary arc starts and how far it turns, in radians (negative = + * clockwise). DXF stores a clockwise edge (73 = 0) with its angles mirrored: + * 0..120 clockwise runs from 0° to -120°, not the long way round from 0° to + * 120°. An elliptic edge's angles are geometric (the direction from the + * centre), so with a `ratio` they are turned into ellipse parameters. + */ +export function edgeSweep( + startDeg: number, + endDeg: number, + counterClockwise: boolean, + ratio?: number +): { start: number; sweep: number } { + const span = endDeg - startDeg; + const fullTurn = span !== 0 && Math.abs(span) % 360 === 0; + const sign = counterClockwise ? 1 : -1; + const toAngle = (deg: number) => { + const a = (sign * deg * Math.PI) / 180; + // On an ellipse, the parameter whose point lies in direction a from the centre + return ratio ? Math.atan2(Math.sin(a) / ratio, Math.cos(a)) : a; + }; + const start = toAngle(startDeg); + if (fullTurn) return { start, sweep: sign * Math.PI * 2 }; + let sweep = toAngle(endDeg) - start; if (counterClockwise) { while (sweep <= 0) sweep += Math.PI * 2; + while (sweep > Math.PI * 2) sweep -= Math.PI * 2; } else { while (sweep >= 0) sweep -= Math.PI * 2; + while (sweep < -Math.PI * 2) sweep += Math.PI * 2; } + return { start, sweep }; +} +function sampleArc(center: Point2D, radius: number, startAngle: number, sweep: number): Point2D[] { const segments = Math.max( 2, Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * ARC_SEGMENTS_PER_TURN) @@ -298,21 +308,7 @@ function sampleArc( return points; } -function sampleEllipse( - center: Point2D, - major: Point2D, - ratio: number, - startAngle: number, - endAngle: number, - counterClockwise: boolean -): Point2D[] { - let sweep = endAngle - startAngle; - if (counterClockwise) { - while (sweep <= 0) sweep += Math.PI * 2; - } else { - while (sweep >= 0) sweep -= Math.PI * 2; - } - +function sampleEllipse(center: Point2D, major: Point2D, ratio: number, startAngle: number, sweep: number): Point2D[] { const segments = Math.max( 4, Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * ARC_SEGMENTS_PER_TURN) diff --git a/src/dxf/parseDxf.ts b/src/dxf/parseDxf.ts index 58b0e0f..5c38d7d 100644 --- a/src/dxf/parseDxf.ts +++ b/src/dxf/parseDxf.ts @@ -500,6 +500,10 @@ function parseAttrib( const code = lines[i].trim(); const value = lines[i + 1].trim(); if (code === '0') break; + // A multiline attribute ends with an Xrecord and an embedded MTEXT object that reuse + // the same group codes (10/20/40/1/8); they are not this attribute's fields. R12 + // attributes have neither marker, so they still read to the end. + if (code === '101' || (code === '100' && value === 'AcDbXrecord')) break; switch (code) { case '8': layer = value; break; diff --git a/test/hatch.test.ts b/test/hatch.test.ts index a77ffe9..48b47a6 100644 --- a/test/hatch.test.ts +++ b/test/hatch.test.ts @@ -203,3 +203,82 @@ test('a curved boundary is flattened into a polygon', () => { assert.ok(Number.isFinite(point.x) && Number.isFinite(point.y)); } }); + +/** One hatch whose single loop is the given edges (path type 0: edge-defined). */ +function edgeHatch(...edges: string[][]): string { + return dxf( + '0', 'SECTION', + '2', 'ENTITIES', + '0', 'HATCH', + '8', '0', + '2', 'SOLID', + '70', '1', + '91', '1', + '92', '0', + '93', String(edges.length), + ...edges.flat(), + '97', '0', + '0', 'ENDSEC' + ); +} + +const near = (actual: number, expected: number, label: string) => + assert.ok(Math.abs(actual - expected) < 1e-6, `${label}: expected ${expected}, got ${actual}`); + +/** Signed angle swept along a sampled arc around the origin, in degrees. */ +function sweptDegrees(points: { x: number; y: number }[]): number { + let total = 0; + for (let i = 1; i < points.length; i++) { + const a = Math.atan2(points[i - 1].y, points[i - 1].x); + const b = Math.atan2(points[i].y, points[i].x); + let d = b - a; + while (d > Math.PI) d -= 2 * Math.PI; + while (d < -Math.PI) d += 2 * Math.PI; + total += d; + } + return (total * 180) / Math.PI; +} + +test('a clockwise circular edge sweeps the arc its angles describe, not the rest of the circle (issue #4)', () => { + // DXF stores a clockwise edge's angles mirrored: 0..120 clockwise runs from 0° to -120° + const [hatch] = scanHatches(edgeHatch(['72', '2', '10', '0', '20', '0', '40', '10', '50', '0', '51', '120', '73', '0'])); + const loop = hatch.loops[0]; + near(sweptDegrees(loop), -120, 'sweep'); + near(loop[0].x, 10, 'start x'); + near(loop[0].y, 0, 'start y'); + near(loop[loop.length - 1].x, 10 * Math.cos((-120 * Math.PI) / 180), 'end x'); + near(loop[loop.length - 1].y, 10 * Math.sin((-120 * Math.PI) / 180), 'end y'); +}); + +test('a counter-clockwise circular edge is unchanged', () => { + const [hatch] = scanHatches(edgeHatch(['72', '2', '10', '0', '20', '0', '40', '10', '50', '0', '51', '120', '73', '1'])); + near(sweptDegrees(hatch.loops[0]), 120, 'sweep'); +}); + +test('a full clockwise circle edge still makes a whole turn', () => { + const [hatch] = scanHatches(edgeHatch(['72', '2', '10', '0', '20', '0', '40', '10', '50', '0', '51', '360', '73', '0'])); + near(Math.abs(sweptDegrees(hatch.loops[0])), 360, 'sweep'); +}); + +test('a clockwise elliptic edge stays in the quadrant its angles describe (issue #4)', () => { + const [hatch] = scanHatches( + edgeHatch(['72', '3', '10', '0', '20', '0', '11', '10', '21', '0', '40', '0.5', '50', '0', '51', '90', '73', '0']) + ); + const loop = hatch.loops[0]; + near(loop[0].x, 10, 'start x'); + near(loop[0].y, 0, 'start y'); + near(loop[loop.length - 1].x, 0, 'end x'); + near(loop[loop.length - 1].y, -5, 'end y'); + assert.ok(loop.every((p) => p.x >= -1e-9 && p.y <= 1e-9), 'every point in the lower-right quadrant'); +}); + +test('elliptic edge angles are geometric angles, turned into ellipse parameters', () => { + // 45° on an ellipse with axes 10 and 5 is where the ray at 45° meets it: x = y = 10*5/sqrt(10²+5²) + const [hatch] = scanHatches( + edgeHatch(['72', '3', '10', '0', '20', '0', '11', '10', '21', '0', '40', '0.5', '50', '0', '51', '45', '73', '1']) + ); + const end = hatch.loops[0][hatch.loops[0].length - 1]; + const r = (10 * 5) / Math.sqrt(10 * 10 + 5 * 5); + near(end.x, r, 'end x'); + near(end.y, r, 'end y'); +}); diff --git a/test/parse-fixes.test.ts b/test/parse-fixes.test.ts index e6d8e63..725e565 100644 --- a/test/parse-fixes.test.ts +++ b/test/parse-fixes.test.ts @@ -126,6 +126,45 @@ test('an invisible attribute is not drawn', () => { assert.deepEqual(modelEntities(text).filter((e) => e.type === 'TEXT').map((e) => (e as TextEntity).text), ['SHOWN']); }); +test('an attribute keeps its own fields when an Xrecord and an embedded MTEXT object follow (issue #4)', () => { + const text = withLayers( + [layer('0', 7), layer('TEST', 7)], + ...entities( + '0', 'INSERT', '8', '0', '66', '1', '2', 'NOPE', '10', '0', '20', '0', '30', '0', + '0', 'ATTRIB', '8', 'TEST', + '100', 'AcDbText', '10', '5', '20', '7', '30', '0', '40', '2.5', '1', 'LABEL', + '100', 'AcDbAttribute', '2', 'NAME', '70', '0', + '100', 'AcDbXrecord', '280', '1', '40', '1e307', + '101', 'Embedded Object', '10', '1e307', '20', '-1e307', '40', '1e307', '1', 'WRONG', '8', 'OTHER', + '0', 'SEQEND', '8', '0' + ) + ); + + const attribs = modelEntities(text).filter((e): e is TextEntity => e.type === 'TEXT'); + assert.equal(attribs.length, 1); + assert.equal(attribs[0].text, 'LABEL'); + assert.deepEqual(attribs[0].position, { x: 5, y: 7 }); + assert.equal(attribs[0].height, 2.5); + assert.equal(attribs[0].layer, 'TEST'); +}); + +test('an R12 attribute without subclass markers still reads every field', () => { + const text = withLayers( + [layer('0', 7), layer('TEST', 7)], + ...entities( + '0', 'INSERT', '8', '0', '66', '1', '2', 'NOPE', '10', '0', '20', '0', '30', '0', + '0', 'ATTRIB', '8', 'TEST', '10', '5', '20', '7', '30', '0', '40', '2.5', '1', 'LABEL', '2', 'NAME', '70', '0', + '0', 'SEQEND', '8', '0' + ) + ); + + const [attrib] = modelEntities(text).filter((e): e is TextEntity => e.type === 'TEXT'); + assert.equal(attrib.text, 'LABEL'); + assert.deepEqual(attrib.position, { x: 5, y: 7 }); + assert.equal(attrib.height, 2.5); + assert.equal(attrib.layer, 'TEST'); +}); + // ── OCS / extrusion ─────────────────────────────────────────────────────── test('a mirrored ARC (extrusion 0,0,-1) is drawn on the mirrored side', () => { From 8754f488c9746c758b78da2ce680e81b80c3ac86 Mon Sep 17 00:00:00 2001 From: Administrator Date: Wed, 25 Nov 2026 23:18:53 +0700 Subject: [PATCH 2/4] Ignore drawings cached before the issue #4 parser fixes Co-Authored-By: Claude Opus 5.5 --- src/ai/drawingStore.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ai/drawingStore.ts b/src/ai/drawingStore.ts index c91b86b..065441d 100644 --- a/src/ai/drawingStore.ts +++ b/src/ai/drawingStore.ts @@ -5,7 +5,7 @@ import type { DiskCache } from './diskCache'; export type { DrawingKey }; /** Bump whenever parser output changes, so stale disk caches are ignored. */ -export const CACHE_FORMAT = 1; +export const CACHE_FORMAT = 2; export interface StoredDrawing { key: DrawingKey; From 0ce46b0402346425ebff638459e02b1002ba5744 Mon Sep 17 00:00:00 2001 From: Administrator Date: Wed, 25 Nov 2026 23:31:54 +0700 Subject: [PATCH 3/4] Shut the drawing worker down after two idle minutes Its WASM heap stays allocated while the thread lives, so an idle worker held that memory until VS Code closed. A job sent before the delay ends cancels the release; the next job after it starts a new worker. Refs #4 Co-Authored-By: Claude Opus 5.5 --- src/dwg/workerClient.ts | 49 +++++++++++++++++++++++++++++++++++++++-- test/worker.test.ts | 30 +++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/src/dwg/workerClient.ts b/src/dwg/workerClient.ts index e496ab7..ef835df 100644 --- a/src/dwg/workerClient.ts +++ b/src/dwg/workerClient.ts @@ -16,6 +16,15 @@ const WORKER_HEAP_MB = 3072; */ const JOB_TIMEOUT_MS = 300_000; +/** + * How long the worker may sit with no job before it is shut down. Its WASM heap + * (LibreDWG, ODA's output) stays allocated for as long as the thread lives, so an + * idle worker would hold that memory until VS Code closes. Restarting costs one + * WASM load, under a second, so this only needs to cover opening several drawings + * in a row. + */ +const IDLE_MS = 120_000; + interface Job { request: WorkerRequest; resolve: (parsed: ParsedDxf) => void; @@ -28,6 +37,8 @@ interface Job { export interface DrawingWorkerOptions { /** Overrides JOB_TIMEOUT_MS. */ timeoutMs?: number; + /** Overrides IDLE_MS. */ + idleMs?: number; } /** @@ -35,13 +46,16 @@ export interface DrawingWorkerOptions { * load once. If the worker dies — out of memory, a crash in WASM — its jobs * fail with a readable message and the next job starts a fresh worker. A job * that runs too long fails alone: the worker is replaced and the jobs queued - * behind it are sent to the new one. + * behind it are sent to the new one. A worker left idle for IDLE_MS is shut + * down to give its memory back; the next job starts a new one. */ export class DrawingWorker { private worker: Worker | null = null; private readonly jobs = new Map(); private nextId = 1; private readonly timeoutMs: number; + private readonly idleMs: number; + private idleTimer?: ReturnType; constructor( private readonly scriptPath: string, @@ -49,6 +63,12 @@ export class DrawingWorker { options: DrawingWorkerOptions = {} ) { this.timeoutMs = options.timeoutMs ?? JOB_TIMEOUT_MS; + this.idleMs = options.idleMs ?? IDLE_MS; + } + + /** Whether a worker thread is alive (for tests and diagnostics). */ + get running(): boolean { + return this.worker !== null; } run(bytes: Uint8Array, filePath: string, converterPath: string, progress: (stage: Stage) => void): Promise { @@ -61,6 +81,7 @@ export class DrawingWorker { } async dispose(): Promise { + this.cancelIdle(); const worker = this.worker; this.worker = null; this.failAll(new Error('The drawing worker was shut down.')); @@ -68,6 +89,7 @@ export class DrawingWorker { } private send(request: WorkerRequest): void { + this.cancelIdle(); const worker = this.ensureWorker(); // Keep the process alive while a job is out; an idle worker must not. worker.ref(); @@ -154,7 +176,30 @@ export class DrawingWorker { private finish(id: number, job: Job): void { if (job.timer) clearTimeout(job.timer); this.jobs.delete(id); - if (this.jobs.size === 0) this.worker?.unref(); + if (this.jobs.size === 0 && this.worker) { + this.worker.unref(); + this.scheduleIdle(); + } + } + + private scheduleIdle(): void { + this.cancelIdle(); + this.idleTimer = setTimeout(() => { + this.idleTimer = undefined; + // A job sent since then cancelled this timer; check anyway, a busy worker is never released. + if (this.jobs.size > 0 || !this.worker) return; + const idle = this.worker; + // Cleared first, so the exit it reports is ignored and the next job starts a new worker. + this.worker = null; + this.log(`Drawing worker idle for ${this.idleMs} ms; shutting it down to free its memory`); + void idle.terminate(); + }, this.idleMs); + this.idleTimer.unref(); + } + + private cancelIdle(): void { + if (this.idleTimer) clearTimeout(this.idleTimer); + this.idleTimer = undefined; } private failAll(err: Error): void { diff --git a/test/worker.test.ts b/test/worker.test.ts index c58e78f..ffc61d2 100644 --- a/test/worker.test.ts +++ b/test/worker.test.ts @@ -83,3 +83,33 @@ test('a drawing waiting on its converter is not timed out by the one stuck after await worker.dispose(); } }); + +test('an idle worker is released, and the next drawing starts a fresh one (issue #4)', async () => { + const logs: string[] = []; + const worker = new DrawingWorker(WORKER, (msg) => logs.push(msg), { idleMs: 50 }); + try { + await worker.run(dxfBytes(), 'a.dxf', '', () => {}); + assert.equal(worker.running, true); + await new Promise((r) => setTimeout(r, 200)); + assert.equal(worker.running, false); + assert.ok(logs.some((m) => /idle/.test(m)), 'the release is logged'); + const parsed = await worker.run(dxfBytes(), 'b.dxf', '', () => {}); + assert.equal(parsed.pages[0].entities.length, 1); + } finally { + await worker.dispose(); + } +}); + +test('a drawing opened before the idle delay ends keeps the worker it would have lost', async () => { + const worker = new DrawingWorker(WORKER, () => {}, { idleMs: 150 }); + try { + await worker.run(dxfBytes(), 'a.dxf', '', () => {}); + await new Promise((r) => setTimeout(r, 100)); + const second = worker.run(dxfBytes(), 'b.dxf', '', () => {}); + await new Promise((r) => setTimeout(r, 100)); + assert.equal(worker.running, true, 'the pending job cancelled the release'); + await second; + } finally { + await worker.dispose(); + } +}); From 780ee8549f7ef3d2acdadb31266e9237b7bec30b Mon Sep 17 00:00:00 2001 From: Administrator Date: Wed, 25 Nov 2026 23:35:19 +0700 Subject: [PATCH 4/4] Release 1.4.1: ATTRIB and HATCH parsing fixes, idle worker released Refs #4 (parser defects and worker memory); large-drawing rendering performance is left for a separate issue. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 55e5a26..4fa5263 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "dwg-previewer", - "version": "1.4.0", + "version": "1.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dwg-previewer", - "version": "1.4.0", + "version": "1.4.1", "license": "GPL-3.0-or-later", "dependencies": { "@mlightcad/libredwg-web": "0.8.8", diff --git a/package.json b/package.json index 52bd3eb..9490be3 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "dwg-previewer", "displayName": "AutoCAD DWG & DXF Previewer", "description": "View AutoCAD DWG and DXF drawings inside VS Code — no AutoCAD needed. Open .dwg and .dxf files instantly with pan, zoom, layer control and SVG/PNG export.", - "version": "1.4.0", + "version": "1.4.1", "publisher": "bumkom", "license": "GPL-3.0-or-later", "icon": "icon.png",