From 3edf218a98bfed0fb02902bbebc53713d10b4e5c Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sun, 22 Nov 2026 19:26:31 -0500 Subject: [PATCH 01/15] The picture of a read file: toSVG of a DrawingRead, and tsdraft render of a DXF or DWG `toSVG` now draws a `DrawingRead` read with `geometry` as the leading CAD app shows the file: model space, or a layout as it plots, with its viewports and its plot style table. Every kind the readers keep is drawn by the same code that draws a `Drawing`: - A dimension and a table draw from the block of their picture. - A multileader draws from its own points and sizes, with the arrowheads of `leaderPicture`. - A text starts where that app starts it. Its font is the nearest one in `FONTS` where tsdraft lacks the file's own. - An insert draws its attributes where the file places them. - An xref draws from its own read, with its host's layer states, its own attachments and its own images. `readPicture(read, options)` gives the same picture, plus: - `notes`: the fonts drawn in another, what draws nothing (counted by kind), and what draws only nearly. - The picture in fragments, one for each entity at the top of each space, in the order the app draws them. `joinPicture` joins them back into the picture, and an edit can keep the fragments of what it leaves alone. The insert of an xref is a run of its own fragments, one for each entity of the xref's model space. `pictureDrawing(read)` gives the `Drawing` the picture draws, with the read handle of every entity, for pictures and the checks of text. It is not for writing. `tsdraft render` and `tsdraft dev` take a DXF, or a DWG a reader reads (from the project, or named with `--reader`), as they take a drawing file. They read the drawing's xrefs, and the xrefs' own attachments, from beside it. Their `read-picture` warnings list what the pictures could not draw as the file holds it. The picture also escapes every character XML cannot hold. A file's text with a control character no longer makes an SVG a renderer refuses. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 10 + cli/src/build.ts | 19 +- cli/src/cli.ts | 17 +- cli/src/dev.ts | 3 +- cli/src/read-child.ts | 6 +- cli/src/read.ts | 19 +- cli/src/state.ts | 7 +- cli/src/worker.ts | 270 ++++++- cli/test/render.test.ts | 25 +- docs/agents/pictures.md | 10 + docs/command.md | 8 + docs/reading.md | 46 ++ src/blocks.ts | 5 + src/index.ts | 19 + src/picture-marks.ts | 131 ++++ src/read/picture.ts | 1515 +++++++++++++++++++++++++++++++++++++ src/read/plan.ts | 12 +- src/svg.ts | 406 ++++++++-- test/read-fuzz.ts | 23 +- test/read-picture.test.ts | 376 +++++++++ 20 files changed, 2858 insertions(+), 69 deletions(-) create mode 100644 src/picture-marks.ts create mode 100644 src/read/picture.ts create mode 100644 test/read-picture.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c17fa4..d50c6d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- The picture of a read file. `toSVG` draws a `DrawingRead` read with `geometry` as the leading + CAD app shows the file: model space, or a layout as it plots, with every kind the readers keep. + A dimension and a table draw from the block of their picture, a multileader from its own + points, a text from where that app starts it, in the nearest font of `FONTS` where tsdraft lacks + its own. `readPicture` gives the picture with notes of what it could not draw as the file holds + it, and in fragments, one for each entity at the top of a space, which `joinPicture` joins. + `pictureDrawing` gives the `Drawing` it draws. +- `tsdraft render` and `tsdraft dev` draw a DXF, and a DWG through a reader the project installs + or `--reader` names, as they draw a drawing file. + ## 0.5.4 This release has breaking changes, though its number is a patch's. A project that depends on diff --git a/cli/src/build.ts b/cli/src/build.ts index e382159..6d51964 100644 --- a/cli/src/build.ts +++ b/cli/src/build.ts @@ -24,6 +24,8 @@ const workerPath = new URL( import.meta.url, ); const LOG_LIMIT = 8_000; +/** How long the build of a DXF or a DWG may take at least: the read's own limit, and its pictures. */ +const READ_TIMEOUT = 150_000; const SPARES = 2; /** A warm-up takes a fraction of a second. One that takes this long will not end. */ const WARM_DEADLINE = 2_000; @@ -66,6 +68,8 @@ export class Builder { */ readonly #spares: Child[] = []; readonly #view: BuildRequest["view"]; + /** The package that reads a DWG, as `--reader` names it. */ + readonly #reader: string | undefined; #running: Child | undefined; /** The library the last good build used, when a spare may load it ahead. */ #library: string | null = null; @@ -88,7 +92,10 @@ export class Builder { warmDeadline?: number; /** The one picture to draw, in place of the pictures of every space. */ view?: BuildRequest["view"]; + /** The package that reads a DWG, by its name in the project or its folder. */ + reader?: string; }) { + this.#reader = options.reader; this.#drawNoPlot = options.drawNoPlot === true; this.#view = options.view; this.#timeout = options.timeout; @@ -115,9 +122,17 @@ export class Builder { try { const running = run( child, - { type: "build", file, root, drawNoPlot: this.#drawNoPlot, view: this.#view }, + { + type: "build", + file, + root, + drawNoPlot: this.#drawNoPlot, + view: this.#view, + ...(this.#reader === undefined ? {} : { reader: this.#reader, cwd: process.cwd() }), + }, started, - this.#timeout, + // A read has its own time limit, as the read of any drawing file has. + /\.(dxf|dwg)$/i.test(file) ? Math.max(this.#timeout, READ_TIMEOUT) : this.#timeout, ); // Starting the next child takes time, so a child that is ready is sent the file first. if (child.isReady) await null; diff --git a/cli/src/cli.ts b/cli/src/cli.ts index ba8073c..a6d6ee9 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -23,9 +23,13 @@ const HELP = `Usage: tsdraft render [--out ] [--width ] [--timeout ] [--pdf] [--draw-no-plot] [--view [--layout ]] tsdraft dev [--port ] [--timeout ] [--draw-no-plot] + For a DXF or a DWG, either takes [--reader ] A drawing file is a TypeScript module whose default export is a Drawing, or a -function that returns one. +function that returns one. It may also be a DXF, or a DWG that a reader the +project installs reads: its pictures are the file as the leading CAD app shows +it, model space and each layout as it plots, read with geometry, and the JSON's +read-picture warnings say what they could not draw as the file holds it. render Builds the file once, writes .svg and .png to --out (default: an out folder beside the file), and prints the result as JSON. Exits 0 @@ -55,8 +59,11 @@ dev Serves a live preview on localhost that rebuilds on every save of the --pdf With render, plots the sheets to PDF as well, as listed above. --draw-no-plot Draws the layers that do not plot too. The pictures leave them out by default, as a plot does. +--reader The package that reads a DWG, by its name in the project or the path + to its folder, when the project names none or more than one. --port Default 4610. When it is taken and no port was given, a free one. ---timeout How long a build may run. Default 10000. +--timeout How long a build may run. Default 10000. The build of a DXF or a + DWG takes at least 150000, as long as its read may take. Misuse prints this to stderr and exits 64, so stdout holds only JSON. @@ -98,6 +105,7 @@ try { pdf: { type: "boolean" }, view: { type: "string" }, layout: { type: "string" }, + reader: { type: "string" }, help: { type: "boolean", short: "h" }, }, }); @@ -121,6 +129,9 @@ const timeout = number(values.timeout, "--timeout") ?? 10_000; if (values.view !== undefined && command !== "render") usage("--view goes with render."); if (values.layout !== undefined && values.view === undefined) usage("--layout goes with --view."); if (values.pdf && command !== "render") usage("--pdf goes with render."); +if (values.reader !== undefined && !/\.(dxf|dwg)$/i.test(file)) { + usage("--reader goes with a DXF or a DWG."); +} if (values.pdf && values.view !== undefined) usage("--pdf plots whole sheets, and --view draws one rectangle."); if (values.pdf && values["draw-no-plot"]) { @@ -133,6 +144,7 @@ if (command === "dev") { port: number(values.port, "--port"), timeout, drawNoPlot: values["draw-no-plot"] === true, + ...(values.reader === undefined ? {} : { reader: values.reader }), }); } else { const width = number(values.width, "--width") ?? 1600; @@ -141,6 +153,7 @@ if (command === "dev") { timeout, warm: false, drawNoPlot: values["draw-no-plot"] === true, + ...(values.reader === undefined ? {} : { reader: values.reader }), view: view && { box: view, ...(values.layout === undefined ? {} : { layout: values.layout }) }, }); // The plotter loads only for --pdf, and before anything is built or written, as a static diff --git a/cli/src/dev.ts b/cli/src/dev.ts index ec57b74..9aed569 100644 --- a/cli/src/dev.ts +++ b/cli/src/dev.ts @@ -40,7 +40,7 @@ interface BuildEvent { export async function dev( file: string, - options: { port: number | undefined; timeout: number; drawNoPlot?: boolean }, + options: { port: number | undefined; timeout: number; drawNoPlot?: boolean; reader?: string }, ): Promise { const root = projectRoot(file); const session = randomUUID().slice(0, 8); @@ -48,6 +48,7 @@ export async function dev( timeout: options.timeout, warm: true, drawNoPlot: options.drawNoPlot === true, + ...(options.reader === undefined ? {} : { reader: options.reader }), }); /** Why this server makes no PNG, when the optional renderer is absent. */ const noPng = pngUnavailable(); diff --git a/cli/src/read-child.ts b/cli/src/read-child.ts index 73aafa3..b2a13a5 100644 --- a/cli/src/read-child.ts +++ b/cli/src/read-child.ts @@ -4,7 +4,7 @@ // that prints cannot reach, and ends. import { writeSync } from "node:fs"; import { pathToFileURL } from "node:url"; -import type { ReadDrawingFile } from "tsdraft"; +import type { ReadDrawingFile, ReadOptions } from "tsdraft"; /** What the process answers: the reader's result, or why there is none. */ export type ReadAnswer = @@ -15,6 +15,8 @@ export type ReadAnswer = const ANSWER = 3; const [name = "", module] = process.argv.slice(2); +/** What to read, as `ReadOptions`: the command sets it when it draws the file. */ +const options: ReadOptions = process.env["TSDRAFT_READ_GEOMETRY"] === "1" ? { geometry: true } : {}; const message = (error: unknown): string => (error instanceof Error ? error.message : String(error)).slice(0, 2_000); @@ -51,7 +53,7 @@ try { answer({ error: message(error), loading: true }); } try { - answer({ read: await read(process.stdin, name) }); + answer({ read: await read(process.stdin, name, options) }); } catch (error) { answer({ error: message(error), loading: false }); } diff --git a/cli/src/read.ts b/cli/src/read.ts index b219eb1..751873f 100644 --- a/cli/src/read.ts +++ b/cli/src/read.ts @@ -10,7 +10,7 @@ import { stat } from "node:fs/promises"; import { basename, join } from "node:path"; import { pipeline, type Readable } from "node:stream"; import { fileURLToPath } from "node:url"; -import { checkDrawingRead, type DrawingRead } from "tsdraft"; +import { checkDrawingRead, type DrawingRead, type ReadOptions } from "tsdraft"; import { lookup, OWN_FOLDER, type ReaderPackage } from "./readers.ts"; const childPath = realpathSync.native( @@ -131,6 +131,7 @@ export function readDrawingFile( file: string, reader: ReaderPackage | null, limits: ReadLimits = {}, + options: ReadOptions = {}, ): Promise { const by: ReadBy = reader ? { name: reader.name, version: reader.version } : core; const skip = (skipped: string): FileRead => ({ file, reader: by, skipped }); @@ -156,12 +157,13 @@ export function readDrawingFile( if (!reader && extension(file) !== ".dxf") { return skip(`no installed reader reads ${basename(file)}`); } - const outcome = await run(file, module, permission(reader), { - maxFileBytes, - maxMemoryMb, - timeoutMs, - maxAnswerBytes, - }); + const outcome = await run( + file, + module, + permission(reader), + { maxFileBytes, maxMemoryMb, timeoutMs, maxAnswerBytes }, + options, + ); return "read" in outcome ? { file, reader: by, read: outcome.read } : skip(outcome.skipped); }); } @@ -181,6 +183,7 @@ function run( module: string | undefined, allow: readonly string[], limits: Required, + options: ReadOptions, ): Promise<{ read: DrawingRead } | { skipped: string }> { const { maxFileBytes, maxMemoryMb, timeoutMs, maxAnswerBytes } = limits; prlimit ??= spawnSync("prlimit", ["--core=1:1", "true"], { stdio: "ignore" }).status === 0; @@ -201,6 +204,8 @@ function run( // NODE_OPTIONS would add its own flags to the process's, and could allow what is denied. const env = { ...process.env }; delete env["NODE_OPTIONS"]; + if (options.geometry === true) env["TSDRAFT_READ_GEOMETRY"] = "1"; + else delete env["TSDRAFT_READ_GEOMETRY"]; if (!watching) { watching = true; process.once("exit", endLive); diff --git a/cli/src/state.ts b/cli/src/state.ts index ddd7e05..b06c5ca 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -210,6 +210,10 @@ export interface PngFont { * `footprint-off-property` the footprint's box. `footprint-in-setback` also gives `side`, * `required` and `provided`. * + * `read-picture` is a warning of the command's own about a drawing file a reader reads, a DXF or + * a DWG: a text style whose font tsdraft does not have and the font its text is drawn in, or what + * the pictures draw as nothing, or only nearly, counted by kind. + * * `standard-unchecked` is a warning of the command's own, among lint's: the file exports a * standard, and the copy of tsdraft the drawing loaded is from before standards, so `lint` held * the drawing to none of it. @@ -219,7 +223,8 @@ export interface BuildDiagnostic extends Omit { | Diagnostic["rule"] | TextWarning["rule"] | IntentWarning["rule"] - | "standard-unchecked"; + | "standard-unchecked" + | "read-picture"; readonly kind?: Entity["kind"]; /** The box around the entity, in drawing units, worked out as `extents` is. */ readonly bounds?: Box; diff --git a/cli/src/worker.ts b/cli/src/worker.ts index 79143ce..88ebe7d 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -21,6 +21,7 @@ import type { DimensionPicture, DimensionStyle, Drawing, + DrawingRead, Entity, Intent, IntentWarning, @@ -57,6 +58,9 @@ export interface BuildRequest { readonly root: string; /** Draws the layers that do not plot too. */ readonly drawNoPlot?: boolean; + /** For a DXF or a DWG: the package that reads it, as `--reader` names it, from `cwd`. */ + readonly reader?: string; + readonly cwd?: string; /** * Draws this one rectangle, of model space or of the layout named, in place of the pictures * of every space. @@ -526,7 +530,271 @@ async function warm(library: string | null, deadline: number): Promise { process.send!({ type: "warmed", kept: closed, held } satisfies WorkerMessage); } -async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { +/** The most xrefs of a read file whose drawings a build reads. */ +const XREFS_READ = 32; + +/** A file a reader reads, which the command draws as the leading CAD app shows it. */ +export const READ_FILE = /\.(dxf|dwg)$/i; + +async function build(request: BuildRequest): Promise { + return READ_FILE.test(request.file) ? buildRead(request) : buildCode(request); +} + +/** + * The pictures of a drawing file a reader reads: model space and each layout, drawn from the read + * with geometry by `readPicture`, with what it could not draw as warnings. + */ +async function buildRead({ + file, + drawNoPlot, + view, + reader: named, + cwd, +}: BuildRequest): Promise { + const timings: { load?: number; svg?: number } = {}; + const failed = (message: string, name = "ReadError"): WorkerResult => ({ + ok: false, + files: readFiles(file), + timings, + drawing: null, + diagnostics: [], + svg: null, + fonts: [], + layouts: [], + view: null, + swatches: {}, + error: { + name, + message, + code: null, + file, + line: null, + column: null, + stack: "", + }, + library: null, + modules, + }); + let t = now(); + track(file, fileVersion(file)); + const library = (await import("tsdraft")) as typeof import("tsdraft") & Library; + const { findReaders, readerFor, ReaderRefusal } = await import("./readers.ts"); + const { readDrawingFile } = await import("./read.ts"); + /** The reader of a file of an extension: `--reader`'s, the project's, or the file's folder's. */ + const readerOf = (extension: string) => { + const at = cwd ?? process.cwd(); + const found = readerFor( + findReaders({ cwd: at, inputs: [file], ...(named === undefined ? {} : { reader: named }) }), + extension, + ); + if (found !== null || named !== undefined || extension.toLowerCase() === ".dxf") return found; + return readerFor(findReaders({ cwd: dirname(file), inputs: [file] }), extension); + }; + let reader; + try { + reader = readerOf(/\.[^.]*$/.exec(file)![0]); + } catch (error) { + if (error instanceof ReaderRefusal) return failed(error.message); + throw error; + } + const outcome = await readDrawingFile(file, reader, {}, { geometry: true }); + timings.load = now() - t; + if ("skipped" in outcome) return failed(`${file} was not read: ${outcome.skipped}`); + const read = outcome.read; + t = now(); + try { + // The size of each page the underlays show, read from its PDF beside the file. + const pageSizes: Record> = Object.create( + null, + ); + const pdfs = new Map(); + const spaces = [ + read.model.entities, + ...read.layouts.map((l) => l.entities), + ...read.blocks.map((b) => b.entities), + ]; + for (const list of spaces) { + for (const e of list ?? []) { + if (e.kind !== "underlay" || isAbsolute(e.path) || /^[A-Za-z]:/.test(e.path)) continue; + const at = join(dirname(file), e.path.replaceAll("\\", "/")); + let pdf = pdfs.get(at); + if (pdf === undefined) { + track(at, fileVersion(at)); + try { + pdf = new Uint8Array(readFileSync(at)); + } catch { + pdf = null; + } + pdfs.set(at, pdf); + } + const size = pdf === null ? undefined : library.pdfPageSize(pdf, e.page); + if (size !== undefined) (pageSizes[e.path] ??= Object.create(null))[e.page] = size; + } + } + // Each xref's drawing, read from the path the file holds, from the folder of the file that + // holds it, or else by its name in that folder, where CAD programs look next: the file's own + // xrefs, and theirs. Each is given with all of them, so an xref finds its own attachments. + type Given = { + read: DrawingRead; + xrefs: typeof xrefs; + images?: Record; + }; + // The bytes of the images of every drawing, the host's and its xrefs', count against one budget. + const budget = { total: 0 }; + const diagnostics: BuildDiagnostic[] = []; + const xrefs: Record = Object.create(null); + let level: { readonly list: DrawingRead["xrefs"]; readonly from: string }[] = [ + { list: read.xrefs, from: file }, + ]; + let reads = 0; + for (let depth = 0; depth < 2 && level.length > 0; depth++) { + const next: typeof level = []; + for (const { list, from } of level) { + for (const xref of list) { + if (Object.hasOwn(xrefs, xref.name) || reads >= XREFS_READ) continue; + const path = xref.path.replaceAll("\\", "/"); + const name = path.slice(path.lastIndexOf("/") + 1); + const found = [ + ...(isAbsolute(path) || /^[A-Za-z]:/.test(path) ? [] : [join(dirname(from), path)]), + join(dirname(from), name), + ].find((at) => existsSync(at) && statSync(at).isFile()); + if (found === undefined || !/\.(dxf|dwg)$/i.test(found) || found === file) continue; + track(found, fileVersion(found)); + let xrefReader; + try { + xrefReader = readerOf(/\.[^.]*$/.exec(found)![0]); + } catch { + continue; + } + reads++; + const got = await readDrawingFile(found, xrefReader, {}, { geometry: true }); + if (!("read" in got)) continue; + // Its images, from its own folder. + const rasters = rasterFiles( + library, + library.pictureDrawing(got.read).drawing, + found, + budget, + xref.name, + ); + diagnostics.push(...rasters.diagnostics); + xrefs[xref.name] = { + read: got.read, + xrefs, + ...(rasters.images !== undefined && { images: rasters.images }), + }; + next.push({ list: got.read.xrefs, from: found }); + } + } + level = next; + } + const made = library.pictureDrawing(read, { pageSizes, xrefs }); + const shown = made.drawing; + const rasters = rasterFiles(library, shown, file, budget); + diagnostics.push(...rasters.diagnostics); + const pages = pageFiles(library, shown, file, budget); + diagnostics.push(...pages.diagnostics); + const shaped = shapeFiles(library, shown, file); + const options = { + drawNoPlot: drawNoPlot === true, + pageSizes, + xrefs, + ...(rasters.images === undefined ? {} : { images: rasters.images }), + ...(pages.underlays === undefined ? {} : { underlays: pages.underlays }), + ...shaped, + }; + const { notes } = made; + for (const { style, font, drawnIn } of notes.fonts) { + diagnostics.push({ + rule: "read-picture", + severity: "warning", + message: `The text style ${JSON.stringify(style)} sets its text in ${JSON.stringify(font)}, which tsdraft does not have, so the pictures measure and draw it in ${drawnIn}`, + }); + } + for (const [kind, n] of Object.entries(notes.notDrawn)) { + diagnostics.push({ + rule: "read-picture", + severity: "warning", + message: `The pictures draw nothing for ${n} of ${JSON.stringify(kind)}, which the read does not keep or the picture cannot draw`, + }); + } + for (const [what, n] of Object.entries(notes.approximate)) { + diagnostics.push({ + rule: "read-picture", + severity: "warning", + message: `The pictures draw ${n} of ${JSON.stringify(what)} only nearly as the file holds it`, + }); + } + const fontsOf = fontsIn(library, [shown]); + let viewed: WorkerResult["view"] = null; + let svg: string | null = null; + let min: [number, number] = [0, 0]; + let max: [number, number] = [0, 0]; + const sheets: { name: string; svg: string; fonts: string[] }[] = []; + if (view) { + const one = library.readPicture(read, { + ...options, + view: view.box, + ...(view.layout === undefined ? {} : { layout: view.layout }), + }).svg; + viewed = { layout: view.layout ?? null, svg: one, fonts: fontsOf(one) }; + } else { + ({ svg, min, max } = framed(library.readPicture(read, { ...options, margin: 0 }).svg)); + const names = new Set(); + for (const layout of read.layouts) { + // A layout the read did not read has no picture: it is not empty. + if (names.has(layout.name) || layout.entities === undefined) continue; + names.add(layout.name); + const sheet = library.readPicture(read, { ...options, layout: layout.name }).svg; + sheets.push({ name: layout.name, svg: sheet, fonts: fontsOf(sheet) }); + } + } + timings.svg = now() - t; + const units = shown.units; + return { + ok: true, + files: readFiles(file), + timings, + drawing: { + units, + dxf: shown.dxf, + standard: null, + extents: { min, max }, + counts: { + layers: read.layers.length, + entities: read.model.entities?.length ?? 0, + blocks: read.blocks.length, + xrefs: read.xrefs.length, + layouts: read.layouts.length, + errors: 0, + warnings: diagnostics.length, + }, + layers: layerSummaries(shown), + blocks: [], + inserts: [], + dimensions: [], + xrefs: [], + layouts: layoutSummaries(library, shown), + }, + diagnostics, + svg, + fonts: svg === null ? [] : fontsOf(svg), + layouts: sheets, + view: viewed, + swatches: {}, + error: null, + library: null, + modules, + }; + } catch (thrown) { + return failed( + `${file} was read, and its pictures could not be drawn: ${(thrown as Error).message}`, + "PictureError", + ); + } +} + +async function buildCode({ file, root, drawNoPlot, view }: BuildRequest): Promise { const timings: { load?: number; lint?: number; diff --git a/cli/test/render.test.ts b/cli/test/render.test.ts index cd2ccbe..d06fbca 100644 --- a/cli/test/render.test.ts +++ b/cli/test/render.test.ts @@ -18,7 +18,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { deflateSync } from "node:zlib"; import { after, test } from "node:test"; import { inScratch } from "./scratch.ts"; -import { BUILT_IN_STANDARD, pdfFace } from "tsdraft"; +import { BUILT_IN_STANDARD, pdfFace, toDXF } from "tsdraft"; import { faces } from "../src/fonts.ts"; import type { BuildState } from "../src/state.ts"; @@ -1702,3 +1702,26 @@ test("render checks each underlay's page size against its PDF, and draws no page // The page is drawn as missing at each placement, since one of them is refused. assert.doesNotMatch(readFileSync(state.outputs.svg!, "utf8"), / { + const out = tempDir(); + const { default: sheet } = await import( + pathToFileURL(join(root, "../examples/site-plan.ts")).href + ); + const file = join(out, "sheet.dxf"); + writeFileSync(file, toDXF(sheet)); + const { state, status } = render(file, "--out", out, "--width", "600"); + assert.equal(status, 0, JSON.stringify(state.error)); + assert.equal(state.ok, true); + assert.equal(state.outputs.svg, join(out, "sheet.svg")); + assert.deepEqual( + state.outputs.layouts.map((l) => [l.name, l.svg]), + [["C-101", join(out, "sheet.layout-C-101.svg")]], + ); + assert.match(readFileSync(state.outputs.layouts[0]!.svg, "utf8"), /data-picture=/); + assert.equal(state.drawing?.counts.layouts, 1); + assert.ok( + state.diagnostics.every((d) => d.rule !== "read-picture"), + JSON.stringify(state.diagnostics), + ); +}); diff --git a/docs/agents/pictures.md b/docs/agents/pictures.md index 437a504..1604f15 100644 --- a/docs/agents/pictures.md +++ b/docs/agents/pictures.md @@ -75,3 +75,13 @@ fonts or dashes. [AGENTS.md](../../AGENTS.md) has the rules that hold for every that app makes that `A` as tall as the text's height. It is not the cap height the font states. Add a font only when the 2025 release of that app or Windows installs it. +- A read file's picture is `src/read/picture.ts`: `pictureDrawing` turns a `DrawingRead` into the + `Drawing` `toSVG` draws, and what a `Drawing` cannot hold, a paper tsdraft does not list, an + entity's own linetype scale and a layer's true color, rides on the symbols of + `src/picture-marks.ts`, which only `toSVG` reads. Draw a new kind of `ReadEntity` there, from the + kinds a `Drawing` has, never with code of its own in `src/svg.ts`. With `READ_SOURCES` given, + `svgWithin` groups the elements of each top-level read entity into one fragment, starts each id + it makes from the fragment's viewport and handle, and names an image's picture by its file, so + a fragment kept from one picture joins with another's. Without it, the picture of a `Drawing` is + byte for byte what it was: change the pieces in `finish` so that `joinPicture` gives the same + text either way. diff --git a/docs/command.md b/docs/command.md index c53cd93..04b8670 100644 --- a/docs/command.md +++ b/docs/command.md @@ -58,6 +58,14 @@ as it plots: a layer that does not plot is left out, as one that is off or froze `--draw-no-plot` draws those layers too. `tsdraft dev` takes the same flag. The colors are the ones a plot gives each pen, so the darkest pens are faint on the dark preview. +`render` and `dev` take a DXF, or a DWG a reader reads, as they take a drawing file: they read it +with geometry, within the limits of [Reading drawing files](#reading-drawing-files), and draw +model space and each layout as [the picture of a read file](reading.md#the-picture-of-a-read-file) +draws them, with the images, the pages of the underlays and the shape files the file names from +its own folder. `--reader ` names the reader of a DWG where the project names +none or more than one. Their `read-picture` warnings say what the pictures could not draw as the +file holds it. A build of such a file may take as long as its read, at least 150 s. + With `--pdf`, `render` also plots the sheets of a drawing with layouts: `.layout-.pdf`, each sheet alone, in `outputs.layouts[].pdf`, and `.pdf`, the set, with a page for each layout in order, in `outputs.pdf`. Each is made from the picture of its sheet, as diff --git a/docs/reading.md b/docs/reading.md index 7744961..245c651 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -333,6 +333,52 @@ that is not an integer, or a file that ends between a code and its value. A reco layer, block name or tag is longer than the 2,049 characters a DXF value holds is counted under `unread.malformed`. +## The picture of a read file + +`toSVG(read, options)` draws a `DrawingRead` read with `geometry` as the leading CAD app shows the +file: model space, or with `layout` the sheet as it plots, with its viewports, their scale, twist +and frozen layers, at the layout's plot style table where tsdraft has it and at `acad.ctb` where +the layout names none. It takes the options a drawing's picture takes, and two more: `xrefs`, the +read each xref stands for, by its name, drawn with the states of its layers the host holds as +`XREF|LAYER`; and `pageSizes`, the size in inches of each page the underlays show, by path and +page, as `pdfPageSize` reads it. + +Each kind the readers keep is drawn by the code that draws a drawing's: + +- A dimension and a table are drawn from the block of their picture, which is what the leading CAD + app shows and plots. One with no such block draws nothing. +- A multileader is drawn from its own points, its landing and sizes, with the arrowheads of + `leaderPicture`; an old leader from its points, with its dimension style's arrow size. +- A text starts where that app starts it, `at`. A text justified to `fit` or `aligned` is fitted + between its two points. A text in a font tsdraft does not have is measured and drawn in the + nearest font of `FONTS`, as `nearestFont` picks it. +- An insert draws its block and each attribute that shows, where the file places it. A constant + attribute draws in every insert of its block. +- A solid draws as a filled outline, a hatch with the lines of its pattern as the file holds + them, and a 3D solid, region or body as `edgesInPlan` gives its edges. +- An entity's own linetype scale, a layer's true color and a paper tsdraft does not list are + drawn as the file holds them. + +`readPicture(read, options)` draws the same picture and gives, beside `svg`: + +- `notes`: each text style whose font tsdraft does not have, with the font drawn in its place; + what draws nothing, counted by kind, which holds what the read counts under a space's or a + block's `other` and under `unread.entities`; and what draws only nearly, counted by what, such + as a mirrored text or an image a file slants. +- `pieces` and `defs`: the picture in pieces, which `joinPicture(pieces, defs)` joins into `svg`. + Each space it draws, a layout's paper and model space through each of its viewports or alone, + is a `PictureRun` of fragments, one for each entity at the top of the space that shows, in the + order the leading CAD app draws them: the `drawOrder` the file holds, then the rest in the + file's order. A fragment has its entity's `index` among the space's `entities`, its `handle`, + its `svg` and the ids of the definitions it uses, such as an image's picture or a gradient. + Each id a fragment makes starts from its viewport and its entity's handle, and an image's + comes from its file, so a fragment kept from one picture joins with fragments of another. + +`pictureDrawing(read)` gives the `Drawing` the picture draws, where each of its entities came +from, the handle of each and the notes. It holds what a `Drawing` cannot, such as a paper tsdraft +does not list, where `toSVG` alone reads it, and it is for pictures and for the checks of text: +`toDXF` of it is not the file. + ## Readers of other formats A package that reads another format names its reader in its `package.json`: diff --git a/src/blocks.ts b/src/blocks.ts index 3f3b952..387c97b 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -847,6 +847,8 @@ function holds(list: readonly unknown[], index: number): boolean { * @param holding - The inserts an entity a referenced drawing holds draws after itself, in that * drawing's coordinates, as a table draws the block of each of its cells. Each is entered as * any insert of that drawing is. + * @param top - Told the index of each entity of the insert's own block or drawing as the walk + * reaches it, before what it draws. * @returns False when `spend` ended the walk. */ export function eachDrawn( @@ -859,6 +861,7 @@ export function eachDrawn( key: (name: string) => string = layerKey, holding?: (entity: Exclude, placement: Placement) => readonly Insert[], heldByBlock?: (from: Referenced | undefined) => ReadonlySet, + top?: (index: number) => void, ): boolean { if (entity.kind !== "insert") { draw(entity, { @@ -945,6 +948,8 @@ export function eachDrawn( if (at.entities) { const item = at.items[at.next++]!; if (!spend(1)) return false; + // Each entity the insert's own block or drawing holds starts with its index. + if (stack.length === 1) top?.(at.next - 1); if (item.kind !== "insert") { const placement: Placement = { matrix: at.matrix, diff --git a/src/index.ts b/src/index.ts index 07c26c9..3da1a48 100644 --- a/src/index.ts +++ b/src/index.ts @@ -488,6 +488,25 @@ export { ReadError } from "./read/groups.ts"; export { layoutMtext, measureMtext } from "./read/mtext.ts"; export { decipherSat, sabEdges, satEdges, type ModelerEdges } from "./read/modeler.ts"; export { edgesInPlan, type PlanEdge } from "./read/plan.ts"; +export { + pictureDrawing, + readPicture, + type PictureDrawing, + type PictureDrawingOptions, + type ReadPicture, + type ReadPictureNotes, + type ReadSvgOptions, + type XrefReads, + type UnderlayPageSizes, +} from "./read/picture.ts"; +export { + joinPicture, + type PictureFragment, + type PicturePiece, + type PictureRun, + type ReadSource, + type ReadSources, +} from "./picture-marks.ts"; export { BLOCK_ITEMS, CENSUS_LIMIT, diff --git a/src/picture-marks.ts b/src/picture-marks.ts new file mode 100644 index 0000000..936e584 --- /dev/null +++ b/src/picture-marks.ts @@ -0,0 +1,131 @@ +// What the picture of a read file gives `toSVG` beside the `Drawing` it draws, under keys no +// `Drawing` holds, so that a drawing made in code draws as it always has. +import type { PaperInfo } from "./papers.ts"; + +/** On a layout: the paper of a read layout, which need not be one of `PAPERS`. */ +export const READ_PAPER: unique symbol = Symbol("tsdraft read paper"); + +/** On an entity: its own linetype scale, group 48, which a `Drawing` does not hold. */ +export const OWN_LINETYPE_SCALE: unique symbol = Symbol("tsdraft own linetype scale"); + +/** On a paragraph: the text of a table's cell, whose words wider than its width break. */ +export const CELL_TEXT: unique symbol = Symbol("tsdraft cell text"); + +/** + * On a drawing: `$PSLTSCALE` is 0, so a viewport sizes dashes in model units, by the linetype scale + * alone, not on the paper. + */ +export const MODEL_DASHES: unique symbol = Symbol("tsdraft model dashes"); + +/** On an image: its fade, from 0 to 100, which mixes it toward the background. */ +export const IMAGE_FADE: unique symbol = Symbol("tsdraft image fade"); + +/** On a layer: its true color as 0xRRGGBB, which a `Drawing`'s layer does not hold. */ +export const LAYER_TRUE_COLOR: unique symbol = Symbol("tsdraft layer true color"); + +/** On the options of `svgPieces`: which top-level entity of the read each entity came from. */ +export const READ_SOURCES: unique symbol = Symbol("tsdraft read sources"); + +/** A layout of a read, with its paper. */ +export interface ReadPaperLayout { + readonly [READ_PAPER]?: PaperInfo; +} + +/** An entity with its own linetype scale. */ +export interface OwnLinetypeScale { + readonly [OWN_LINETYPE_SCALE]?: number; +} + +/** The top-level entity of a read an entity of the drawing was made from. */ +export interface ReadSource { + /** Its index in its space's `entities`. */ + readonly index: number; + readonly handle?: string; +} + +/** For each space of the drawing, the source of each of its top-level entities, by its index. */ +export interface ReadSources { + readonly model: readonly ReadSource[]; + /** By the layout's index in `drawing.layouts`. */ + readonly layouts: readonly (readonly ReadSource[])[]; +} + +/** The picture of one entity at the top of a space, and of what was made from it. */ +export interface PictureFragment { + /** Its entity's index in its space's `entities` in the read. */ + readonly index: number; + readonly handle?: string; + /** Its elements, as the picture joins them. */ + readonly svg?: string; + /** + * For an insert of an xref at the top of a space: in place of `svg`, the xref's run, with a + * fragment for each entity at the top of the xref's model space, whose handles are its file's. + */ + readonly run?: PictureRun; + /** The ids of the definitions it uses, in the order it first uses them. */ + readonly defs: readonly string[]; +} + +/** + * The fragments of one space as the picture draws it: a layout's paper, model space through one + * of its viewports, or model space alone. Joined, they are `open`, each fragment with `between` + * between two, and `close`, or `empty` when there is none. + */ +export interface PictureRun { + readonly kind: "fragments"; + readonly space: "paper" | "model"; + /** + * For model space through a viewport, its index among the viewports the picture draws: those of + * the layout's that are on and have a view, in the layout's order. + */ + readonly viewport?: number; + /** For an xref's run, the block name its insert names. */ + readonly xref?: string; + readonly open: string; + readonly between: string; + readonly close: string; + readonly empty: string; + readonly fragments: readonly PictureFragment[]; +} + +/** A piece of a picture: its own text, a space's fragments, or where the definitions go. */ +export type PicturePiece = string | PictureRun | { readonly kind: "defs" }; + +/** The picture's text from its pieces, with each definition its fragments use, in order. */ +export function joinPicture( + pieces: readonly PicturePiece[], + defs: Readonly>, +): string { + const used: string[] = []; + const seen = new Set(); + const use = (run: PictureRun): void => { + for (const fragment of run.fragments) { + for (const id of fragment.defs) { + if (!seen.has(id) && Object.hasOwn(defs, id)) { + seen.add(id); + used.push(defs[id]!); + } + } + if (fragment.run !== undefined) use(fragment.run); + } + }; + for (const piece of pieces) { + if (typeof piece !== "string" && piece.kind === "fragments") use(piece); + } + const joined = (run: PictureRun): string => + run.fragments.length === 0 + ? run.empty + : run.open + + run.fragments + .map((f) => (f.run !== undefined ? joined(f.run) : (f.svg ?? ""))) + .join(run.between) + + run.close; + let out = ""; + for (const piece of pieces) { + if (typeof piece === "string") out += piece; + else if (piece.kind === "defs") + out += used.length > 0 ? `\n ${used.join("")}` : ""; + else out += joined(piece); + } + return out; +} diff --git a/src/read/picture.ts b/src/read/picture.ts new file mode 100644 index 0000000..4e1d491 --- /dev/null +++ b/src/read/picture.ts @@ -0,0 +1,1515 @@ +// The picture of a read file: a `DrawingRead` as the `Drawing` `toSVG` draws, so that a firm's +// sheet is drawn with the code, the pens and the plot style tables every drawing is drawn with. +// Each kind the readers keep becomes the kinds of a `Drawing` that draw it as the leading CAD app +// does: a dimension and a table their picture's block, a text from where that app starts it, an +// insert's attributes where the file places them. What a read counts and does not keep draws +// nothing, and the notes count it. +import type { XrefDrawings } from "../blocks.ts"; +import { drawnPicture, type PictureParts, type SvgOptions } from "../svg.ts"; +import { checkDrawingRead } from "./check.ts"; +import type { + AttributeDefinition, + Block, + Drawing, + Entity, + HatchPattern, + Image, + Layer, + Layout, + Leader, + LeaderStyle, + Linetype, + LinetypeMark, + Paragraph, + Point, + Text, + TextStyle, + Units, + Viewport, +} from "../drawing.ts"; +import { matchedIndex } from "../colors.ts"; +import { nearestFont, FONTS } from "../fonts.ts"; +import { layerKey } from "../layers.ts"; +import { measureText } from "../measure.ts"; +import { paperInfo, PAPERS, PLOT_STYLE_TABLES, type PaperInfo } from "../papers.ts"; +import { pointStyleOf } from "../points.ts"; +import { imageFrame } from "../images.ts"; +import { leaderPicture } from "../leaders.ts"; +import { LEADER_ATTACHMENTS } from "../rules.ts"; +import { + CELL_TEXT, + IMAGE_FADE, + MODEL_DASHES, + LAYER_TRUE_COLOR, + OWN_LINETYPE_SCALE, + READ_PAPER, + READ_SOURCES, + type PicturePiece, + type ReadSource, + type ReadSources, +} from "../picture-marks.ts"; +import { modelLength } from "../units.ts"; +import type { + DrawingRead, + ReadAttribute, + ReadAttributeParagraph, + ReadEntity, + ReadEntityBase, + ReadHatch, + ReadLayer, + ReadLayout, + ReadMultileader, + ReadTextPlacement, + ReadTextStyle, + ReadViewport, +} from "./model.ts"; +import { edgesInPlan, penOf } from "./plan.ts"; + +/** What the picture of a read file could not draw as the file holds it. */ +export interface ReadPictureNotes { + /** + * Each text style whose font tsdraft does not have, with the font of `FONTS` its texts are + * measured and drawn in, which `nearestFont` picks. + */ + readonly fonts: readonly { + readonly style: string; + readonly font: string; + readonly drawnIn: string; + }[]; + /** + * What draws nothing, counted by kind: what the read counts under a space's `other` or under + * `unread`, and what it keeps and the picture cannot draw, such as a dimension with no block of + * its picture. + */ + readonly notDrawn: Readonly>; + /** What draws only nearly as the leading CAD app draws it, counted by what. */ + readonly approximate: Readonly>; +} + +/** What `pictureDrawing` gives: the drawing, where each of its entities came from, and the notes. */ +export interface PictureDrawing { + readonly drawing: Drawing; + readonly sources: ReadSources; + readonly notes: ReadPictureNotes; + /** + * The handle of the read entity each entity of the drawing was made from, in its spaces and its + * blocks alike, and in the drawings of its xrefs, where the read entity has one: an attribute + * drawn as a text is its attribute's. A handle of an xref's entity is one of the xref's file. + */ + readonly handles: WeakMap; + /** The drawings of the xrefs given, as `toSVG`'s `xrefs` takes them. */ + readonly xrefs: XrefDrawings; +} + +/** What `pictureDrawing` reads beside the read. */ +export interface PictureDrawingOptions { + /** The size in inches of each page the underlays show, by path and page, as `pdfPageSize` reads it. */ + readonly pageSizes?: UnderlayPageSizes; + /** + * The read each xref stands for, by the xref's name, or `{ read, xrefs }` with the reads its + * own attachments stand for. Each is drawn with the states of its layers the host holds as + * `XREF|LAYER`, as the leading CAD app shows it. + */ + readonly xrefs?: XrefReads; +} + +/** The reads xrefs stand for, by the xref's name. */ +export type XrefReads = Readonly< + Record< + string, + | DrawingRead + | { + readonly read: DrawingRead; + readonly xrefs?: XrefReads; + /** The bytes of each raster file its images show, by path, as `SvgOptions.images`. */ + readonly images?: Readonly>; + } + > +>; + +/** The size in inches of each page of the PDF files the read's underlays show, by path and page. */ +export type UnderlayPageSizes = Readonly< + Record>> +>; + +/** What `toSVG` and `readPicture` take to draw a read, as `SvgOptions` and the reads of its xrefs. */ +export interface ReadSvgOptions extends Omit { + /** The read each xref stands for, by the xref's name, drawn with the host's states of its layers. */ + readonly xrefs?: XrefReads; + /** + * The size in inches of each page the underlays show, by path and page, as `pdfPageSize` reads + * it. An underlay whose page's size is not here draws nothing, and the notes say so. + */ + readonly pageSizes?: UnderlayPageSizes; +} + +/** The picture of a read file, what it could not draw as the file holds it, and its pieces. */ +export interface ReadPicture { + readonly svg: string; + readonly notes: ReadPictureNotes; + /** + * The picture in pieces, which `joinPicture` joins into `svg`: its own text, the definitions, + * and for each space it draws one fragment for each entity at the top of the space that shows, + * in the order the leading CAD app draws them. A fragment holds what was made from its entity, + * an insert's attributes among it, and its ids are its own: an edit keeps the fragments of what + * it does not reach and joins them with those it draws again. + */ + readonly pieces: readonly PicturePiece[]; + /** Each definition a fragment uses, such as an image's picture or a gradient, by its id. */ + readonly defs: Readonly>; +} + +/** + * The picture of a read file: what `toSVG` draws of a `DrawingRead` read with `geometry`, with its + * notes and its fragments. A layout is drawn as it plots, with its viewports and at its own plot + * style table where tsdraft has it, and model space as the leading CAD app shows it. Each kind the + * read keeps is drawn as tsdraft draws a `Drawing`'s: a dimension and a table from the block of + * their picture, a multileader from its own points with the arrowheads of `leaderPicture`, a text + * from where that app starts it, and a text in a font tsdraft does not have in the nearest of + * `FONTS`. What the read counts and does not keep draws nothing, and `notes` counts it. + * + * @throws RangeError when `read` is not a `DrawingRead`, as `checkDrawingRead` says, and as + * `toSVG` throws for a drawing. + */ +export function readPicture(read: DrawingRead, options: ReadSvgOptions = {}): ReadPicture { + return readPictureWithin(read, options); +} + +/** `readPicture` with at most `most` entities walked, as `svgWithin` takes it. */ +export function readPictureWithin( + read: DrawingRead, + options: ReadSvgOptions, + most?: number, +): ReadPicture { + const problems = checkDrawingRead(read); + if (problems.length > 0) { + throw new RangeError(`The read is not a DrawingRead: ${problems.slice(0, 3).join("; ")}`); + } + const { xrefs: given, pageSizes, ...rest } = options; + const made = pictureDrawing(read, { + ...(given !== undefined && { xrefs: given }), + ...(pageSizes !== undefined && { pageSizes }), + }); + const parts: PictureParts = {}; + const svg = drawnPicture( + made.drawing, + { ...rest, xrefs: made.xrefs, [READ_SOURCES]: made.sources } as SvgOptions, + parts, + most, + ); + return { svg, notes: made.notes, pieces: parts.pieces ?? [], defs: parts.defs ?? {} }; +} + +const UNITS: Readonly> = { 1: "in", 2: "ft", 4: "mm", 5: "cm", 6: "m" }; + +/** A name no file's name can be, to tell the styles and patterns the picture makes apart. */ +const MADE = "\u0001"; + +/** + * A handle as the readers make one: 1 to 16 hexadecimal digits. Only such a handle keys a map or + * scopes an id; another, which a reader of another format may give, is passed over. + */ +const handleOf = (handle: string | undefined): string | undefined => + handle !== undefined && /^[0-9A-Fa-f]{1,16}$/.test(handle) ? handle : undefined; + +/** The longest value a DXF holds, and so the longest name the readers make. */ +const NAME_MOST = 2049; + +/** + * A name as the maps of a picture key it: `layerKey`'s, and for a name longer than a reader makes, + * one of its length and its start, so that no map is keyed by a string V8 hashes by its length. + */ +const nameKey = (name: string): string => + name.length > NAME_MOST + ? `${MADE}${name.length}${MADE}${layerKey(name.slice(0, 64))}${MADE}${layerKey(name.slice(-64))}` + : layerKey(name); + +/** A name as the picture's drawing holds it: as the file does, or a key for one too long. */ +const drawnName = (name: string): string => (name.length > NAME_MOST ? nameKey(name) : name); + +/** A counter of names, with no prototype, so any name is a key. */ +const counter = (): Record => Object.create(null) as Record; + +/** + * The read as a `Drawing` that `toSVG` draws as the leading CAD app shows the file, with the + * source of each top-level entity, in the order the app draws each space. + */ +export function pictureDrawing( + read: DrawingRead, + options: PictureDrawingOptions = {}, +): PictureDrawing { + return drawingOf(read, options, new WeakMap(), { + made: new WeakMap(), + open: new Set(), + count: 0, + cuts: 0, + }); +} + +/** The xrefs a picture has converted, each once whatever shares it, and those being converted. */ +interface XrefWalk { + readonly made: WeakMap; + readonly open: Set; + count: number; + /** How many cycles the walk has cut. */ + cuts: number; +} + +/** The most xref drawings one picture converts. */ +const XREFS_MADE = 256; + +/** `pictureDrawing`, with the handle of each entity made, its xrefs' among them, in `handles`. */ +function drawingOf( + read: DrawingRead, + options: PictureDrawingOptions, + handles: WeakMap, + walk: XrefWalk, + nested = false, +): PictureDrawing { + const pageSizes = options.pageSizes ?? {}; + const mark = (made: E, handle: string | undefined): E => { + if (handle !== undefined) handles.set(made, handle); + return made; + }; + const notDrawn = counter(); + const approximate = counter(); + const count = (to: Record, what: string, n = 1): void => { + to[what] = (to[what] ?? 0) + n; + }; + for (const [kind, n] of Object.entries(read.unread.entities)) count(notDrawn, kind, n); + + // The text styles, each in the font of `FONTS` nearest its own. + const fonts: { style: string; font: string; drawnIn: string }[] = []; + const readStyles = new Map(); + const textStyles = new Map(); + for (const style of read.textStyles) { + const key = nameKey(style.name); + if (readStyles.has(key)) continue; + readStyles.set(key, style); + const named = style.font !== undefined && style.font !== "" ? style.font : style.family; + const near = + named === undefined || named === "" ? { font: "txt.shx", exact: true } : nearestFont(named); + if (!near.exact) fonts.push({ style: style.name, font: named!, drawnIn: near.font }); + textStyles.set(key, { + name: drawnName(style.name), + font: near.font, + ...(style.widthFactor !== undefined && + style.widthFactor !== 1 && { widthFactor: style.widthFactor }), + ...(style.oblique !== undefined && style.oblique !== 0 && { obliqueAngle: style.oblique }), + }); + } + const fontOf = (style: string): string => textStyles.get(nameKey(style))?.font ?? "txt.shx"; + /** The style a text of its own width factor and slant is drawn in: its own, or one made for it. */ + const styleFor = (style: string, widthFactor = 1, oblique = 0): string => { + const base = textStyles.get(nameKey(style)); + const font = base?.font ?? "txt.shx"; + if ((base?.widthFactor ?? 1) === widthFactor && (base?.obliqueAngle ?? 0) === oblique) { + return base?.name ?? drawnName(style); + } + const name = `${drawnName(style)}${MADE}${widthFactor}${MADE}${oblique}`; + const key = nameKey(name); + if (!textStyles.has(key)) { + textStyles.set(key, { + name, + font, + ...(widthFactor !== 1 && { widthFactor }), + ...(oblique !== 0 && { obliqueAngle: oblique }), + }); + } + return name; + }; + + // The blocks, each by a name of its own: two anonymous records of one name stay apart by handle. + const blockNames = new Map(); + const taken = new Set(); + for (const block of read.blocks) { + let name = drawnName(block.name); + const handle = handleOf(block.handle); + if (taken.has(nameKey(name))) name = `${drawnName(block.name)}${MADE}${handle ?? taken.size}`; + taken.add(nameKey(name)); + if (handle !== undefined) blockNames.set(handle, name); + if (!blockNames.has(`${MADE}${nameKey(block.name)}`)) { + blockNames.set(`${MADE}${nameKey(block.name)}`, name); + } + } + const blockOf = (name: string, handle: string | undefined): string => + (handleOf(handle) !== undefined ? blockNames.get(handle!) : undefined) ?? + blockNames.get(`${MADE}${nameKey(name)}`) ?? + drawnName(name); + + const patterns: HatchPattern[] = []; + const readLayers = new Map(); + for (const layer of read.layers) { + if (!readLayers.has(nameKey(layer.name))) readLayers.set(nameKey(layer.name), layer); + } + const definitions = new Map( + read.images.flatMap((d) => (handleOf(d.handle) === undefined ? [] : [[d.handle!, d] as const])), + ); + /** The blocks the picture makes, beside the file's. */ + const madeBlocks: Block[] = []; + /** The blocks a multileader holds as content, which keep their attribute definitions. */ + const contents = new Map(); + const contentBlock = (name: string): string => { + let made = contents.get(nameKey(name)); + if (made === undefined) + contents.set(nameKey(name), (made = { name, content: `${name}${MADE}content` })); + return made.content; + }; + /** What fits a multileader's block to the file once the blocks are made. */ + const fitted: ((findBlock: (name: string) => Block | undefined) => void)[] = []; + const leaderStyles: LeaderStyle[] = []; + const dimensionStyles = new Map(read.dimensionStyles.map((s) => [nameKey(s.name), s])); + + /** A text of one line as the leading CAD app draws it: from where it starts. */ + const textOf = ( + t: ReadTextPlacement & ReadEntityBase, + value: string, + id: string | undefined, + ): Text | undefined => { + const pen = penOf(t); + let height = t.height; + let widthFactor = t.widthFactor ?? 1; + let rotation = t.rotation; + if ((t.align === "fit" || t.align === "aligned") && t.alignAt !== undefined) { + // Fitted between its two points: wider for `fit`, taller too for `aligned`. + const span = Math.hypot(t.alignAt[0] - t.stored[0], t.alignAt[1] - t.stored[1]); + const natural = measureText({ + value, + height, + font: fontOf(t.style), + widthFactor, + obliqueAngle: t.oblique ?? 0, + }).length; + if (span > 0 && natural > 0) { + rotation = + (Math.atan2(t.alignAt[1] - t.stored[1], t.alignAt[0] - t.stored[0]) * 180) / Math.PI; + if (t.align === "fit") widthFactor *= span / natural; + else height *= span / natural; + } + return { + kind: "text", + ...pen, + ...(id !== undefined && { id }), + at: t.stored, + height, + value, + rotation, + style: styleFor(t.style, widthFactor, t.oblique ?? 0), + }; + } + const style = styleFor(t.style, widthFactor, t.oblique ?? 0); + if (t.startFrom === "alignment" && t.alignAt !== undefined) { + // Its start is not known: it is justified to its alignment point. + count(approximate, "a text justified to its alignment point"); + const middle = t.align === "middle"; + return { + kind: "text", + ...pen, + ...(id !== undefined && { id }), + at: t.alignAt, + height, + value, + rotation, + style, + ...(t.align !== undefined && { + align: middle ? "center" : t.align === "right" ? "right" : "center", + }), + ...(middle + ? { valign: "middle" as const } + : t.valign !== undefined && { valign: t.valign }), + }; + } + return { + kind: "text", + ...pen, + ...(id !== undefined && { id }), + at: t.at, + height, + value, + rotation, + style, + }; + }; + + /** + * A text as `textOf` draws it, and one drawn backward or upside down as the leading CAD app draws + * it: upright in a block of its own, placed mirrored about its start and its baseline. + */ + const drawnText = ( + t: ReadTextPlacement & ReadEntityBase, + value: string, + id: string | undefined, + ): Entity | undefined => { + if (!t.backward && !t.upsideDown) return textOf(t, value, id); + // A text fitted between two points spans them: upright along X from 0 to their distance, its + // insert turned to them, at the first point, or at the second when it runs backward. + const fitted = (t.align === "fit" || t.align === "aligned") && t.alignAt !== undefined; + const span = fitted ? Math.hypot(t.alignAt![0] - t.stored[0], t.alignAt![1] - t.stored[1]) : 0; + const placed = fitted + ? { + at: t.backward ? t.alignAt! : t.stored, + rotation: + (Math.atan2(t.alignAt![1] - t.stored[1], t.alignAt![0] - t.stored[0]) * 180) / Math.PI, + } + : { at: t.at, rotation: t.rotation }; + const upright = textOf( + { + ...t, + at: [0, 0], + stored: [0, 0], + ...(fitted && { alignAt: [span, 0] as Point }), + rotation: 0, + startFrom: "file", + backward: false, + upsideDown: false, + }, + value, + undefined, + ); + if (upright === undefined) return undefined; + const name = `${MADE}mirrored ${madeBlocks.length}`; + madeBlocks.push({ name, entities: [upright] }); + const pen = penOf(t); + return { + kind: "insert", + layer: t.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...(id !== undefined && { id }), + block: name, + at: placed.at, + scale: [t.backward ? -1 : 1, t.upsideDown ? -1 : 1], + rotation: placed.rotation, + }; + }; + + /** Paragraph text, from the point of its box its attachment names. */ + const paragraphOf = ( + p: Pick< + ReadAttributeParagraph, + | "at" + | "height" + | "width" + | "attachment" + | "rotation" + | "style" + | "lineSpacing" + | "lineSpacingStyle" + | "mirrored" + >, + base: ReadEntityBase, + value: string, + id: string | undefined, + extra: Partial> = {}, + ): Entity => { + if (p.mirrored) { + // Seen from below, as a mirrored insert holds it: the paragraph upright in a block of its + // own, placed mirrored, its lines along `rotation` with their tops to their right. + const name = `${MADE}mirrored ${madeBlocks.length}`; + const upright = paragraphOf( + { ...p, at: [0, 0], rotation: 0, mirrored: false }, + base, + value, + undefined, + extra, + ); + madeBlocks.push({ name, entities: [upright] }); + const pen = penOf(base); + return { + kind: "insert", + layer: base.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...(id !== undefined && { id }), + block: name, + at: p.at, + scale: [-1, 1], + rotation: p.rotation - 180, + }; + } + const a = p.attachment >= 1 && p.attachment <= 9 ? p.attachment - 1 : 0; + const align = (["left", "center", "right"] as const)[a % 3]!; + const valign = (["top", "middle", "bottom"] as const)[Math.floor(a / 3)]!; + return { + kind: "paragraph", + ...penOf(base), + ...(id !== undefined && { id }), + at: p.at, + height: p.height, + value, + rotation: p.rotation, + ...(p.width > 0 && { width: p.width }), + style: drawnName(p.style), + ...(align !== "left" && { align }), + ...(valign !== "top" && { valign }), + ...(p.lineSpacing !== 1 && { lineSpacing: p.lineSpacing }), + ...(p.lineSpacingStyle !== "at-least" && { lineSpacingStyle: p.lineSpacingStyle }), + ...extra, + }; + }; + + /** An insert's attributes that show, each where the file places it. */ + const attributesOf = ( + attributes: readonly ReadAttribute[] | undefined, + insert: ReadEntityBase, + ): Entity[] => { + const out: Entity[] = []; + for (const held of attributes ?? []) { + if (held.invisible) continue; + // An attribute on layer 0 draws on its insert's layer, as its block's entities do, and one + // ByBlock in its insert's color. + const { color, trueColor, ...rest } = held; + // ByBlock is the insert's color, and for an insert ByLayer its layer's. + const byBlock = color === 0; + const insertLayer = readLayers.get(nameKey(insert.layer)); + const own = !byBlock + ? { color, trueColor } + : insert.color !== undefined || insert.trueColor !== undefined + ? insert + : { color: insertLayer?.color, trueColor: insertLayer?.trueColor }; + const a: ReadAttribute = { + ...rest, + layer: held.layer === "0" ? insert.layer : held.layer, + ...(own.color !== undefined && own.color !== 0 && { color: own.color }), + ...(own.trueColor !== undefined && { trueColor: own.trueColor }), + }; + if (a.paragraph !== undefined) { + out.push(mark(paragraphOf(a.paragraph, a, a.value, undefined), a.handle)); + } else { + const text = drawnText(a, a.value, undefined); + if (text) out.push(mark(text, a.handle)); + } + } + return out; + }; + + /** A multileader as a leader of a style made for it, from its own points and sizes. */ + const multileaderOf = (e: ReadMultileader, id: string | undefined): Entity | undefined => { + const first = e.roots[0]; + if (first === undefined) { + count(notDrawn, "a multileader with no root"); + return undefined; + } + const vertical = e.vertical === true; + const [dx, dy] = first.direction; + // A vertical multileader's direction runs along X too: 1 for a note above, -1 below. + const ahead = dx !== 0 ? dx >= 0 : dy >= 0; + const side = vertical ? (ahead ? "above" : "below") : ahead ? "right" : "left"; + const along = vertical ? [0, ahead ? 1 : -1] : [ahead ? 1 : -1, 0]; + const content = e.block?.at ?? e.textAt; + const reach = (content[0] - first.at[0]) * along[0]! + (content[1] - first.at[1]) * along[1]!; + const gap = e.block !== undefined ? 0 : Math.max(0, reach - first.landing); + const attachment = (code: number) => LEADER_ATTACHMENTS[code] ?? LEADER_ATTACHMENTS[1]!; + const name = `${MADE}multileader ${leaderStyles.length}`; + const style: LeaderStyle = { + name, + textStyle: drawnName(e.textStyle), + textHeight: e.textHeight, + arrowSize: e.arrowSize, + landing: first.landing, + gap, + attachment: attachment(side === "left" ? e.attachments.right : e.attachments.left), + ...(vertical && { direction: "vertical" as const }), + ...(vertical && { + verticalAttachment: + (side === "above" ? e.attachments.bottom : e.attachments.top) === 10 ? "line" : "center", + }), + ...(e.frame && { frame: true }), + ...(e.shaft === "curved" && { shaft: "curved" as const }), + ...(e.block !== undefined && { + block: contentBlock(blockOf(e.block.name, undefined)), + blockScale: e.block.scale, + }), + }; + if (e.block !== undefined && e.block.rotation !== 0) + count(approximate, "a multileader's block turned"); + const second = e.roots[1]; + const leader: Leader = { + kind: "leader", + ...penOf(e), + ...(id !== undefined && { id }), + style: name, + ...(e.block === undefined && { text: [e.text] }), + ...(e.block?.attributes !== undefined && { attributes: e.block.attributes }), + at: first.at, + shafts: e.shaft === "none" ? [] : first.shafts, + side, + ...(e.width > 0 && { width: e.width }), + ...(e.mask !== undefined && { + mask: { + offsetFactor: e.mask.offsetFactor, + ...(e.mask.color !== undefined && { color: e.mask.color }), + }, + }), + ...(second !== undefined && e.shaft !== "none" && { farShafts: second.shafts }), + }; + // The note goes where the file holds it: placed once, it moves along the landing by how far + // that is from where it was placed. + if (e.block === undefined) { + const placed = leaderPicture(leader, style, textStyles.get(nameKey(e.textStyle))); + const off = + (e.textAt[0] - placed.location[0]) * along[0]! + + (e.textAt[1] - placed.location[1]) * along[1]!; + if (Number.isFinite(off)) leaderStyles.push({ ...style, gap: Math.max(0, gap + off) }); + else leaderStyles.push(style); + } else { + // The block goes where the file holds it, once the blocks are made: by the way it meets + // its landing that puts it nearest, moved along the landing the rest of the way. + const at = leaderStyles.push(style) - 1; + const target = e.block.at; + fitted.push((findBlock) => { + let best: { style: LeaderStyle; miss: number } | undefined; + for (const blockConnection of ["extents", "insertion"] as const) { + const tried = { ...style, blockConnection }; + const placed = leaderPicture(leader, tried, undefined, findBlock).block?.at; + if (placed === undefined) continue; + const off = (target[0] - placed[0]) * along[0]! + (target[1] - placed[1]) * along[1]!; + const moved = { ...tried, gap: Math.max(0, tried.gap + off) }; + const now = leaderPicture(leader, moved, undefined, findBlock).block?.at ?? placed; + const miss = Math.hypot(target[0] - now[0], target[1] - now[1]); + if (Number.isFinite(miss) && (best === undefined || miss < best.miss)) { + best = { style: moved, miss }; + } + } + if (best !== undefined) leaderStyles[at] = best.style; + }); + } + return leader; + }; + + /** Each entity of the kinds of a `Drawing` that draws a read entity, or none, with its handle. */ + const entitiesOf = (e: ReadEntity, id: string | undefined, top: boolean): Entity[] => { + const made = madeOf(e, id, top).map((m) => { + // A name longer than a reader makes is drawn by a short one of the picture's. + const { layer, linetype } = m as { layer: string; linetype?: string }; + if (layer.length <= NAME_MOST && (linetype === undefined || linetype.length <= NAME_MOST)) { + return m; + } + return { + ...m, + layer: drawnName(layer), + ...(linetype !== undefined && { linetype: drawnName(linetype) }), + } as Entity; + }); + if (e.handle !== undefined) for (const m of made) if (!handles.has(m)) handles.set(m, e.handle); + return made; + }; + const madeOf = (e: ReadEntity, id: string | undefined, top: boolean): Entity[] => { + const pen = penOf(e); + const own = (x: Entity): Entity => + e.linetypeScale !== undefined && e.linetypeScale !== 1 + ? Object.assign({ ...x }, { [OWN_LINETYPE_SCALE]: e.linetypeScale }) + : x; + const named = id === undefined ? {} : { id }; + switch (e.kind) { + case "line": + return [own({ kind: "line", ...pen, ...named, from: e.from, to: e.to })]; + case "polyline": + return [ + own({ + kind: "polyline", + ...pen, + ...named, + points: e.points, + closed: e.closed, + ...(e.bulges !== undefined && { bulges: e.bulges }), + ...(e.width !== undefined && { width: e.width }), + ...(e.widths !== undefined && { widths: e.widths }), + ...(e.linetypeGeneration && { linetypeGeneration: true }), + }), + ]; + case "circle": + return [own({ kind: "circle", ...pen, ...named, center: e.center, radius: e.radius })]; + case "arc": + return [ + own({ + kind: "arc", + ...pen, + ...named, + center: e.center, + radius: e.radius, + startAngle: e.start, + endAngle: e.end, + }), + ]; + case "point": + return [ + { + kind: "point", + ...pen, + ...named, + at: e.at, + ...(e.rotation !== undefined && { rotation: e.rotation }), + }, + ]; + case "ellipse": + return [ + own({ + kind: "ellipse", + ...pen, + ...named, + center: e.center, + majorAxis: e.majorAxis, + ratio: e.ratio, + ...(e.startParameter !== undefined && { + startParameter: e.startParameter, + endParameter: e.endParameter, + }), + }), + ]; + case "spline": + if (e.controlPoints.length > 0) { + // Drawn as its knots and points give it: a closed one the file holds repeats its first + // point at its end. + return [ + own({ + kind: "spline", + ...pen, + ...named, + controlPoints: e.controlPoints, + degree: e.degree, + knots: e.knots, + ...(e.weights !== undefined && { weights: e.weights }), + }), + ]; + } + if (e.fitPoints === undefined || e.fitPoints.length < 2) { + count(notDrawn, "a spline with no points"); + return []; + } + return [ + own({ + kind: "spline", + ...pen, + ...named, + fitPoints: e.fitPoints, + ...(e.closed + ? { closed: true } + : { + ...(e.startTangent !== undefined && { startTangent: e.startTangent }), + ...(e.endTangent !== undefined && { endTangent: e.endTangent }), + }), + }), + ]; + case "text": { + const text = drawnText(e, e.value, id); + return text ? [own(text)] : []; + } + case "mtext": + return [ + paragraphOf(e, e, e.value, id, { + ...(e.columns !== undefined && { columns: e.columns }), + ...(e.mask !== undefined && { + mask: + e.mask.color === undefined && e.mask.trueColor === undefined + ? { offsetFactor: e.mask.offsetFactor } + : { + offsetFactor: e.mask.offsetFactor, + // A mask holds an index; a true color's is the nearest index. + color: + e.mask.trueColor !== undefined + ? matchedIndex([ + (e.mask.trueColor >> 16) & 255, + (e.mask.trueColor >> 8) & 255, + e.mask.trueColor & 255, + ]) + : e.mask.color!, + }, + }), + }), + ]; + case "insert": { + const insert: Entity = { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: blockOf(e.block, e.blockHandle), + at: e.at, + scale: e.scale, + rotation: e.rotation, + }; + return [insert, ...attributesOf(e.attributes, e)]; + } + case "dimension": + case "radial-dimension": + case "angular-dimension": + case "ordinate-dimension": + case "arc-length-dimension": + case "table": { + // Drawn as the leading CAD app shows it: the block of its picture. + if (e.block === undefined) { + count(notDrawn, `a ${e.kind} with no block of its picture`); + return []; + } + return [ + { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: blockOf(e.block, e.blockHandle), + // A dimension's block is in the world's coordinates; a table's is turned in the + // world, from its corner. + at: e.kind === "table" ? e.at : [0, 0], + }, + ]; + } + case "multileader": { + const leader = multileaderOf(e, id); + return leader === undefined ? [] : [leader]; + } + case "leader": { + if (e.points.length < 2) { + count(notDrawn, "a leader of fewer than two points"); + return []; + } + const style = dimensionStyles.get(nameKey(e.style)); + const scale = style?.scale !== undefined && style.scale > 0 ? style.scale : 1; + // A leader's arrowhead is its style's DIMLDRBLK, which the read does not keep: the + // default, closed and filled. + const arrowhead = "closed-filled"; + const name = `${MADE}leader ${leaderStyles.length}`; + leaderStyles.push({ + name, + textHeight: 1, + arrowhead, + arrowSize: e.arrowhead ? (style?.arrowSize ?? 0.18) * scale : 0, + landing: 0, + gap: 0, + ...(e.shaft === "curved" && { shaft: "curved" as const }), + }); + return [ + { + kind: "leader", + ...penOf(e), + ...named, + style: name, + at: e.points[e.points.length - 1]!, + shafts: [e.points.slice(0, -1)], + }, + ]; + } + case "solid": + return [ + { + kind: "hatch", + ...pen, + ...named, + loops: [ + { + points: e.points.filter( + (p, i) => i === 0 || p[0] !== e.points[i - 1]![0] || p[1] !== e.points[i - 1]![1], + ), + }, + ], + }, + ]; + case "image": { + const [u, v] = [e.u, e.v]; + const across = Math.hypot(u[0], u[1]); + const up = Math.hypot(v[0], v[1]); + if (!(across > 0 && up > 0)) { + count(notDrawn, "an image of no size"); + return []; + } + // A `Drawing`'s image is square, with its side to the left of its bottom. One the file + // mirrors is drawn as such an image in a block of its own, placed mirrored. + const cross = (u[0] * v[1] - u[1] * v[0]) / (across * up); + const mirrored = cross < 0; + if (Math.abs(Math.abs(cross) - 1) > 1e-9) count(approximate, "an image slanted"); + if ((e.brightness ?? 50) !== 50 || (e.contrast ?? 50) !== 50) + count(approximate, "an image's brightness or contrast"); + const turn = Math.atan2(u[1], u[0]); + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + // From the world into the block: back from `at`, turned back, and mirrored up and down. + const inBlock = (p: Point): Point => { + const [x, y] = [p[0] - e.at[0], p[1] - e.at[1]]; + return [x * cos + y * sin, -(-x * sin + y * cos)]; + }; + const rotation = (turn * 180) / Math.PI; + const image: Image = { + kind: "image", + ...pen, + ...(mirrored ? {} : named), + path: e.path, + pixels: e.pixels, + at: mirrored ? [0, 0] : e.at, + width: across * e.pixels[0], + height: up * e.pixels[1], + ...(!mirrored && rotation !== 0 && { rotation }), + ...(e.clip !== undefined && + !e.unclipped && { clip: mirrored ? e.clip.map(inBlock) : e.clip }), + ...(e.invertClip && { invertClip: true }), + ...(e.transparent && { transparent: true }), + ...(e.fade !== undefined && e.fade > 0 && { [IMAGE_FADE]: e.fade }), + }; + // One the file hides, or whose definition is not loaded, shows its frame alone. + const definition = + handleOf(e.definition) === undefined ? undefined : definitions.get(e.definition!); + const shown: Entity = + e.hidden || definition?.loaded === false + ? { + kind: "polyline", + ...pen, + ...(mirrored ? {} : named), + points: imageFrame(image), + closed: true, + } + : image; + if (!mirrored) return [shown]; + const name = `${MADE}mirrored ${madeBlocks.length}`; + madeBlocks.push({ name, entities: [shown] }); + return [ + { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: name, + at: e.at, + scale: [1, -1], + ...(rotation !== 0 && { rotation }), + }, + ]; + } + case "underlay": { + const size = Object.hasOwn(pageSizes, e.path) + ? Object.hasOwn(pageSizes[e.path]!, e.page) + ? pageSizes[e.path]![e.page] + : undefined + : undefined; + if (size === undefined) { + count(notDrawn, "an underlay whose page's size is not given"); + return []; + } + // A `Drawing`'s underlay has one scale. One the file scales two ways is drawn at its + // first in a block of its own, placed stretched by the second over the first. + const [sx, sy] = e.scale; + const stretched = sx !== sy && sx !== 0 && Number.isFinite(sy / sx); + const turn = (e.rotation * Math.PI) / 180; + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + const inBlock = (p: Point): Point => { + const [x, y] = [p[0] - e.at[0], p[1] - e.at[1]]; + return [x * cos + y * sin, ((-x * sin + y * cos) * sx) / sy]; + }; + const underlay: Entity = { + kind: "underlay", + ...pen, + ...(stretched ? {} : named), + path: e.path, + page: e.page, + pageSize: size, + at: stretched ? [0, 0] : e.at, + scale: sx, + ...(!stretched && e.rotation !== 0 && { rotation: e.rotation }), + ...(e.clip !== undefined && + !e.unclipped && { clip: stretched ? e.clip.map(inBlock) : e.clip }), + ...(e.invertClip && { invertClip: true }), + ...(e.fade !== undefined && { fade: e.fade }), + ...(e.contrast !== undefined && { contrast: e.contrast }), + ...(e.monochrome && { monochrome: true }), + ...(e.hidden && { on: false }), + }; + if (!stretched) return [underlay]; + const name = `${MADE}stretched ${madeBlocks.length}`; + madeBlocks.push({ name, entities: [underlay] }); + return [ + { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: name, + at: e.at, + scale: [1, sy / sx], + ...(e.rotation !== 0 && { rotation: e.rotation }), + }, + ]; + } + case "hatch": + return [own(hatchOf(e, pen, named))]; + case "wipeout": + return [{ kind: "wipeout", ...pen, ...named, points: e.points }]; + case "3dsolid": + case "region": + case "body": + if (e.dataUnread) count(notDrawn, `a ${e.kind} whose data is not read`); + else if (e.edgesUnread) + count(approximate, `the edges of a ${e.kind} not read`, e.edgesUnread); + return edgesInPlan(e).map((edge) => (id === undefined || !top ? edge : { ...edge, id })); + } + }; + + const hatchOf = (e: ReadHatch, pen: ReturnType, named: { id?: string }): Entity => { + // The leading CAD app fills by the parity of the loops its style counts. + const loops = e.loops + .filter((loop) => + e.style === "normal" + ? true + : e.style === "outer" + ? (loop.flags & 17) !== 0 + : (loop.flags & 1) !== 0, + ) + .map((loop) => ({ + points: loop.points, + ...(loop.bulges !== undefined && { bulges: loop.bulges }), + })); + const shown = + loops.length > 0 + ? loops + : e.loops.map((l) => ({ points: l.points, ...(l.bulges && { bulges: l.bulges }) })); + const base = { kind: "hatch" as const, ...pen, ...named, loops: shown }; + if (e.gradient !== undefined) { + const name = e.gradient.name.toUpperCase(); + const inverted = name.startsWith("INV"); + const bare = (inverted ? name.slice(3) : name).toLowerCase(); + const kinds = ["linear", "cylinder", "spherical", "hemispherical", "curved"]; + const kind = kinds.includes(bare) ? bare : "linear"; + if (!kinds.includes(bare)) count(approximate, "a gradient of a name tsdraft does not know"); + const rgb = (n: number) => [(n >> 16) & 255, (n >> 8) & 255, n & 255] as const; + const [a = 0x0000ff, b = 0xffffff] = e.gradient.colors; + return { + ...base, + gradient: { + name: (inverted && kind !== "linear" ? `inverted-${kind}` : kind) as "linear", + ...(e.gradient.angle !== 0 && { angle: e.gradient.angle }), + ...(!e.gradient.centered && { centered: false }), + ...(e.gradient.tint !== undefined && e.gradient.colors.length < 2 + ? { color: rgb(a), tint: e.gradient.tint } + : { colors: [rgb(a), rgb(b)] as const }), + }, + }; + } + if (e.solid || e.patternLines === undefined) return base; + // The lines of its pattern, as the file holds them placed in the world, are the pattern. + const name = `${MADE}pattern ${patterns.length}`; + patterns.push({ + name, + lines: e.patternLines.map((line) => { + const t = (-line.angle * Math.PI) / 180; + const [ox, oy] = line.offset; + return { + angle: line.angle, + base: line.base, + offset: [ + ox * Math.cos(t) - oy * Math.sin(t), + ox * Math.sin(t) + oy * Math.cos(t), + ] as Point, + ...(line.dashes !== undefined && { dashes: line.dashes }), + }; + }), + }); + return { ...base, pattern: { name } }; + }; + + /** A space's entities in the order the leading CAD app draws them, and where each came from. */ + const space = ( + entities: readonly ReadEntity[] | undefined, + order: readonly string[] | undefined, + other: Readonly> | undefined, + ): { entities: Entity[]; sources: ReadSource[] } => { + for (const [kind, n] of Object.entries(other ?? {})) count(notDrawn, kind, n); + const list = entities ?? []; + let indexes = list.map((_, i) => i); + if (order !== undefined && order.length > 0) { + const at = new Map(); + list.forEach((e, i) => { + const handle = handleOf(e.handle); + if (handle !== undefined && !at.has(handle)) at.set(handle, i); + }); + const placed = new Set(); + const sorted: number[] = []; + for (const handle of order) { + const i = handleOf(handle) === undefined ? undefined : at.get(handle); + if (i !== undefined && !placed.has(i)) { + placed.add(i); + sorted.push(i); + } + } + indexes = [...sorted, ...indexes.filter((i) => !placed.has(i))]; + } + const out: Entity[] = []; + const sources: ReadSource[] = []; + for (const i of indexes) { + const e = list[i]!; + const source: ReadSource = { index: i, ...(e.handle !== undefined && { handle: e.handle }) }; + const id = handleOf(e.handle); + for (const made of entitiesOf(e, id, true)) { + out.push(made); + sources.push(source); + } + } + return { entities: out, sources }; + }; + + // The blocks of tables' pictures, whose paragraphs are the text of cells. + const cellBlocks = new Set(); + for (const list of [ + read.model.entities, + ...read.layouts.map((l) => l.entities), + ...read.blocks.map((b) => b.entities), + ]) { + for (const e of list ?? []) { + if (e.kind === "table" && e.block !== undefined) + cellBlocks.add(blockOf(e.block, e.blockHandle)); + } + } + const blocks: Block[] = read.blocks.map((block) => { + const entities: Entity[] = []; + let order = block.entities.map((_, i) => i); + if (block.drawOrder !== undefined && block.drawOrder.length > 0) { + const at = new Map(); + block.entities.forEach((e, i) => { + const handle = handleOf(e.handle); + if (handle !== undefined && !at.has(handle)) at.set(handle, i); + }); + const seen = new Set(); + const sorted: number[] = []; + for (const h of block.drawOrder) { + const i = handleOf(h) === undefined ? undefined : at.get(h); + if (i !== undefined && !seen.has(i)) { + seen.add(i); + sorted.push(i); + } + } + order = [...sorted, ...order.filter((i) => !seen.has(i))]; + } + const cells = cellBlocks.has(blockOf(block.name, block.handle)); + for (const i of order) { + for (const made of entitiesOf(block.entities[i]!, undefined, false)) { + entities.push( + cells && made.kind === "paragraph" ? Object.assign(made, { [CELL_TEXT]: true }) : made, + ); + } + } + for (const [kind, n] of Object.entries(block.other)) count(notDrawn, `${kind} in a block`, n); + // A constant attribute draws in every insert; the others draw as each insert places them. + for (const definition of block.attributeDefinitions) { + if (!definition.constant || definition.invisible) continue; + const value = definition.default ?? ""; + if (definition.paragraph !== undefined) { + entities.push(paragraphOf(definition.paragraph, definition, value, undefined)); + } else { + const text = drawnText(definition, value, undefined); + if (text) entities.push(text); + } + } + return { + name: blockOf(block.name, block.handle), + base: block.base, + entities, + }; + }); + + const model = space(read.model.entities, read.model.drawOrder, read.model.other); + const units = UNITS[read.header.insunits ?? 1] ?? "in"; + const layoutSources: ReadSource[][] = []; + const layouts: Layout[] = read.layouts.map((layout) => { + // A layout the read kept nothing of, as a read without geometry or one by other layouts + // leaves it, is not read, which is not empty. + if (layout.entities === undefined) count(notDrawn, "a layout the read did not read"); + const drawn = space(layout.entities, layout.drawOrder, layout.other); + layoutSources.push(drawn.sources); + return layoutOf(layout, drawn.entities, units, (what) => count(approximate, what)); + }); + // A multileader's block keeps its attribute definitions, whose values the leader sets. + const readBlocks = new Map(read.blocks.map((b) => [blockOf(b.name, b.handle), b])); + const builtBlocks = new Map(blocks.map((b) => [nameKey(b.name), b])); + for (const { name, content } of contents.values()) { + const block = builtBlocks.get(nameKey(name)); + const held = readBlocks.get(name); + if (block === undefined || held === undefined) continue; + const attributes = held.attributeDefinitions + .filter((d) => !d.constant && !d.invisible) + .map((d): AttributeDefinition => { + if (d.paragraph !== undefined) { + const p = paragraphOf(d.paragraph, d, d.default ?? "", undefined); + if (p.kind === "paragraph") { + const { kind: _kind, layer: _layer, value: _value, ...rest } = p; + return { + ...rest, + kind: "paragraph", + tag: d.tag, + value: d.default ?? "", + layer: d.layer, + }; + } + } + const t = textOf(d, d.default ?? "", undefined)!; + return { + tag: d.tag, + value: d.default ?? "", + layer: d.layer, + at: t.at, + height: t.height, + rotation: t.rotation, + ...(t.style !== undefined && { style: t.style }), + ...(t.align !== undefined && { align: t.align }), + ...(t.valign !== undefined && { valign: t.valign }), + }; + }); + madeBlocks.push({ ...block, name: content, attributes }); + } + const allBlocks = new Map([...blocks, ...madeBlocks].map((b) => [nameKey(b.name), b])); + for (const fit of fitted) fit((name) => allBlocks.get(nameKey(name))); + + const layers: Layer[] = read.layers.map((layer) => ({ + name: drawnName(layer.name), + color: layer.color ?? 7, + ...(layer.linetype !== undefined && { linetype: drawnName(layer.linetype) }), + ...(layer.lineweight !== undefined && + layer.lineweight >= 0 && { lineweight: layer.lineweight / 100 }), + ...(!layer.on && { off: true }), + ...(layer.frozen && { frozen: true }), + ...(!layer.plot && { plot: false }), + ...(layer.trueColor !== undefined && { [LAYER_TRUE_COLOR]: layer.trueColor }), + })); + const linetypes: Linetype[] = read.linetypes.map((linetype) => ({ + name: drawnName(linetype.name), + description: linetype.description ?? "", + pattern: linetype.pattern, + ...(linetype.marks !== undefined && { + marks: linetype.marks.map((mark): LinetypeMark => + "text" in mark + ? { + after: mark.after, + ...(mark.rotation !== undefined && { rotation: mark.rotation }), + ...(mark.orient !== undefined && { orient: mark.orient }), + ...(mark.offset !== undefined && { offset: mark.offset }), + text: mark.text, + style: drawnName(mark.style), + height: mark.height, + } + : { + after: mark.after, + ...(mark.rotation !== undefined && { rotation: mark.rotation }), + ...(mark.orient !== undefined && { orient: mark.orient }), + ...(mark.offset !== undefined && { offset: mark.offset }), + shape: mark.shape, + file: mark.file, + scale: mark.scale, + }, + ), + }), + })); + // An xref with no read given draws nothing where it is placed. + for (const xref of read.xrefs) { + if ((!nested || !xref.overlay) && !Object.hasOwn(options.xrefs ?? {}, xref.name)) { + count(notDrawn, "an xref whose drawing is not given"); + } + } + // Each xref given, with its layers as the host holds them. + const xrefs: Record< + string, + | Drawing + | { drawing: Drawing; xrefs?: XrefDrawings; images?: Readonly> } + > = {}; + // An xref's overlays are not loaded where the xref is: only its attachments are drawn. + const listed = new Set( + read.xrefs.filter((x) => !nested || !x.overlay).map((x) => nameKey(x.name)), + ); + for (const [name, given] of Object.entries(options.xrefs ?? {})) { + // Only the xrefs the file lists are drawn, as the leading CAD app loads them. + if (typeof given !== "object" || given === null || !listed.has(nameKey(name))) continue; + const { read: of, xrefs: below } = + "read" in given && + typeof given.read === "object" && + given.read !== null && + "format" in given.read + ? given + : { read: given as DrawingRead, xrefs: undefined }; + // An xref that holds itself draws nothing the second time, as the leading CAD app draws it; + // one many hold is converted once. + if (walk.open.has(given)) { + count(notDrawn, "an xref that holds itself"); + walk.cuts++; + continue; + } + let made = walk.made.get(given); + if (made === undefined) { + if (++walk.count > XREFS_MADE) { + count(notDrawn, "an xref past the most a picture converts"); + continue; + } + walk.open.add(given); + const cuts = walk.cuts; + // An entity of an xref keeps its handle in the xref's file. + made = drawingOf( + of, + { pageSizes, ...(below !== undefined && { xrefs: below }) }, + handles, + walk, + true, + ); + walk.open.delete(given); + // One that cut a cycle is drawn again where it is reached another way. + if (walk.cuts === cuts) walk.made.set(given, made); + } + // What the xref's picture could not draw is the host's to say. + for (const [what, n] of Object.entries(made.notes.notDrawn)) count(notDrawn, what, n); + for (const [what, n] of Object.entries(made.notes.approximate)) count(approximate, what, n); + for (const font of made.notes.fonts) { + if (!fonts.some((f) => f.style === font.style && f.font === font.font)) fonts.push(font); + } + const prefix = nameKey(`${name}|`); + const host = new Map(); + for (const layer of read.layers) { + const key = nameKey(layer.name); + if (key.startsWith(prefix)) host.set(key.slice(prefix.length), layer); + } + const layered: Drawing = { + ...made.drawing, + layers: made.drawing.layers.map((layer) => { + const held = host.get(nameKey(layer.name)); + if (held === undefined) return layer; + const { off: _off, frozen: _frozen, plot: _plot, ...rest } = layer; + // The host's color wins, its true color with it. + const trueColor = + held.color !== undefined || held.trueColor !== undefined + ? held.trueColor + : (layer as { [LAYER_TRUE_COLOR]?: number })[LAYER_TRUE_COLOR]; + return { + ...rest, + [LAYER_TRUE_COLOR]: trueColor, + color: held.color ?? layer.color, + ...(held.linetype !== undefined && { linetype: held.linetype.replace(/^.*\|/, "") }), + ...(held.lineweight !== undefined && + held.lineweight >= 0 && { lineweight: held.lineweight / 100 }), + ...(!held.on && { off: true }), + ...(held.frozen && { frozen: true }), + ...(!held.plot && { plot: false }), + }; + }), + }; + // Its sources go with it, so its picture keeps a fragment for each of its entities. + Object.assign(layered, { [READ_SOURCES]: made.sources }); + const images = "read" in given && "images" in given ? given.images : undefined; + xrefs[drawnName(name)] = + Object.keys(made.xrefs).length > 0 || images !== undefined + ? { + drawing: layered, + ...(Object.keys(made.xrefs).length > 0 && { xrefs: made.xrefs }), + ...(images !== undefined && { images }), + } + : layered; + } + const header = read.header; + const drawing: Drawing = { + format: 0, + units, + dxf: "R2018", + layers, + entities: model.entities, + linetypes, + ...(header.ltscale !== undefined && { linetypeScale: header.ltscale }), + textStyles: [...textStyles.values()], + blocks: [...blocks, ...madeBlocks], + xrefs: read.xrefs.map((x) => ({ name: drawnName(x.name), path: x.path, attach: !x.overlay })), + layouts, + leaderStyles, + patterns, + ...(read.underlayFrame !== undefined && { underlayFrame: read.underlayFrame }), + ...(header.wipeoutFrame !== undefined && { wipeoutFrame: header.wipeoutFrame !== 0 }), + ...((header.pdmode !== undefined || header.pdsize !== undefined) && { + pointStyle: pointStyleOf(header.pdmode, header.pdsize), + }), + ...(header.psltscale === 0 && { [MODEL_DASHES]: true }), + }; + return { + drawing, + sources: { model: model.sources, layouts: layoutSources }, + notes: { fonts, notDrawn, approximate }, + handles, + xrefs, + }; +} + +/** A read layout as a `Drawing`'s, on its own paper. */ +function layoutOf( + layout: ReadLayout, + entities: Entity[], + units: Units, + approximate: (what: string) => void, +): Layout { + const paper = paperOf(layout); + const viewports = layout.viewports + .filter((v) => v.on) + .flatMap((v): Viewport[] => { + if (v.turnedView) { + approximate("a viewport that looks along another direction"); + } + const view = viewportOf(v, paper, units); + return view === undefined ? [] : [view]; + }); + const table = + layout.plotStyleTable === undefined || layout.plotStyleTable === "" + ? "acad.ctb" + : PLOT_STYLE_TABLES.find((t) => t.toLowerCase() === layout.plotStyleTable!.toLowerCase()); + if (table === undefined) approximate("a plot style table tsdraft does not have"); + return { + name: layout.name, + paper: paper.name, + plotStyle: table ?? "monochrome.ctb", + viewports, + entities, + [READ_PAPER]: paper.info, + } as Layout; +} + +/** The paper of a read layout: one of `PAPERS` where its media is one's, else its own size. */ +function paperOf(layout: ReadLayout): { name: string; info: PaperInfo } { + const units = layout.paperUnits === 1 ? "mm" : "in"; + // A paper of `PAPERS` where the page setup names its media in its units. + const known = Object.entries(PAPERS).find( + ([, info]) => info.media === layout.media && info.units === units, + ); + if (known !== undefined) return { name: known[0], info: paperInfo(known[0])! }; + const [w, h] = layout.paperSize ?? [279.4, 215.9]; + const per = units === "mm" ? 1 : 1 / 25.4; + const turned = layout.plotRotation % 2 === 1; + const [width, height] = turned ? [h * per, w * per] : [w * per, h * per]; + return { + name: layout.media ?? "", + info: { + media: layout.media ?? "", + units, + width, + height, + medium: { width: w * per, height: h * per, rotation: turned ? 1 : 0 }, + printable: [0, 0, width, height], + }, + }; +} + +/** A read viewport as a `Drawing`'s: its ratio in model units to a paper unit. */ +function viewportOf( + v: ReadViewport, + paper: { info: PaperInfo }, + units: Units, +): Viewport | undefined { + if (!(v.ratio > 0) || !(v.width > 0) || !(v.height > 0)) return undefined; + // `modelLength` is in proportion to the ratio, so one unit of ratio gives the factor. + const one = modelLength(v.height, paper.info.units, 1, units); + if (!(one > 0)) return undefined; + const ratio = v.height / v.ratio / one; + const twist = ((v.twist % 360) + 360) % 360; + return { + ...(v.handle !== undefined && { id: `vp${v.handle}` }), + layer: drawnName(v.layer), + corner: [v.center[0] - v.width / 2, v.center[1] - v.height / 2], + width: v.width, + height: v.height, + center: v.viewCenter, + ratio, + ...(v.frozenLayers.length > 0 && { frozenLayers: v.frozenLayers.map(drawnName) }), + ...(twist !== 0 && { twist: twist > 180 ? twist - 360 : twist }), + }; +} + +/** True for a font of `FONTS`. */ +export const isKnownFont = (font: string): boolean => Object.hasOwn(FONTS, font); diff --git a/src/read/plan.ts b/src/read/plan.ts index c3134c2..727dd70 100644 --- a/src/read/plan.ts +++ b/src/read/plan.ts @@ -12,7 +12,13 @@ import type { } from "../drawing.ts"; import { written } from "../format.ts"; import { SPLINE_DEGREE_MOST } from "../rules.ts"; -import type { Point3, ReadEdge, ReadEdgeEllipse, ReadModelerGeometry } from "./model.ts"; +import type { + Point3, + ReadEdge, + ReadEdgeEllipse, + ReadEntityBase, + ReadModelerGeometry, +} from "./model.ts"; /** What `edgesInPlan` gives for an edge. */ export type PlanEdge = Line | Circle | Arc | Ellipse | ControlSpline; @@ -29,8 +35,8 @@ const toDegrees = (r: number): number => { return turned >= 360 ? 0 : turned; }; -/** The pen the solid sets for itself, as a drawing's entity holds it. */ -function penOf(s: ReadModelerGeometry): { +/** The pen a read entity sets for itself, as a drawing's entity holds it. */ +export function penOf(s: ReadEntityBase): { layer: string; color?: EntityColor; transparency?: EntityTransparency; diff --git a/src/svg.ts b/src/svg.ts index caa2062..04dee15 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -168,6 +168,26 @@ import { ellipsePoint, splinePieces, splinePolyline, unturned } from "./curves.t import { filled, KEYED } from "./shape.ts"; import { shapeFinder, type ShapeDefinition, type ShapeFiles } from "./shapes.ts"; import { isUnits } from "./units.ts"; +import { + CELL_TEXT, + IMAGE_FADE, + MODEL_DASHES, + LAYER_TRUE_COLOR, + OWN_LINETYPE_SCALE, + READ_PAPER, + READ_SOURCES, + type OwnLinetypeScale, + type PictureFragment, + type PicturePiece, + type PictureRun, + joinPicture, + type ReadPaperLayout, + type ReadSource, + type ReadSources, +} from "./picture-marks.ts"; +import { sha256Text } from "./sha256.ts"; +import type { DrawingRead } from "./read/model.ts"; +import { readPicture, type ReadSvgOptions } from "./read/picture.ts"; /** * ACI, the color index CAD programs share: the color the leading CAD app plots each index in, from @@ -385,6 +405,43 @@ export interface SvgOptions { readonly plotTransparency?: boolean; } +/** Where the fragments of a space of a read file's picture go, and where each entity came from. */ +interface Run { + readonly sources: readonly ReadSource[]; + readonly viewport?: number; + readonly fragments: PictureFragment[]; +} + +/** + * What the ids a fragment makes start from: its entity's handle, where it is one the readers make + * and the first of the space to have it, and else its index, so no two fragments share one and no + * id holds a character markup would read. + */ +function scopeName(source: ReadSource, scoped: Set): string { + const { handle } = source; + if (handle === undefined || !/^[0-9A-Fa-f]{1,16}$/.test(handle)) return `e${source.index}`; + const key = handle.toUpperCase(); + if (scoped.has(key)) return `e${source.index}`; + scoped.add(key); + return `h${handle}`; +} + +/** A run of fragments as it is filled. */ +interface MutableRun extends Run { + readonly kind: "fragments"; + readonly space: "paper" | "model"; + open: string; + between: string; + close: string; + empty: string; +} + +/** The pieces of a read file's picture, and its definitions by id, as `svgWithin` made them. */ +export interface PictureParts { + pieces?: readonly PicturePiece[]; + defs?: Readonly>; +} + /** How an entity is drawn. */ interface Pen { readonly color: string; @@ -689,6 +746,13 @@ function planOf(e: Polyline, known: Known): Plan | undefined { return plan; } +/** + * The picture of a read file, as `readPicture` draws it: the sheet as it plots, or model space, + * as the leading CAD app shows the file. + * + * @throws RangeError as for a drawing, and when `read` is not a `DrawingRead`. + */ +export function toSVG(read: DrawingRead, options?: ReadSvgOptions): string; /** * Renders a preview SVG of the drawing as it plots. Model Y points up, so the drawing group * flips Y. Entities on layers that are off, frozen or set not to plot are left out, and each @@ -748,12 +812,40 @@ function planOf(e: Polyline, known: Known): Plan | undefined { * Its message names the entity or the viewport it stopped at. Draw a part of such a drawing * with `options.view`. */ -export function toSVG(drawing: Drawing, options: SvgOptions = {}): string { - return svgWithin(drawing, options, MAX_WALKED); +export function toSVG(drawing: Drawing, options?: SvgOptions): string; +export function toSVG( + drawing: Drawing | DrawingRead, + options: SvgOptions | ReadSvgOptions = {}, +): string { + if (isDrawingRead(drawing)) return readPicture(drawing, options as ReadSvgOptions).svg; + return svgWithin(drawing, options as SvgOptions, MAX_WALKED); +} + +/** A picture of a drawing `toSVG` draws in full, with its pieces kept in `parts`. */ +export function drawnPicture( + drawing: Drawing, + options: SvgOptions, + parts: PictureParts, + most = MAX_WALKED, +): string { + return svgWithin(drawing, options, most, parts); +} + +/** True for a read, which a `Drawing` is not: it holds the SHA-256 of its file, and no `entities`. */ +function isDrawingRead(value: Drawing | DrawingRead): value is DrawingRead { + return ( + typeof (value as Partial).sha256 === "string" && + !Array.isArray((value as Partial).entities) + ); } /** `toSVG` with `most` entities walked, and `most` times `CHARACTERS` characters written. */ -export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): string { +export function svgWithin( + drawing: Drawing, + options: SvgOptions, + most: number, + collected?: PictureParts, +): string { const xrefs = referencedByKey(drawing, options.xrefs); const { tablesOf, layerOf, hidden, frozen, styleOf, key } = visibility( drawing, @@ -907,6 +999,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): readonly info: RasterInfo; /** False for a file the plot cannot draw, which the picture draws as a file not given. */ readonly plotted: boolean; + /** The files it was given in. */ + readonly given: object; /** Its pixels as they are, and with any transparency left out; null for one not read. */ shown?: string | null; opaque?: string | null; @@ -917,14 +1011,37 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): /** Whether each clip an image gives can be drawn, read once however many images share it. */ const clipsChecked = new WeakMap(); const defs: string[] = []; + /** The id of each of `defs`. */ + const defIds: string[] = []; let clips = 0; let gradients = 0; + // A read file's picture is kept as one fragment for each entity at the top of a space, so the + // ids an entity makes start from where it is, and an image's from its file, and stay the same + // whatever is drawn around it. + const reading: ReadSources | undefined = (options as { [READ_SOURCES]?: ReadSources })[ + READ_SOURCES + ]; + let scope = ""; + /** The ids of the definitions the fragment being drawn uses. */ + let using: Set | undefined; + const define = (id: string, def: string): void => { + defs.push(def); + defIds.push(id); + }; + /** The id of a file's picture, from what it is and the files it was given in. */ + const givenIndex = new WeakMap(); + let givens = 0; + const fileId = (given: object, what: string): string => { + let at = givenIndex.get(given); + if (at === undefined) givenIndex.set(given, (at = givens++)); + return sha256Text(`${at}\u0000${what}`).slice(0, 16); + }; /** * The id of a gradient's picture where `matrix` puts it, held in the definitions, or undefined * when the picture has no room for it. */ const shade = (picture: GradientPicture, matrix: Matrix | undefined): string | undefined => { - const id = `tsdraft-gradient-${gradients++}`; + const id = `tsdraft-gradient-${scope}${gradients++}`; const frame = (matrix ? compose(matrix, picture.frame) : picture.frame).map(precise).join(" "); const stops = picture.stops .map(({ offset, color }) => ``) @@ -935,7 +1052,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): : `radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"`; const def = `<${shape} spreadMethod="pad" gradientTransform="matrix(${frame})">${stops}`; if (!write(def.length)) return undefined; - defs.push(def); + define(id, def); + using?.add(id); return id; }; /** @@ -957,7 +1075,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const plotted = info !== undefined && (info.kind !== "png" || !plotDecodes(info) || info.width * info.height <= RASTER_PIXELS); - found = info === undefined ? null : { bytes: bytes!, info, plotted }; + found = info === undefined ? null : { bytes: bytes!, info, plotted, given }; held.set(key, found); } // Every image of a file is held to its pixels, whichever drawing it is in. @@ -980,19 +1098,26 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const { info } = raster; const copy = opaque && hasAlpha(info) && !markedOpaque(info); const known = copy ? raster.opaque : raster.shown; - if (known !== undefined) return known; + if (known !== undefined) { + if (known !== null) using?.add(known); + return known; + } let bytes: Uint8Array | undefined = raster.bytes; if (info.kind === "jpeg") bytes = withoutExif(bytes); else if (copy && info.kind === "png") bytes = opaquePng(info, bytes); let id: string | null = null; if (bytes !== undefined) { - id = `tsdraft-image-${rastersHeld++}`; + id = + reading === undefined + ? `tsdraft-image-${rastersHeld++}` + : `tsdraft-image-${fileId(raster.given, `${copy ? "opaque" : "shown"}\u0000${path}`)}`; const kind = info.kind === "png" ? "image/png" : "image/jpeg"; const head = ``); + define(id, `${head}${base64(bytes)}"/>`); + using?.add(id); } if (copy) raster.opaque = id; else raster.shown = id; @@ -1031,16 +1156,24 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): .join(" "); // A file too large to hold again is the file, which the plot shows opaque. const marked = e.transparent !== true && markedOpaque(raster!.info); + // A read file's image fades toward the background as the leading CAD app fades it. + const fade = (e as { readonly [IMAGE_FADE]?: number })[IMAGE_FADE]; const use = ``; - if (e.clip === undefined) parts.push(use); + // Faded in a group of its own, outside any clip, as an entity's transparency is, which the + // plot draws too. + const alpha = + typeof fade === "number" && fade > 0 && fade <= 100 + ? Math.round(255 * (1 - fade / 100)) + : 255; + if (e.clip === undefined) parts.push(fadedGroup(use, alpha)); else { - const id = `tsdraft-image-clip-${clips++}`; + const id = `tsdraft-image-clip-${scope}${clips++}`; const outline = ring(imageFrame(e)); const d = e.invertClip ? `${ring(imageCorners(e))} ${outline}` : outline; const rule = e.invertClip ? ` clip-rule="evenodd"` : ""; parts.push( ``, - `${use}`, + fadedGroup(`${use}`, alpha), ); } } else { @@ -1107,7 +1240,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ); } const known = held.get(key); - if (known !== undefined) return known; + if (known !== undefined) { + if (known !== null) using?.add(known); + return known; + } let id: string | null = null; if (info !== undefined && info.kind === "png" && info.width * info.height <= RASTER_PIXELS) { let png: Uint8Array | undefined = bytes; @@ -1139,11 +1275,15 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): } } if (png !== undefined) { - id = `tsdraft-image-${rastersHeld++}`; + id = + reading === undefined + ? `tsdraft-image-${rastersHeld++}` + : `tsdraft-image-${fileId(given, `page\u0000${pageOf(e)}\u0000${key}\u0000${e.path}`)}`; const head = ``); + define(id, `${head}${base64(png)}"/>`); + using?.add(id); } } held.set(key, id); @@ -1181,7 +1321,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const use = ``; if (e.clip === undefined) parts.push(use); else { - const id = `tsdraft-image-clip-${clips++}`; + const id = `tsdraft-image-clip-${scope}${clips++}`; const outline = ring(underlayFrame(e)); const d = e.invertClip ? `${ring(underlayCorners(e))} ${outline}` : outline; const rule = e.invertClip ? ` clip-rule="evenodd"` : ""; @@ -1227,7 +1367,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const room = longest - length; if (e.kind === "paragraph") { const style = styleOf(e, from); - const layout = () => paragraphs.layout(paragraphInStyle(e, style)); + // A table's cell in a read file's picture breaks a word wider than its width. + const layout = (e as { readonly [CELL_TEXT]?: true })[CELL_TEXT] + ? () => layoutCellText(paragraphInStyle(e, style)) + : () => paragraphs.layout(paragraphInStyle(e, style)); return paragraphToSvg(e, layout, mark, drawnPen, look, matrix, room); } if (e.kind === "leader") { @@ -1439,13 +1582,13 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): byBlock?: BlockColor, ): Pen => { const layer: Layer | undefined = layerOf(on); - const byLayer = layer?.color ?? 7; + const byLayer = layerShade(layer); const blockShade = byBlock === undefined ? 7 : "color" in byBlock ? byBlock.color - : (layerOf(byBlock.layer)?.color ?? 7); + : layerShade(layerOf(byBlock.layer)); const own: unknown = e.color; const shade = own === "ByBlock" ? blockShade : typeof own === "number" || isRgb(own) ? own : byLayer; @@ -1476,6 +1619,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ? (e.lineweight ?? "Default") : (weightFrom.layer?.lineweight ?? "Default"); const code = lineweightCode(weight); + // A read entity's own linetype scale, which a `Drawing` does not hold. + const scaled = (e as OwnLinetypeScale)[OWN_LINETYPE_SCALE]; + const ownScale = + typeof scaled === "number" && scaled > 0 && Number.isFinite(scaled) ? scaled : 1; return { color: drawnColor(look, shade), byLayer: drawnColor(look, byLayer), @@ -1483,12 +1630,12 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // A pattern keeps its length whatever size an insert draws its entity at, so it is cut in // the block's own units shrunk by the insert's scale. dashes: - pattern && Number.isFinite(look.dashScale / placed) && placed > 0 + pattern && Number.isFinite((look.dashScale * ownScale) / placed) && placed > 0 ? dashesOf( pattern, - look.dashScale / placed, + (look.dashScale * ownScale) / placed, where, - look.dashScale, + look.dashScale * ownScale, tablesOf(named).textStyles, ) : undefined, @@ -1547,13 +1694,53 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): look: Look, space: string, frozenHere?: (layer: LayerRef) => boolean, + run?: Run, ): string[] => { // A layer frozen in a viewport is frozen there for the walk of an insert too. const isFrozen = frozenHere ? (ref: LayerRef) => frozen(ref) || frozenHere(ref) : frozen; const marks = (e: Entity, index: number): string => `data-layer="${esc(e.layer)}" data-entity="${index}"${e.id === undefined ? "" : ` data-id="${esc(e.id)}"`}`; const line = look.indent.length + 1; - return shown.map(([i, e]) => { + /** The run of the xref the last insert drawn places, for a read's picture. */ + let nested: PictureRun | undefined; + if (run === undefined) return shown.map(draw); + // The elements made from one entity of the read are one fragment, its ids its own. + const out: string[] = []; + let open: + | { source: ReadSource; parts: string[]; uses: Set; nested?: PictureRun } + | undefined; + const close = (): void => { + if (open === undefined) return; + const { source, parts, uses, nested: within } = open; + run.fragments.push({ + index: source.index, + ...(source.handle !== undefined && { handle: source.handle }), + ...(within !== undefined && parts.length === 1 + ? { run: within } + : { svg: parts.join(`\n${look.indent}`) }), + defs: [...uses], + }); + }; + const scoped = new Set(); + for (const item of shown) { + const source = run.sources[item[0]] ?? { index: item[0] }; + if (open?.source !== source) { + close(); + open = { source, parts: [], uses: new Set() }; + const name = scopeName(source, scoped); + scope = `${run.viewport === undefined ? "" : `v${run.viewport}-`}${name}-`; + [gradients, clips, using] = [0, 0, open.uses]; + } + const element = draw(item); + open!.parts.push(element); + if (nested !== undefined) [open!.nested, nested] = [nested, undefined]; + out.push(element); + } + close(); + [scope, using] = ["", undefined]; + return out; + + function draw([i, e]: readonly [number, Entity]): string { const where = () => entityAt(i, e, space); drawingAt = where; if (e.kind !== "insert") { @@ -1576,6 +1763,27 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // which holds no more than its characters, with what joins them as the group joins them. const joined: string[] = []; let parts: string[] = []; + // An xref of a read's picture is a run of its own: a fragment for each entity of its model + // space, each with its ids, so an edit of the xref's file draws only what it changes. + const referenced = + run === undefined || blocks.has(key(e.block)) ? undefined : xrefs.get(key(e.block)); + const xrefSources = (referenced?.drawing as { readonly [READ_SOURCES]?: ReadSources })?.[ + READ_SOURCES + ]?.model; + const subs: { source: ReadSource; parts: string[]; uses: Set }[] = []; + const xrefScoped = new Set(); + const outer = { scope, using, gradients, clips }; + const top = + xrefSources === undefined + ? undefined + : (index: number): void => { + const source = xrefSources[index] ?? { index }; + if (subs.at(-1)?.source === source) return; + const name = scopeName(source, xrefScoped); + scope = `${outer.scope}x${name}-`; + [gradients, clips, using] = [0, 0, new Set()]; + subs.push({ source, parts: [], uses: using }); + }; const walked = eachDrawn( e, blocks, @@ -1607,7 +1815,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ); if (!write(part.length + line + 2)) return; parts.push(part); - if (parts.length === JOINED) { + if (top !== undefined) subs.at(-1)?.parts.push(part); + else if (parts.length === JOINED) { joined.push(parts.join(between)); parts = []; } @@ -1627,7 +1836,9 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): return tableInserts(held, picture); }, leaderHeld, + top, ); + if (top !== undefined) ({ scope, using, gradients, clips } = outer); if (!walked || length > longest) refuse(where()); const xref = blocks.has(key(e.block)) ? undefined : xrefPaths.get(key(e.block)); // Its names are read for each insert, so they are paid for before they are written. @@ -1638,8 +1849,28 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const all = parts.length > 0 ? [...joined, parts.join(between)] : joined; if (!write(open.length - names + 4 + line + (all.length > 0 ? line : 0))) refuse(where()); const inside = all.length > 0 ? `${between}${all.join(between)}\n${look.indent}` : ""; + if (top !== undefined) { + nested = { + kind: "fragments", + space: "model", + ...(run!.viewport !== undefined && { viewport: run!.viewport }), + xref: e.block, + open: `${open}${between}`, + between, + close: `\n${look.indent}`, + empty: `${open}`, + fragments: subs + .filter((sub) => sub.parts.length > 0) + .map((sub) => ({ + index: sub.source.index, + ...(sub.source.handle !== undefined && { handle: sub.source.handle }), + svg: sub.parts.join(between), + defs: [...sub.uses], + })), + }; + } return `${open}${inside}`; - }); + } }; /** @@ -1715,9 +1946,49 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): drawing.pointStyle !== undefined && pointStyleProblems(drawing.pointStyle).length === 0 ? drawing.pointStyle : { figure: "dot" }; + /** The runs of fragments of a read's picture, in the order they are drawn. */ + const runs: MutableRun[] = []; + const newRun = (space: "paper" | "model", sources: readonly ReadSource[], viewport?: number) => { + const run: MutableRun = { + kind: "fragments", + space, + ...(viewport !== undefined && { viewport }), + sources, + open: "", + between: "\n ", + close: "", + empty: "", + fragments: [], + }; + runs.push(run); + return run; + }; + const modelRun = (viewport: number): MutableRun | undefined => + reading === undefined ? undefined : newRun("model", reading.model, viewport); + /** Where the definitions go: written out, or for a read, worked out from its fragments. */ + const defsPiece = (): PicturePiece => + reading !== undefined + ? { kind: "defs" } + : defs.length > 0 + ? `\n ${defs.join("")}` + : ""; + const finish = (pieces: PicturePiece[]): string => { + const shaped = pieces.map((piece): PicturePiece => { + if (typeof piece === "string" || piece.kind !== "fragments") return piece; + const { sources: _sources, ...rest } = piece as MutableRun; + return rest; + }); + const held: Record = Object.create(null) as Record; + defIds.forEach((id, i) => (held[id] = defs[i]!)); + if (collected !== undefined) { + collected.pieces = shaped; + collected.defs = held; + } + return joinPicture(shaped, held); + }; if (options.layout !== undefined) { const layout = findLayout(drawing, options.layout); - const paper = layout && paperInfo(layout.paper); + const paper = layout && ((layout as ReadPaperLayout)[READ_PAPER] ?? paperInfo(layout.paper)); if (!layout || !paper) { throw new RangeError(`The drawing has no layout named ${JSON.stringify(options.layout)}`); } @@ -1730,9 +2001,11 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // Hundredths of a millimetre in paper units. const perHundredth = paper.units === "in" ? 1 / 2540 : 1 / 100; /** A look whose lines are as wide as they plot, in a space `scale` paper units to one. */ + // A read file whose $PSLTSCALE is 0 sizes a viewport's dashes in model units. + const modelDashes = (drawing as { readonly [MODEL_DASHES]?: true })[MODEL_DASHES] === true; const plotted = (scale: number, indent: string, points: PointLook): Look => ({ color, - dashScale: linetypeScale / scale, + dashScale: modelDashes ? linetypeScale : linetypeScale / scale, chord: (paper.units === "in" ? 1 : 25.4) / 1200 / scale, indent, points, @@ -1758,8 +2031,9 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): written(top - bottom + margin * 2), ] as const; const picture = [frame[0], -(frame[1] + frame[3]), frame[0] + frame[2], -frame[1]] as const; - const parts: string[] = []; + const parts: (string | PictureRun)[] = []; const space = `layout ${quoted(layout.name)}`; + const layoutSources = reading?.layouts[filled(drawing.layouts).indexOf(layout)]; /** Keeps a part of the sheet, each on a line of its own set in by four spaces. */ const keep = (where: string, part: string): void => { if (!write(part.length + 5)) refuse(where); @@ -1808,12 +2082,14 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const [cx, cy] = view.displayCenter; const turn = view.twist === 0 ? "" : ` rotate(${fmt(view.twist)})`; const place = `translate(${fmt(view.paperCenter[0])} ${fmt(view.paperCenter[1])}) scale(${precise(view.scale)}) translate(${fmt(-cx)} ${fmt(-cy)})${turn}`; - // The layers frozen in this viewport alone, which an entity of the drawing's own is on. + // The layers frozen in this viewport alone: the drawing's own, and an xref's by the name the + // drawing holds it by, the xref's name, a bar and the layer's. const frozenKeys = new Set(filled(viewport.frozenLayers ?? []).map(key)); const frozenHere = frozenKeys.size === 0 ? undefined - : (ref: LayerRef) => ref.of === undefined && frozenKeys.has(key(ref.name)); + : (ref: LayerRef) => + frozenKeys.has(key(ref.of === undefined ? ref.name : `${ref.of.name}|${ref.name}`)); // A view is drawn only where it can be seen: the viewport, cut to the paper, cut to // the picture, with every number as it is written. The clip, the hidden rectangle and // the choice of what to draw all use this one rectangle. @@ -1862,8 +2138,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): }), `model space in ${at}`, frozenHere, + modelRun(index), ); - if (inside.length === 0) { + const shownRun = runs.at(-1); + if (inside.length === 0 && (shownRun === undefined || !visible)) { // Nothing of the view can be seen, so there is nothing to clip. keep(at, ``); } else { @@ -1873,7 +2151,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // clips them, and stops the program that runs it when that box lies wholly more than // two widths of the picture to its left or right, or two heights above or below it. const rect = `x="${seen[0]}" y="${seen[1]}" width="${seenWidth}" height="${seenHeight}"`; - keep(at, ``); + const clip = ``; + if (!write(clip.length + 5)) refuse(at); // Its elements were counted as they were made. const head = [ ``, @@ -1882,7 +2161,18 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ]; const tail = [` `, ` `]; if (!write([...head, ...tail].join("\n").length + 6)) refuse(at); - parts.push([...head, ...inside.map((element) => ` ${element}`), ...tail].join("\n")); + if (shownRun === undefined) { + parts.push(clip); + parts.push( + [...head, ...inside.map((element) => ` ${element}`), ...tail].join("\n"), + ); + } else { + // A view nothing of a read shows in is a group of its own, which an edit can fill. + shownRun.open = `\n ${clip}\n ${head.join("\n")}\n `; + shownRun.close = `\n${tail.join("\n")}`; + shownRun.empty = `\n `; + parts.push(shownRun); + } } // The leading CAD app plots a viewport's border as its thinnest line, and only when its layer plots. if (!hidden({ name: viewport.layer })) { @@ -1894,7 +2184,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): } }); // A sheet may hold more entities than a call takes arguments. - for (const element of elements(shownOf(layout.entities), onPaper, space)) parts.push(element); + const paperRun = layoutSources === undefined ? undefined : newRun("paper", layoutSources); + const onSheet = elements(shownOf(layout.entities), onPaper, space, undefined, paperRun); + if (paperRun === undefined) for (const element of onSheet) parts.push(element); + else parts.push({ ...paperRun, open: "\n ", between: "\n " }); const head = [ ``, ` `, @@ -1902,14 +2195,13 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ]; const tail = [` `, ``, ``]; if (!write([...head, ...tail].join("\n").length + 1)) refuse(space); - const held = defs.length > 0 ? [` ${defs.join("")}`] : []; - return [ - head[0], - ...held, - ...head.slice(1), - ...parts.map((part) => ` ${part}`), - ...tail, - ].join("\n"); + return finish([ + head[0]!, + defsPiece(), + `\n${head.slice(1).join("\n")}`, + ...parts.map((part) => (typeof part === "string" ? `\n ${part}` : part)), + `\n${tail.join("\n")}`, + ]); } // Each entity keeps its index in `drawing.entities`, for its element's data-entity. @@ -1951,15 +2243,23 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): : ` stroke-width="${fmt((stroke * Math.max(lineweight, 5)) / DEFAULT_LINEWEIGHT)}"` } vector-effect="non-scaling-stroke"`, }; - const body = elements(shown, onScreen, "model space").join("\n "); + const run = reading === undefined ? undefined : newRun("model", reading.model); + const body = elements(shown, onScreen, "model space", undefined, run).join("\n "); const head = [ ``, ` `, ]; const tail = [` `, ``, ``]; if (!write([...head, ...tail].join("\n").length + 1)) refuse("model space"); - const held = defs.length > 0 ? [` ${defs.join("")}`] : []; - return [head[0], ...held, ...head.slice(1), ` ${body}`, ...tail].join("\n"); + return finish([ + head[0]!, + defsPiece(), + `\n${head.slice(1).join("\n")}`, + run === undefined + ? `\n ${body}` + : { ...run, open: "\n ", between: "\n ", empty: "\n " }, + `\n${tail.join("\n")}`, + ]); } /** @@ -1970,6 +2270,13 @@ function precise(value: number): string { return String(Number(value.toPrecision(12))); } +/** The color a layer gives what draws ByLayer: its index, or the true color a read layer holds. */ +function layerShade(layer: Layer | undefined): number | Rgb { + const rgb = (layer as { readonly [LAYER_TRUE_COLOR]?: number } | undefined)?.[LAYER_TRUE_COLOR]; + if (typeof rgb === "number") return [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255]; + return layer?.color ?? 7; +} + /** * The color an index or a true color draws in: an index as `look` draws it, and a true color as it * is, which CAD programs plot under every plot style table. @@ -3930,9 +4237,14 @@ function rad(degrees: number): number { return (degrees * Math.PI) / 180; } +/** + * A value as XML holds it: its markup escaped, and each character XML cannot hold, a control + * character other than a tab or a line break, or a lone surrogate, which a file's text may hold, as + * U+FFFD. + */ function esc(value: string): string { return value.replace( - /[&<>"]/g, - (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] ?? c, + /[&<>"\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]|[\ud800-\udbff](?![\udc00-\udfff])|(? ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] ?? "\ufffd", ); } diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index d1cecb3..6aa34ad 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -1,7 +1,8 @@ // The DXF reader's fuzz: files bent group by group and byte by byte, each read under a time // limit. Each read gives a `DrawingRead` that `checkDrawingRead` passes, or a `ReadError`, and // nothing else; its answer stays within the command's size; and its document gives the file -// back byte for byte. test/read-fuzz.test.ts runs a fixed set of seeds. +// back byte for byte; and the picture of each space of a read with geometry is drawn, or refused +// with a RangeError, within its time. test/read-fuzz.test.ts runs a fixed set of seeds. // // The long pass, from new seeds and with any DXF files beside the core's own, under a memory // cap and with no core dump: @@ -19,6 +20,7 @@ import { } from "../src/index.ts"; import type { DxfDocument } from "../src/read/document.ts"; import { READ_LIMITS, readDXFDocument, readDXFWithin } from "../src/read/dxf.ts"; +import { readPictureWithin } from "../src/read/picture.ts"; import { timeLimit } from "./time-limit.ts"; /** A random number from 0 up to 1, the same for a seed. */ @@ -565,6 +567,9 @@ function within(ms: number, fn: () => T): T { return running.runInThisContext({ timeout: ms }) as T; } +/** The entities a fuzzed read's picture walks, of the 2,000,000 `toSVG` walks. */ +const PICTURE_WALK = 50_000; + /** The command's largest answer. */ const ANSWER = 128 * 1024 * 1024; @@ -590,8 +595,22 @@ export async function problemOf(bytes: Uint8Array, geometry: boolean): Promise ANSWER) return `its answer is ${json.length} characters`; - const problems = checkDrawingRead(JSON.parse(json)); + const parsed = JSON.parse(json) as DrawingRead; + const problems = checkDrawingRead(parsed); if (problems.length > 0) return problems.slice(0, 3).join("; "); + // Its picture: each space drawn, or refused with a RangeError, within its time. + if (geometry) { + for (const layout of [undefined, ...parsed.layouts.slice(0, 4).map((l) => l.name)]) { + const options = layout === undefined ? {} : { layout }; + try { + within(timeLimit(4000), () => readPictureWithin(parsed, options, PICTURE_WALK)); + } catch (error) { + if (!(error instanceof RangeError)) { + return `its picture of ${layout ?? "model space"} threw ${(error as Error).stack}`; + } + } + } + } const { document } = await both; let at = 0; for (let i = 0; i < document.count; i++) { diff --git a/test/read-picture.test.ts b/test/read-picture.test.ts new file mode 100644 index 0000000..6014e9a --- /dev/null +++ b/test/read-picture.test.ts @@ -0,0 +1,376 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import sheet, { images } from "../examples/site-plan.ts"; +import { timeLimit, within } from "./time-limit.ts"; +import { + createDrawing, + joinPicture, + readDXF, + readPicture, + svgToPDF, + toDXF, + toSVG, + type DrawingRead, + type PictureRun, +} from "../src/index.ts"; + +const read = await readDXF(toDXF(sheet), { geometry: true }); +const runsOf = (pieces: readonly unknown[]): PictureRun[] => + pieces.filter( + (p): p is PictureRun => typeof p === "object" && (p as PictureRun).kind === "fragments", + ); + +test("a read's picture joins back from its fragments, one for each entity that shows", () => { + for (const layout of [undefined, ...read.layouts.map((l) => l.name)]) { + const options = { images, ...(layout === undefined ? {} : { layout }) }; + const picture = readPicture(read, options); + assert.equal(joinPicture(picture.pieces, picture.defs), picture.svg); + assert.equal(toSVG(read, options), picture.svg); + for (const run of runsOf(picture.pieces)) { + // An entity's fragment holds all that was made of it: an insert and its attributes are one. + const handles = run.fragments.map((f) => f.handle); + assert.equal(new Set(handles).size, handles.length, `${layout} ${run.space} ${run.viewport}`); + assert.ok(handles.every((h) => h !== undefined)); + } + } + const sheetRuns = runsOf(readPicture(read, { images, layout: "C-101" }).pieces); + assert.deepEqual( + sheetRuns.map((run) => [run.space, run.viewport]), + [ + ["model", 0], + ["model", 1], + ["paper", undefined], + ], + ); + // The paper's fragments are in the order of the layout's entities, and each shows. + const paper = sheetRuns[2]!; + assert.deepEqual( + paper.fragments.map((f) => f.index), + read.layouts[0]!.entities!.map((_, i) => i), + ); +}); + +test("a fragment's ids are its own, so it keeps whatever is drawn around it", async () => { + const d = createDrawing({ units: "ft" }); + d.layer("FILL", { color: 3 }); + const loop = (x: number) => ({ + points: [ + [x, 0], + [x + 10, 0], + [x + 10, 10], + [x, 10], + ] as [number, number][], + }); + const gradient = { + name: "linear", + colors: [ + [255, 0, 0], + [0, 0, 255], + ], + } as const; + d.hatch([loop(0)], { gradient }); + d.hatch([loop(20)], { gradient }); + const both = await readDXF(toDXF(d.build()), { geometry: true }); + const picture = readPicture(both); + const [first, second] = runsOf(picture.pieces)[0]!.fragments; + assert.equal(first!.defs.length, 1); + assert.match(first!.defs[0]!, new RegExp(`^tsdraft-gradient-h${first!.handle}-`)); + // Drawn without the first, the second's fragment is the same. + const alone: DrawingRead = { + ...both, + model: { ...both.model, entities: both.model.entities!.slice(1) }, + }; + const again = runsOf(readPicture(alone).pieces)[0]!.fragments[0]!; + assert.equal( + again.svg!.replaceAll(/data-entity="\d+"/g, ""), + second!.svg!.replaceAll(/data-entity="\d+"/g, ""), + ); + assert.deepEqual(again.defs, second!.defs); +}); + +test("an xref at the top of a space is a run of its own, a fragment for each of its entities", () => { + // A host whose model space overlays the example's as the xref BASE, which a sheet shows. + const host: DrawingRead = { + ...read, + xrefs: [{ name: "BASE", path: "base.dwg", overlay: true }], + model: { + ...read.model, + entities: [ + { + kind: "insert", + handle: "F00", + layer: "0", + block: "BASE", + at: [0, 0], + scale: [1, 1], + rotation: 0, + tags: {}, + }, + ], + drawOrder: [], + }, + }; + for (const layout of [undefined, "C-101"]) { + const picture = readPicture(host, { images, xrefs: { BASE: read }, ...(layout && { layout }) }); + assert.equal(joinPicture(picture.pieces, picture.defs), picture.svg); + const run = runsOf(picture.pieces)[0]!; + assert.equal(run.fragments[0]!.handle, "F00"); + const xref = run.fragments[0]!.run!; + assert.equal(xref.xref, "BASE"); + // Each of the xref's entities that shows, by its handle in the xref's file. + const handles = xref.fragments.map((f) => f.handle); + assert.ok(handles.length > 50, `${handles.length}`); + assert.equal(new Set(handles).size, handles.length); + assert.ok(handles.every((h) => read.model.entities!.some((e) => e.handle === h))); + } +}); + +test("the notes count what a read keeps and the picture cannot draw as the file holds it", () => { + const firm: DrawingRead = { + ...read, + textStyles: read.textStyles.map((s) => + s.name === "Standard" ? { ...s, font: "romans2.shx" } : s, + ), + model: { ...read.model, other: { OLE2FRAME: 2 } }, + }; + const { notes } = readPicture(firm); + assert.deepEqual(notes.fonts, [ + { style: "Standard", font: "romans2.shx", drawnIn: "romans.shx" }, + ]); + assert.equal(notes.notDrawn["OLE2FRAME"], 2); +}); + +test("a value that is not a read is refused with a RangeError", () => { + assert.throws( + () => readPicture({ ...read, layers: 5 } as unknown as DrawingRead), + (error) => error instanceof RangeError && /not a DrawingRead/.test(error.message), + ); +}); + +test("an xref whose drawing is not given is counted, as it draws nothing", () => { + const host: DrawingRead = { ...read, xrefs: [{ name: "BASE", path: "base.dwg", overlay: true }] }; + assert.equal(readPicture(host).notes.notDrawn["an xref whose drawing is not given"], 1); + assert.equal( + readPicture(host, { xrefs: { BASE: read } }).notes.notDrawn[ + "an xref whose drawing is not given" + ], + undefined, + ); +}); + +test("an old leader's arrowhead is closed and filled, whatever its style's DIMBLK", () => { + const leader = { + kind: "leader", + handle: "F01", + layer: "0", + style: "Standard", + points: [ + [0, 0], + [5, 5], + [8, 5], + ], + shaft: "straight", + arrowhead: true, + } as const; + const dotted: DrawingRead = { + ...read, + dimensionStyles: [{ name: "Standard", annotative: false, arrowheadBlock: "_Dot" }], + model: { ...read.model, entities: [leader], drawOrder: [] }, + }; + const svg = readPicture(dotted).svg; + assert.doesNotMatch(svg, /]*data-part="arrowhead"/); + assert.match(svg, /data-part="arrowhead"/); +}); + +test("a handle the readers do not make keys nothing and scopes no id", () => { + // Hatches whose handles are long and of one length, which V8 hashes by their length alone, and + // one whose handle holds markup. + const long = (i: number) => "A".repeat(19_992) + String(i).padStart(8, "0"); + const base = read.model.entities!.find((e) => e.kind === "polyline")!; + const hatch = (handle: string) => ({ + kind: "hatch" as const, + handle, + layer: base.layer, + pattern: "SOLID", + solid: true, + style: "normal" as const, + loops: [ + { + points: [ + [0, 0], + [1, 0], + [1, 1], + ] as [number, number][], + flags: 1, + }, + ], + gradient: { name: "LINEAR", angle: 0, centered: true, colors: [0xff0000, 0x0000ff] }, + }); + const entities = [ + ...Array.from({ length: 2000 }, (_, i) => hatch(long(i))), + hatch('1"/>'), + ]; + const hostile: DrawingRead = { + ...read, + model: { ...read.model, entities, drawOrder: [long(0), long(1)] }, + }; + const picture = within(timeLimit(4000), () => readPicture(hostile)); + assert.doesNotMatch(picture.svg, /'), ]; + const hostile: DrawingRead = { ...read, model: { ...read.model, entities, drawOrder: [long(0), long(1)] }, }; + const picture = within(timeLimit(4000), () => readPicture(hostile)); assert.doesNotMatch(picture.svg, /